<commit_before>import { test } from 'tap';
import fs from 'fs';
import path from 'path';
import jsdom from 'jsdom';

const document = jsdom.jsdom(undefined, {
    virtualConsole: jsdom.createVirtualConsole().sendTo(console)
});
const window = document.defaultView;

global.document = document;
global.window = window;
global.navigator = window.navigator;

const treeData = Object.freeze(require('./fixtures/tree.json'));
const InfiniteTree = require('../src');

const getTreeElement = () => {
    while (document.body.firstChild) {
        document.body.removeChild(document.body.firstChild);
    }

    const el = document.createElement('div');
    el.setAttribute('id', 'tree');
    document.body.appendChild(el);

    return el;
};

test('Close all nodes on tree initialization', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    t.same(tree.nodes.length, 1);
    t.same(tree.rows.length, 1);
    t.end();
});

test('Open all nodes on tree initialization', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    t.same(tree.nodes.length, 12);
    t.same(tree.rows.length, 12);
    t.end();
});

test('It should generate expected output for empty result', (t) => {
    const el = getTreeElement();
    const options = {
        noDataClass: 'my-no-data-class',
        noDataText: 'My no data text'
    };
    const tree = new InfiniteTree(el, options);
    const innerHTML = `

${options.noDataText}

`;

    t.same(window.document.body.innerHTML, innerHTML);
    t.same(tree.nodes.length, 0);
    t.same(tree.rows.length, 0);
    t.end();
});

test('tree.clear', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    t.same(tree.nodes.length, 12);
    tree.clear();
    t.same(tree.nodes.length, 0);

    t.end();
});

test('tree.closeNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    let eventFiredCount = 0;

    tree.on('closeNode', (node) => {
        ++eventFiredCount;
    });

    t.same(tree.nodes.length, 12);
    tree.closeNode(tree.getNodeById('india'));
    t.same(tree.nodes.length, 11);
    tree.closeNode(tree.getNodeById('delta'));
    t.same(tree.nodes.length, 9);
    tree.closeNode(tree.getNodeById('hotel'));
    t.same(tree.nodes.length, 8);
    tree.closeNode(tree.getNodeById('charlie'));
    t.same(tree.nodes.length, 6);
    tree.closeNode(tree.getNodeById('bravo'));
    t.same(tree.nodes.length, 3);
    tree.closeNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.nodes.length, 1);

    // Check event fired count
    t.same(eventFiredCount, 5);

    t.end();
});

test('tree.flattenChildNodes', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    { // #1: Flatten all nodes within the tree
        const nodes = tree.flattenChildNodes();
        const wanted = tree.nodes;
        t.same(nodes, wanted);
    }

    { // #2: Flatten all child nodes of a node
        const node = tree.getNodeById('<root>');
        const nodes = tree.flattenChildNodes(node);
        const wanted = tree.nodes.slice(tree.nodes.indexOf(node) + 1);
        t.same(nodes, wanted);
    }

    t.end();
});

test('tree.flattenNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    { // #1: Flatten a node
        const node = tree.getNodeById('bravo');
        const nodes = tree.flattenNode(node);
        const wanted = tree.nodes.slice(tree.nodes.indexOf(node) + 0);
        t.same(nodes, wanted);
    }

    { // #2: Pass null as a parameter
        const nodes = tree.flattenNode(null);
        const wanted = [];
        t.same(nodes, wanted);
    }

    { // #3: Pass empty parameter
        const nodes = tree.flattenNode();
        const wanted = [];
        t.same(nodes, wanted);
    }

    t.end();
});

test('tree.getChildNodes', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        data: { ...treeData }
    });

    { // #1: Get child nodes of the root node
        const nodes = tree.getChildNodes().map((node) => {
            return {
                id: node.id,
                label: node.label,
                children: node.children,
                state: node.state
            };
        });
        const wanted = [
            tree.getNodeById('<root>')
        ].map((node) => {
            return {
                id: node.id,
                label: node.label,
                children: node.children,
                state: node.state
            };
        });
        t.same(nodes, wanted);
    }

    { // #2: Get child nodes of a node
        const node = tree.getNodeById('bravo');
        const nodes = tree.getChildNodes(node).map((node) => {
            return {
                id: node.id,
                label: node.label,
                children: node.children,
                state: node.state
            };
        });
        const wanted = [
            tree.getNodeById('charlie'),
            tree.getNodeById('hotel'),
            tree.getNodeById('kilo')
        ].map((node) => {
            return {
                id: node.id,
                label: node.label,
                children: node.children,
                state: node.state
            };
        });
        t.same(nodes, wanted);
    }

    t.end();
});

test('tree.getNodeById', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        data: { ...treeData }
    });

    const rootNode = tree.getNodeById('<root>');
    const noneNode = tree.getNodeById('none');

    t.same(rootNode.id, '<root>');
    t.same(noneNode, null);

    t.end();
});

test('tree.openNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    let eventFiredCount = 0;

    tree.on('openNode', (node) => {
        ++eventFiredCount;
    });

    t.same(tree.nodes.length, 1);
    tree.openNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.nodes.length, 3);
    tree.openNode(tree.getNodeById('bravo'));
    t.same(tree.nodes.length, 6);
    tree.openNode(tree.getNodeById('charlie'));
    t.same(tree.nodes.length, 8);
    tree.openNode(tree.getNodeById('hotel'));
    t.same(tree.nodes.length, 9);
    tree.openNode(tree.getNodeById('delta'));
    t.same(tree.nodes.length, 11);
    tree.openNode(tree.getNodeById('india'));
    t.same(tree.nodes.length, 12);

    // Check event fired count
    t.same(eventFiredCount, 5);

    t.end();
});

test('tree.selectNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    let eventFiredCount = 0;

    tree.on('selectNode', (node) => {
        ++eventFiredCount;
    });

    // Select Node
    t.same(tree.getSelectedNode(), null);
    tree.selectNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.getSelectedNode(), tree.getNodeById('<root>'));
    tree.selectNode(tree.getNodeById('bravo'));
    t.same(tree.getSelectedNode(), tree.getNodeById('bravo'));
    tree.selectNode(tree.getNodeById('charlie'));
    t.same(tree.getSelectedNode(), tree.getNodeById('charlie'));
    tree.selectNode(tree.getNodeById('hotel'));
    t.same(tree.getSelectedNode(), tree.getNodeById('hotel'));
    tree.selectNode(tree.getNodeById('delta'));
    t.same(tree.getSelectedNode(), tree.getNodeById('delta'));
    tree.selectNode(tree.getNodeById('india'));
    t.same(tree.getSelectedNode(), tree.getNodeById('india'));
    tree.selectNode(tree.getNodeById('juliet'));
    t.same(tree.getSelectedNode(), tree.getNodeById('juliet'));

    // Check event fired count
    t.same(eventFiredCount, 6);

    // Close Node
    tree.closeNode(tree.getNodeById('india'));
    t.same(tree.getSelectedNode(), tree.getNodeById('india'));
    tree.closeNode(tree.getNodeById('hotel'));
    t.same(tree.getSelectedNode(), tree.getNodeById('hotel'));
    tree.closeNode(tree.getNodeById('bravo'));
    t.same(tree.getSelectedNode(), tree.getNodeById('bravo'));
    tree.closeNode(tree.getNodeById('<root>'), { silent: true });
    t.same(tree.getSelectedNode(), tree.getNodeById('<root>'));

    // Check event fired count
    t.same(eventFiredCount, 6 + 3);

    t.end();
});

test('tree.toggleNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    let eventFiredCount = 0;

    tree.on('openNode', (node) => {
        ++eventFiredCount;
    });

    tree.on('closeNode', (node) => {
        ++eventFiredCount;
    });

    // Toggle Node
    t.same(tree.nodes.length, 1);
    tree.toggleNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.nodes.length, 3);
    tree.toggleNode(tree.getNodeById('bravo'));
    t.same(tree.nodes.length, 6);
    tree.toggleNode(tree.getNodeById('charlie'));
    t.same(tree.nodes.length, 8);
    tree.toggleNode(tree.getNodeById('hotel'));
    t.same(tree.nodes.length, 9);
    tree.toggleNode(tree.getNodeById('delta'));
    t.same(tree.nodes.length, 11);
    tree.toggleNode(tree.getNodeById('india'));
    t.same(tree.nodes.length, 12);
    tree.toggleNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.nodes.length, 1);

    // Check event fired count
    t.same(eventFiredCount, 5);

    t.end();
});

test('tree.toString', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    { // #1: Serialize the tree
        const found = tree.toString();
        const wanted = '[{"id":null,"label":"","children":[{"id":"<root>","label":"<root>","children":[],"state":{"depth":0,"open":false,"path":".0","prefixMask":"0","total":0}},{"id":"<root>","label":"<root>","children":[{"id":"bravo","label":"Bravo","children":[{"id":"charlie","label":"Charlie","children":[{"id":"delta","label":"Delta","children":[],"state":{"depth":3,"open":false,"path":".0.1.0.0","prefixMask":"0001","total":0,"selected":false}},{"id":"delta","label":"Delta","children":[],"state":{"depth":3,"open":false,"path":".0.1.0.0","prefixMask":"0001","total":0,"selected":false}}],"state":{"depth":2,"open":false,"path":".0.1.0","prefixMask":"000","total":0,"selected":false}},{"id":"charlie","label":"Charlie","children":[],"state":{"depth":2,"open":false,"path":".0.1.0","prefixMask":"000","total":0,"selected":false}}],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}},{"id":"bravo","label":"Bravo","children":[{"id":"hotel","label":"Hotel","children":[{"id":"india","label":"India","children":[],"state":{"depth":3,"open":false,"path":".0.1.1.0","prefixMask":"0001","total":0,"selected":false}}],"state":{"depth":2,"open":false,"path":".0.1.1","prefixMask":"000","total":0,"selected":false}}],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}},{"id":"bravo","label":"Bravo","children":[],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}}],"state":{"depth":0,"open":false,"path":".0","prefixMask":"0","total":0}}],"state":{"depth":-1,"open":true,"path":"","prefixMask":"","total":1}}]';
        t.same(found, wanted);
    }

    { // #2: Serialize a node
        const found = tree.toString(tree.getNodeById('bravo'));
        const wanted = '[{"id":"bravo","label":"Bravo","children":[{"id":"charlie","label":"Charlie","children":[{"id":"delta","label":"Delta","children":[],"state":{"depth":3,"open":false,"path":".0.1.0.0","prefixMask":"0001","total":0,"selected":false}},{"id":"delta","label":"Delta","children":[],"state":{"depth":3,"open":false,"path":".0.1.0.0","prefixMask":"0001","total":0,"selected":false}}],"state":{"depth":2,"open":false,"path":".0.1.0","prefixMask":"000","total":0,"selected":false}},{"id":"charlie","label":"Charlie","children":[],"state":{"depth":2,"open":false,"path":".0.1.0","prefixMask":"000","total":0,"selected":false}}],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}},{"id":"bravo","label":"Bravo","children":[{"id":"hotel","label":"Hotel","children":[{"id":"india","label":"India","children":[],"state":{"depth":3,"open":false,"path":".0.1.1.0","prefixMask":"0001","total":0,"selected":false}}],"state":{"depth":2,"open":false,"path":".0.1.1","prefixMask":"000","total":0,"selected":false}}],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}},{"id":"bravo","label":"Bravo","children":[],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}}]';
        t.same(found, wanted);
    }

    t.end();
});
<commit_msg>Add test: update<commit_after>import { test } from 'tap';
import fs from 'fs';
import path from 'path';
import jsdom from 'jsdom';

const document = jsdom.jsdom(undefined, {
    virtualConsole: jsdom.createVirtualConsole().sendTo(console)
});
const window = document.defaultView;

global.document = document;
global.window = window;
global.navigator = window.navigator;

const treeData = Object.freeze(require('./fixtures/tree.json'));
const InfiniteTree = require('../src');

const getTreeElement = () => {
    while (document.body.firstChild) {
        document.body.removeChild(document.body.firstChild);
    }

    const el = document.createElement('div');
    el.setAttribute('id', 'tree');
    document.body.appendChild(el);

    return el;
};

test('Close all nodes on tree initialization', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    t.same(tree.nodes.length, 1);
    t.same(tree.rows.length, 1);
    t.end();
});

test('Open all nodes on tree initialization', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    t.same(tree.nodes.length, 12);
    t.same(tree.rows.length, 12);
    t.end();
});

test('It should generate expected output for empty result', (t) => {
    const el = getTreeElement();
    const options = {
        noDataClass: 'my-no-data-class',
        noDataText: 'My no data text'
    };
    const tree = new InfiniteTree(el, options);
    const innerHTML = `

${options.noDataText}

`;

    t.same(window.document.body.innerHTML, innerHTML);
    t.same(tree.nodes.length, 0);
    t.same(tree.rows.length, 0);
    t.end();
});

test('tree.clear', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    t.same(tree.nodes.length, 12);
    tree.clear();
    t.same(tree.nodes.length, 0);

    t.end();
});

test('tree.closeNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    let eventFiredCount = 0;

    tree.on('closeNode', (node) => {
        ++eventFiredCount;
    });

    t.same(tree.nodes.length, 12);
    tree.closeNode(tree.getNodeById('india'));
    t.same(tree.nodes.length, 11);
    tree.closeNode(tree.getNodeById('delta'));
    t.same(tree.nodes.length, 9);
    tree.closeNode(tree.getNodeById('hotel'));
    t.same(tree.nodes.length, 8);
    tree.closeNode(tree.getNodeById('charlie'));
    t.same(tree.nodes.length, 6);
    tree.closeNode(tree.getNodeById('bravo'));
    t.same(tree.nodes.length, 3);
    tree.closeNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.nodes.length, 1);

    // Check event fired count
    t.same(eventFiredCount, 5);

    t.end();
});

test('tree.flattenChildNodes', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    { // #1: Flatten all nodes within the tree
        const nodes = tree.flattenChildNodes();
        const wanted = tree.nodes;
        t.same(nodes, wanted);
    }

    { // #2: Flatten all child nodes of a node
        const node = tree.getNodeById('<root>');
        const nodes = tree.flattenChildNodes(node);
        const wanted = tree.nodes.slice(tree.nodes.indexOf(node) + 1);
        t.same(nodes, wanted);
    }

    t.end();
});

test('tree.flattenNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    { // #1: Flatten a node
        const node = tree.getNodeById('bravo');
        const nodes = tree.flattenNode(node);
        const wanted = tree.nodes.slice(tree.nodes.indexOf(node) + 0);
        t.same(nodes, wanted);
    }

    { // #2: Pass null as a parameter
        const nodes = tree.flattenNode(null);
        const wanted = [];
        t.same(nodes, wanted);
    }

    { // #3: Pass empty parameter
        const nodes = tree.flattenNode();
        const wanted = [];
        t.same(nodes, wanted);
    }

    t.end();
});

test('tree.getChildNodes', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        data: { ...treeData }
    });

    { // #1: Get child nodes of the root node
        const nodes = tree.getChildNodes().map((node) => {
            return {
                id: node.id,
                label: node.label,
                children: node.children,
                state: node.state
            };
        });
        const wanted = [
            tree.getNodeById('<root>')
        ].map((node) => {
            return {
                id: node.id,
                label: node.label,
                children: node.children,
                state: node.state
            };
        });
        t.same(nodes, wanted);
    }

    { // #2: Get child nodes of a node
        const node = tree.getNodeById('bravo');
        const nodes = tree.getChildNodes(node).map((node) => {
            return {
                id: node.id,
                label: node.label,
                children: node.children,
                state: node.state
            };
        });
        const wanted = [
            tree.getNodeById('charlie'),
            tree.getNodeById('hotel'),
            tree.getNodeById('kilo')
        ].map((node) => {
            return {
                id: node.id,
                label: node.label,
                children: node.children,
                state: node.state
            };
        });
        t.same(nodes, wanted);
    }

    t.end();
});

test('tree.getNodeById', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        data: { ...treeData }
    });

    const rootNode = tree.getNodeById('<root>');
    const noneNode = tree.getNodeById('none');

    t.same(rootNode.id, '<root>');
    t.same(noneNode, null);

    t.end();
});

test('tree.openNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    let eventFiredCount = 0;

    tree.on('openNode', (node) => {
        ++eventFiredCount;
    });

    t.same(tree.nodes.length, 1);
    tree.openNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.nodes.length, 3);
    tree.openNode(tree.getNodeById('bravo'));
    t.same(tree.nodes.length, 6);
    tree.openNode(tree.getNodeById('charlie'));
    t.same(tree.nodes.length, 8);
    tree.openNode(tree.getNodeById('hotel'));
    t.same(tree.nodes.length, 9);
    tree.openNode(tree.getNodeById('delta'));
    t.same(tree.nodes.length, 11);
    tree.openNode(tree.getNodeById('india'));
    t.same(tree.nodes.length, 12);

    // Check event fired count
    t.same(eventFiredCount, 5);

    t.end();
});

test('tree.selectNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    let eventFiredCount = 0;

    tree.on('selectNode', (node) => {
        ++eventFiredCount;
    });

    // Select Node
    t.same(tree.getSelectedNode(), null);
    tree.selectNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.getSelectedNode(), tree.getNodeById('<root>'));
    tree.selectNode(tree.getNodeById('bravo'));
    t.same(tree.getSelectedNode(), tree.getNodeById('bravo'));
    tree.selectNode(tree.getNodeById('charlie'));
    t.same(tree.getSelectedNode(), tree.getNodeById('charlie'));
    tree.selectNode(tree.getNodeById('hotel'));
    t.same(tree.getSelectedNode(), tree.getNodeById('hotel'));
    tree.selectNode(tree.getNodeById('delta'));
    t.same(tree.getSelectedNode(), tree.getNodeById('delta'));
    tree.selectNode(tree.getNodeById('india'));
    t.same(tree.getSelectedNode(), tree.getNodeById('india'));
    tree.selectNode(tree.getNodeById('juliet'));
    t.same(tree.getSelectedNode(), tree.getNodeById('juliet'));

    // Check event fired count
    t.same(eventFiredCount, 6);

    // Close Node
    tree.closeNode(tree.getNodeById('india'));
    t.same(tree.getSelectedNode(), tree.getNodeById('india'));
    tree.closeNode(tree.getNodeById('hotel'));
    t.same(tree.getSelectedNode(), tree.getNodeById('hotel'));
    tree.closeNode(tree.getNodeById('bravo'));
    t.same(tree.getSelectedNode(), tree.getNodeById('bravo'));
    tree.closeNode(tree.getNodeById('<root>'), { silent: true });
    t.same(tree.getSelectedNode(), tree.getNodeById('<root>'));

    // Check event fired count
    t.same(eventFiredCount, 6 + 3);

    t.end();
});

test('tree.toggleNode', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    let eventFiredCount = 0;

    tree.on('openNode', (node) => {
        ++eventFiredCount;
    });

    tree.on('closeNode', (node) => {
        ++eventFiredCount;
    });

    // Toggle Node
    t.same(tree.nodes.length, 1);
    tree.toggleNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.nodes.length, 3);
    tree.toggleNode(tree.getNodeById('bravo'));
    t.same(tree.nodes.length, 6);
    tree.toggleNode(tree.getNodeById('charlie'));
    t.same(tree.nodes.length, 8);
    tree.toggleNode(tree.getNodeById('hotel'));
    t.same(tree.nodes.length, 9);
    tree.toggleNode(tree.getNodeById('delta'));
    t.same(tree.nodes.length, 11);
    tree.toggleNode(tree.getNodeById('india'));
    t.same(tree.nodes.length, 12);
    tree.toggleNode(tree.getNodeById('<root>'), { silent: true }); // Prevent event from being triggered
    t.same(tree.nodes.length, 1);

    // Check event fired count
    t.same(eventFiredCount, 5);

    t.end();
});

test('tree.toString', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    { // #1: Serialize the tree
        const found = tree.toString();
        const wanted = '[{"id":null,"label":"","children":[{"id":"<root>","label":"<root>","children":[],"state":{"depth":0,"open":false,"path":".0","prefixMask":"0","total":0}},{"id":"<root>","label":"<root>","children":[{"id":"bravo","label":"Bravo","children":[{"id":"charlie","label":"Charlie","children":[{"id":"delta","label":"Delta","children":[],"state":{"depth":3,"open":false,"path":".0.1.0.0","prefixMask":"0001","total":0,"selected":false}},{"id":"delta","label":"Delta","children":[],"state":{"depth":3,"open":false,"path":".0.1.0.0","prefixMask":"0001","total":0,"selected":false}}],"state":{"depth":2,"open":false,"path":".0.1.0","prefixMask":"000","total":0,"selected":false}},{"id":"charlie","label":"Charlie","children":[],"state":{"depth":2,"open":false,"path":".0.1.0","prefixMask":"000","total":0,"selected":false}}],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}},{"id":"bravo","label":"Bravo","children":[{"id":"hotel","label":"Hotel","children":[{"id":"india","label":"India","children":[],"state":{"depth":3,"open":false,"path":".0.1.1.0","prefixMask":"0001","total":0,"selected":false}}],"state":{"depth":2,"open":false,"path":".0.1.1","prefixMask":"000","total":0,"selected":false}}],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}},{"id":"bravo","label":"Bravo","children":[],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}}],"state":{"depth":0,"open":false,"path":".0","prefixMask":"0","total":0}}],"state":{"depth":-1,"open":true,"path":"","prefixMask":"","total":1}}]';
        t.same(found, wanted);
    }

    { // #2: Serialize a node
        const found = tree.toString(tree.getNodeById('bravo'));
        const wanted = '[{"id":"bravo","label":"Bravo","children":[{"id":"charlie","label":"Charlie","children":[{"id":"delta","label":"Delta","children":[],"state":{"depth":3,"open":false,"path":".0.1.0.0","prefixMask":"0001","total":0,"selected":false}},{"id":"delta","label":"Delta","children":[],"state":{"depth":3,"open":false,"path":".0.1.0.0","prefixMask":"0001","total":0,"selected":false}}],"state":{"depth":2,"open":false,"path":".0.1.0","prefixMask":"000","total":0,"selected":false}},{"id":"charlie","label":"Charlie","children":[],"state":{"depth":2,"open":false,"path":".0.1.0","prefixMask":"000","total":0,"selected":false}}],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}},{"id":"bravo","label":"Bravo","children":[{"id":"hotel","label":"Hotel","children":[{"id":"india","label":"India","children":[],"state":{"depth":3,"open":false,"path":".0.1.1.0","prefixMask":"0001","total":0,"selected":false}}],"state":{"depth":2,"open":false,"path":".0.1.1","prefixMask":"000","total":0,"selected":false}}],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}},{"id":"bravo","label":"Bravo","children":[],"state":{"depth":1,"open":false,"path":".0.1","prefixMask":"00","total":0,"selected":false}}]';
        t.same(found, wanted);
    }

    t.end();
});

test('tree.update', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    let eventFiredCount = 0;

    tree.on('contentWillUpdate', () => {
        ++eventFiredCount;
    });
    tree.on('contentDidUpdate', () => {
        ++eventFiredCount;
    });

    tree.update();
    t.same(eventFiredCount, 2);

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


<commit_before>var test = require('tape'),
 codes = require('../')

test('lookup project codes', function (t) {
  t.plan(4)

  // projected codes
  var proj = codes.lookup(3857)
  t.equal(proj.name, 'WGS_1984_Web_Mercator_Auxiliary_Sphere')

  // // geographic codes
  proj = codes.lookup(3819)
  t.equal(proj.name, 'GCS_HD1909')

  // vertical code
  proj = codes.lookup(6359)
  t.equal(proj.name, 'NGVD29_depth')

  // undefined proj code
  proj = codes.lookup(3333333)
  t.equal(proj, undefined)
})
<commit_msg>tests!<commit_after>var test = require('tape'),
 codes = require('../')

test('lookup project codes', function (t) {
  t.plan(6)

  // projected codes
  var proj = codes.lookup(3857)
  t.equal(proj.name, 'WGS_1984_Web_Mercator_Auxiliary_Sphere')

  // geographic codes
  proj = codes.lookup(3819)
  t.equal(proj.name, 'GCS_HD1909')

  // vertical code
  proj = codes.lookup(6359)
  t.equal(proj.name, 'NGVD29_depth')

  // transformation code
  proj = codes.lookup(1226)
  t.equal(proj.name, 'Schwarzeck_To_WGS_1984')

  // vertical transformation code
  proj = codes.lookup(110043)
  t.equal(proj.name, 'NGVD29_To_NAVD88_USFT_HARN_ECW')

  // undefined proj code
  proj = codes.lookup(3333333)
  t.equal(proj, undefined)
})
<|endoftext|>


<commit_before>var Lab = require('lab');
var Hapi = require('hapi');

var expect = Lab.expect;
var before = Lab.before;
var after = Lab.after;
var describe = Lab.experiment;
var it = Lab.test;

describe('Bearer', function () {

    var basicHandler = function (request, reply) {
        reply('ok');
    };

    var server = new Hapi.Server({ debug: false });
    before(function (done) {
        server.pack.register(require('../'), function (err) {
            expect(err).to.not.exist;

            server.auth.strategy('default', 'bearer-access-token', true, {
                validateFunc: function(token, callback) {
                    return callback(null, token==="12345678",  { token: token });
                }
            });

            server.route([
                { method: 'POST', path: '/basic', handler: basicHandler, config: { auth: 'default' } },
                { method: 'POST', path: '/basic_default_auth', handler: basicHandler, config: { } }
            ]);

            done();
        });
    });

    it('returns a reply on successful auth with auth bearer set', function (done) {

        var request = { method: 'POST', url: '/basic', headers: { authorization: "Bearer 12345678" } };

        server.inject(request, function (res) {
            expect(res.result).to.exist;
            expect(res.result).to.equal('ok');
            done();
        });
    });

    it('returns a reply on successful auth with access_token set', function (done) {

        var request = { method: 'POST', url: '/basic?access_token=12345678' };

        server.inject(request, function (res) {
            expect(res.result).to.exist;
            expect(res.result).to.equal('ok');
            done();
        });
    });

    it('returns an error when auth is set to required by default', function (done) {

        var request = { method: 'POST', url: '/basic_default_auth' };

        server.inject(request, function (res) {
            expect(res.result).to.exist;
            expect(res.statusCode).to.equal(401);
            done();
        });
    });

    it('returns an error with wrong scheme', function (done) {

        var request = { method: 'POST', url: '/basic', headers: { authorization: 'definitelynotacorrecttoken' } };

        server.inject(request, function (res) {

            expect(res.statusCode).to.equal(401);
            done();
        });
    });

    it('returns an error with incorrect strategy', function (done) {

        server.auth.strategy('default_2', 'bearer-access-token', {
            validateFunc: function(token, callback) {
                return callback(null, false, { token: token });
            }
        });

        server.route([
            { method: 'POST', path: '/basic_default_2', handler: basicHandler, config: { auth: 'default_2' } }
        ]);

        var request = { method: 'POST', url: '/basic', headers: { authorization: 'Bearer {test: 1}' } };

        server.inject(request, function (res) {

            expect(res.statusCode).to.equal(400);
            done();
        });
    });

    it('it handles when strategy returns an error to validateFunc', function (done) {

        server.auth.strategy('default_3', 'bearer-access-token', {
            validateFunc: function(token, callback) {
                return callback({'Error':'Error'}, false, null);
            }
        });

        server.route([
            { method: 'GET', path: '/basic_default_3', handler: basicHandler, config: { auth: 'default_3' } }
        ]);

        var request = { method: 'GET', url: '/basic_default_3', headers: { authorization: 'Bearer 12345678' } };

        server.inject(request, function (res) {
            expect(res.statusCode).to.equal(200);
            done();
        });
    });

    it('it handles when isValid is false passed to validateFunc', function (done) {

        server.auth.strategy('default_4', 'bearer-access-token', {
            validateFunc: function(token, callback) {
                return callback(null, false, null);
            }
        });

        server.route([
            { method: 'GET', path: '/basic_default_4', handler: basicHandler, config: { auth: 'default_4' } }
        ]);

        var request = { method: 'GET', url: '/basic_default_4', headers: { authorization: 'Bearer 12345678' } };

        server.inject(request, function (res) {
            expect(res.statusCode).to.equal(401);
            done();
        });
    });

    it('it handles when no credentials passed to validateFunc', function (done) {

        server.auth.strategy('default_5', 'bearer-access-token', {
            validateFunc: function(token, callback) {
                return callback(null, true, null);
            }
        });

        server.route([
            { method: 'GET', path: '/basic_default_5', handler: basicHandler, config: { auth: 'default_5' } }
        ]);

        var request = { method: 'GET', url: '/basic_default_5', headers: { authorization: 'Bearer 12345678' } };

        server.inject(request, function (res) {
            expect(res.statusCode).to.equal(500);
            done();
        });
    });
});
<commit_msg>Test for a renamed access token param<commit_after>var Lab = require('lab');
var Hapi = require('hapi');

var expect = Lab.expect;
var before = Lab.before;
var after = Lab.after;
var describe = Lab.experiment;
var it = Lab.test;

describe('Bearer', function () {

    var basicHandler = function (request, reply) {
        reply('ok');
    };

    var server = new Hapi.Server({ debug: false });
    before(function (done) {
        server.pack.register(require('../'), function (err) {
            expect(err).to.not.exist;

            server.auth.strategy('default', 'bearer-access-token', true, {
                validateFunc: function(token, callback) {
                    return callback(null, token==="12345678",  { token: token });
                }
            });

            server.route([
                { method: 'POST', path: '/basic', handler: basicHandler, config: { auth: 'default' } },
                { method: 'POST', path: '/basic_default_auth', handler: basicHandler, config: { } }
            ]);

            done();
        });
    });

    it('returns a reply on successful auth with auth bearer set', function (done) {

        var request = { method: 'POST', url: '/basic', headers: { authorization: "Bearer 12345678" } };

        server.inject(request, function (res) {
            expect(res.result).to.exist;
            expect(res.result).to.equal('ok');
            done();
        });
    });

    it('returns a reply on successful auth with access_token set', function (done) {

        var request = { method: 'POST', url: '/basic?access_token=12345678' };

        server.inject(request, function (res) {
            expect(res.result).to.exist;
            expect(res.result).to.equal('ok');
            done();
        });
    });

    it('returns an error when auth is set to required by default', function (done) {

        var request = { method: 'POST', url: '/basic_default_auth' };

        server.inject(request, function (res) {
            expect(res.result).to.exist;
            expect(res.statusCode).to.equal(401);
            done();
        });
    });

    it('returns an error with wrong scheme', function (done) {

        var request = { method: 'POST', url: '/basic', headers: { authorization: 'definitelynotacorrecttoken' } };

        server.inject(request, function (res) {

            expect(res.statusCode).to.equal(401);
            done();
        });
    });

    it('returns an error with incorrect strategy', function (done) {

        server.auth.strategy('default_2', 'bearer-access-token', {
            validateFunc: function(token, callback) {
                return callback(null, false, { token: token });
            }
        });

        server.route([
            { method: 'POST', path: '/basic_default_2', handler: basicHandler, config: { auth: 'default_2' } }
        ]);

        var request = { method: 'POST', url: '/basic', headers: { authorization: 'Bearer {test: 1}' } };

        server.inject(request, function (res) {

            expect(res.statusCode).to.equal(400);
            done();
        });
    });

    it('it handles when strategy returns an error to validateFunc', function (done) {

        server.auth.strategy('default_3', 'bearer-access-token', {
            validateFunc: function(token, callback) {
                return callback({'Error':'Error'}, false, null);
            }
        });

        server.route([
            { method: 'GET', path: '/basic_default_3', handler: basicHandler, config: { auth: 'default_3' } }
        ]);

        var request = { method: 'GET', url: '/basic_default_3', headers: { authorization: 'Bearer 12345678' } };

        server.inject(request, function (res) {
            expect(res.statusCode).to.equal(200);
            done();
        });
    });

    it('it handles when isValid is false passed to validateFunc', function (done) {

        server.auth.strategy('default_4', 'bearer-access-token', {
            validateFunc: function(token, callback) {
                return callback(null, false, null);
            }
        });

        server.route([
            { method: 'GET', path: '/basic_default_4', handler: basicHandler, config: { auth: 'default_4' } }
        ]);

        var request = { method: 'GET', url: '/basic_default_4', headers: { authorization: 'Bearer 12345678' } };

        server.inject(request, function (res) {
            expect(res.statusCode).to.equal(401);
            done();
        });
    });

    it('it handles when no credentials passed to validateFunc', function (done) {

        server.auth.strategy('default_5', 'bearer-access-token', {
            validateFunc: function(token, callback) {
                return callback(null, true, null);
            }
        });

        server.route([
            { method: 'GET', path: '/basic_default_5', handler: basicHandler, config: { auth: 'default_5' } }
        ]);

        var request = { method: 'GET', url: '/basic_default_5', headers: { authorization: 'Bearer 12345678' } };

        server.inject(request, function (res) {
            expect(res.statusCode).to.equal(500);
            done();
        });
    });

        it('returns a reply on successful auth with access_token renamed and set', function (done) {

        var server = new Hapi.Server({ debug: false });
        var accessTokenName = "my_access_token";

        server.pack.register(require('../'), function (err) {

            expect(err).to.not.exist;

            server.auth.strategy('default', 'bearer-access-token', true, {
                validateFunc: function(token, callback) {
                    return callback(null, token==="12345678",  { token: token });
                },
                accessTokenName: "my_access_token"
            });

            server.route([
                { method: 'POST', path: '/basic', handler: basicHandler, config: { auth: 'default' } }
            ]);

        });

        var request = { method: 'POST', url: '/basic?my_access_token=12345678' };

        server.inject(request, function (res) {
            expect(res.result).to.exist;
            expect(res.result).to.equal('ok');
            done();
        });
    });
});
<|endoftext|>


<commit_before>import chai from 'chai'

import { routeFromUrlHelper, urlFromRouteHelper } from '../src/index'

let routeFromUrl
let urlFromRoute

describe('routeFromUrl', () => {
  beforeEach(() => {
    const routes = [
      '/fruits/:fruitId',
      '/fruits/:fruitId/veggies/:veggieId/meats/:meatId',
    ]
    routeFromUrl = routeFromUrlHelper(routes)
  })

  it('matches nothing', () => {
    const url = '/grains/rice'
    const actualRoute = routeFromUrl(url)
    const expectedRoute = {}
    chai.assert.deepEqual(expectedRoute, actualRoute)
  })

  it('matches a single value', () => {
    const url = '/fruits/apple'
    const actualRoute = routeFromUrl(url)
    const expectedRoute = { fruitId: 'apple' }
    chai.assert.deepEqual(expectedRoute, actualRoute)
  })

  it('matches multiple values', () => {
    const url = '/fruits/apple/veggies/celery/meats/pork'
    const actualRoute = routeFromUrl(url)
    const expectedRoute = { fruitId: 'apple', veggieId: 'celery', meatId: 'pork' }
    chai.assert.deepEqual(expectedRoute, actualRoute)
  })

  it('matches when trailing slash is present', () => {
    const url = '/fruits/apple/'
    const actualRoute = routeFromUrl(url)
    const expectedRoute = { fruitId: 'apple' }
    chai.assert.deepEqual(expectedRoute, actualRoute)
  })
})

describe('urlFromRoute', () => {
  beforeEach(() => {
    const routes = [
      '/fruits/:fruitId',
      '/fruits/:fruitId/veggies/:veggieId/meats/:meatId',
    ]
    urlFromRoute = urlFromRouteHelper(routes)
  })

  it('reverses nothing', () => {
    const route = {}
    const actualUrl = urlFromRoute(route)
    const expectedUrl = undefined
    chai.assert.equal(expectedUrl, actualUrl)
  })

  it('reverses a single value', () => {
    const route = { fruitId: 'apple' }
    const actualUrl = urlFromRoute(route)
    const expectedUrl = '/fruits/apple'
    chai.assert.equal(expectedUrl, actualUrl)
  })

  it('reverses multiple values', () => {
    const route = { fruitId: 'apple', veggieId: 'celery', meatId: 'pork' }
    const actualUrl = urlFromRoute(route)
    const expectedUrl = '/fruits/apple/veggies/celery/meats/pork'
    chai.assert.equal(expectedUrl, actualUrl)
  })

  it('reverses and omits keys with undefined values', () => {
    const route = { fruitId: 'apple', veggieId: undefined, meatId: undefined }
    const actualUrl = urlFromRoute(route)
    const expectedUrl = '/fruits/apple'
    chai.assert.equal(expectedUrl, actualUrl)
  })

  it('reverses and omits keys with null values', () => {
    const route = { fruitId: 'apple', veggieId: null, meatId: null }
    const actualUrl = urlFromRoute(route)
    const expectedUrl = '/fruits/apple'
    chai.assert.equal(expectedUrl, actualUrl)
  })
})
<commit_msg>Improve clarity of partial match treatment in tests<commit_after>import chai from 'chai'

import { routeFromUrlHelper, urlFromRouteHelper } from '../src/index'

let routeFromUrl
let urlFromRoute

describe('routeFromUrl', () => {
  beforeEach(() => {
    const routes = [
      '/fruits/:fruitId',
      '/fruits/:fruitId/veggies/:veggieId/meats/:meatId',
    ]
    routeFromUrl = routeFromUrlHelper(routes)
  })

  it('matches nothing', () => {
    const url = '/grains/rice'
    const actualRoute = routeFromUrl(url)
    const expectedRoute = {}
    chai.assert.deepEqual(expectedRoute, actualRoute)
  })

  it('matches a single value', () => {
    const url = '/fruits/apple'
    const actualRoute = routeFromUrl(url)
    const expectedRoute = { fruitId: 'apple' }
    chai.assert.deepEqual(expectedRoute, actualRoute)
  })

  it('matches multiple values', () => {
    const url = '/fruits/apple/veggies/celery/meats/pork'
    const actualRoute = routeFromUrl(url)
    const expectedRoute = { fruitId: 'apple', veggieId: 'celery', meatId: 'pork' }
    chai.assert.deepEqual(expectedRoute, actualRoute)
  })

  it('matches when trailing slash is present', () => {
    const url = '/fruits/apple/'
    const actualRoute = routeFromUrl(url)
    const expectedRoute = { fruitId: 'apple' }
    chai.assert.deepEqual(expectedRoute, actualRoute)
  })

  // This is a little weird and heavy handed but the library is meant to be
  // super simple so I don't want there to be any ambiguity about what order
  // matches happen in, etc.
  describe ('partial match is possible', () => {
    beforeEach(() => {
      // Note: the order here is what makes a partial match possible, but we're
      // testing that only full matches match.
      const routes = [
        '/fruits/:fruitId/veggies/:veggieId/meats/:meatId',
        '/fruits/:fruitId',
      ]
      routeFromUrl = routeFromUrlHelper(routes)
    })

    it('matches the full URL only', () => {
      const url = '/fruits/apple'
      const actualRoute = routeFromUrl(url)
      const expectedRoute = { fruitId: 'apple' }
      chai.assert.deepEqual(expectedRoute, actualRoute)
    })
  })
})

describe('urlFromRoute', () => {
  beforeEach(() => {
    const routes = [
      '/fruits/:fruitId',
      '/fruits/:fruitId/veggies/:veggieId/meats/:meatId',
    ]
    urlFromRoute = urlFromRouteHelper(routes)
  })

  it('reverses nothing', () => {
    const route = {}
    const actualUrl = urlFromRoute(route)
    const expectedUrl = undefined
    chai.assert.equal(expectedUrl, actualUrl)
  })

  it('reverses a single value', () => {
    const route = { fruitId: 'apple' }
    const actualUrl = urlFromRoute(route)
    const expectedUrl = '/fruits/apple'
    chai.assert.equal(expectedUrl, actualUrl)
  })

  it('reverses multiple values', () => {
    const route = { fruitId: 'apple', veggieId: 'celery', meatId: 'pork' }
    const actualUrl = urlFromRoute(route)
    const expectedUrl = '/fruits/apple/veggies/celery/meats/pork'
    chai.assert.equal(expectedUrl, actualUrl)
  })

  it('reverses and omits keys with undefined values', () => {
    const route = { fruitId: 'apple', veggieId: undefined, meatId: undefined }
    const actualUrl = urlFromRoute(route)
    const expectedUrl = '/fruits/apple'
    chai.assert.equal(expectedUrl, actualUrl)
  })

  it('reverses and omits keys with null values', () => {
    const route = { fruitId: 'apple', veggieId: null, meatId: null }
    const actualUrl = urlFromRoute(route)
    const expectedUrl = '/fruits/apple'
    chai.assert.equal(expectedUrl, actualUrl)
  })
})
<|endoftext|>


<commit_before>/*
Copyright Jesus Perez <jesusprubio gmail com>
          Sergio García <s3rgio.gr gmail com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

// Private stuff

var namiLib = require('nami'),
    Nami    = namiLib.Nami,

    HELP = {
        description : 'Use the Asterisk Manager service (AMI) to get the value of a setup variable',
        options     : {
            target : {
                type : 'ip',
                description  : 'IP address to brute-force',
                defaultValue : '127.0.0.1'
            },
            port : {
                type         : 'port',
                description  : 'Port of the server',
                defaultValue : 5038
            },
            user : {
                type         : 'allValid',
                description  : 'User to use in the request',
                defaultValue : 'admin'
            },
            password : {
                type         : 'allValid',
                description  : 'Password to use in the request',
                defaultValue : 'amp111'
            },
            channel : {
                type         : 'allValid',
                description  : 'Channel to use in the request',
                defaultValue : 'SIP/100@default'
            },
            variable : {
                type         : 'allValid',
                description  : 'Name of the variable to get',
                defaultValue : 'extension'
            },
            timeout : {
                type         : 'positiveInt',
                description  : 'Time to wait for a response (ms.)',
                defaultValue : 5000
            }
        }
    };

// Public stuff

module.exports.help = HELP;

module.exports.run = function (options, callback) {
    var connected = false,
        ami       = new Nami({
            host     : options.target,
            port     : options.port,
            username : options.user,
            secret   : options.password
        });

    ami.logger.setLevel('OFF');

    ami.on('namiConnected', function () {
        var action = new namiLib.Actions.GetVar();

        action.channel = options.channel;
        action.variable = options.variable;
        connected = true;
        ami.send(action, function (res) {
            ami.close();
            callback(null, res);
        });
    });

    ami.on('namiLoginIncorrect', function () {
        callback({
            type : 'login'
        });
    });

    // The module does not support connection timeout, so
    // we add it manually ("connected" var), really dirty trick
    setTimeout(function () {
        if (!connected) {
            callback({
                type : 'timeout'
            });
        }
    }, options.timeout);
    ami.open();
};
<commit_msg>Style changed.<commit_after>// Copyright Jesus Perez <jesusprubio gmail com>
//           Sergio Garcia <s3rgio.gr gmail com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

'use strict';

const namiLib = require('nami');

const Nami = namiLib.Nami;

module.exports.help = {
  description: 'Use the Asterisk Manager service (AMI) to get the value of a setup variable',
  options: {
    target: {
      type: 'ip',
      description: 'IP address to brute-force',
      defaultValue: '127.0.0.1',
    },
    port: {
      type: 'port',
      description: 'Port of the server',
      defaultValue: 5038,
    },
    user: {
      type: 'allValid',
      description: 'User to use in the request',
      defaultValue: 'admin',
    },
    password: {
      type: 'allValid',
      description: 'Password to use in the request',
      defaultValue: 'amp111',
    },
    channel: {
      type: 'allValid',
      description: 'Channel to use in the request',
      defaultValue: 'SIP/100@default',
    },
    variable: {
      type: 'allValid',
      description: 'Name of the variable to get',
      defaultValue: 'extension',
    },
    timeout: {
      type: 'positiveInt',
      description: 'Time to wait for a response (ms.)',
      defaultValue: 5000,
    },
  },
};

module.exports.run = (options, callback) => {
  let connected = false;
  const ami = new Nami({
    host: options.target,
    port: options.port,
    username: options.user,
    secret: options.password,
  });

  ami.logger.setLevel('OFF');

  ami.on('namiConnected', () => {
    const action = new namiLib.Actions.GetVar();

    action.channel = options.channel;
    action.variable = options.variable;
    connected = true;
    ami.send(action, res => {
      ami.close();
      callback(null, res);
    });
  });

  ami.on('namiLoginIncorrect', () => {
    callback({
      type: 'login',
    });
  });

  // The module does not support connection timeout, so
  // we add it manually ("connected" var), really dirty trick
  setTimeout(() => {
    if (!connected) {
      callback({
        type: 'timeout',
      });
    }
  }, options.timeout);
  ami.open();
};
<|endoftext|>


<commit_before>/**
 * node-archiver
 *
 * Copyright (c) 2012-2013 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/ctalkington/node-archiver/blob/master/LICENSE-MIT
 */

var inherits = require('util').inherits;
var Transform = require('stream').Transform || require('readable-stream').Transform;

var headers = require('./headers');
var util = require('../../util');
var DeflateRawChecksum = require('../../util/DeflateRawChecksum');
var ChecksumStream = require('../../util/ChecksumStream');

var Zip = module.exports = function(options) {
  options = this.options = util.defaults(options, {
    comment: '',
    forceUTC: false,
    zlib: {
      level: 1
    }
  });

  Transform.call(this, options);

  if (options.level && options.level >= 0) {
    options.zlib.level = options.level;
    delete options.level;
  }

  this.offset = 0;
  this.files = [];
};

inherits(Zip, Transform);

Zip.prototype._normalizeFileData = function(data) {
  data = util.defaults(data, {
    name: null,
    date: null,
    store: false,
    comment: ''
  });

  data.name = util.sanitizeFilePath(data.name);
  data.date = util.dateify(data.date);

  if (typeof data.lastModifiedDate !== 'number') {
    data.lastModifiedDate = util.dosDateTime(data.date, this.options.forceUTC);
  }

  if (this.options.zlib && this.options.zlib.level === 0) {
    data.store = true;
  }

  data.flags = (1<<3) | (1<<11);
  data.compressionMethod = data.store ? 0 : 8;
  data.uncompressedSize = 0;
  data.compressedSize = 0;

  return data;
};

Zip.prototype._transform = function(chunk, encoding, callback) {
  callback(null, chunk);
};

Zip.prototype._writeCentralDirectory = function() {
  var files = this.files;
  var comment = this.options.comment;
  var cdoffset = this.offset;
  var cdsize = 0;

  var centralDirectoryBuffer;
  for (var i = 0; i < files.length; i++) {
    var file = files[i];

    centralDirectoryBuffer = headers.encode('centralDirectory', file);
    this.write(centralDirectoryBuffer);
    cdsize += centralDirectoryBuffer.length;
  }

  var centralDirectoryFooterData = {
    directoryRecordsDisk: files.length,
    directoryRecords: files.length,
    centralDirectorySize: cdsize,
    centralDirectoryOffset: cdoffset,
    comment: comment
  };

  this.write(headers.encode('centralFooter', centralDirectoryFooterData));
};

Zip.prototype.append = function(source, data, callback) {
  var self = this;
  var file;

  data = file = self._normalizeFileData(data);
  file.offset = self.offset;

  self.write(headers.encode('file', file));

  var deflate;
  var checksumr;

  function onend() {
    self.write(headers.encode('fileDescriptor', file));

    self.files.push(file);

    callback(null, file);
  }

  if (file.store === false) {
    deflate = new DeflateRawChecksum(self.options.zlib);

    deflate.on('error', callback);

    deflate.on('end', function() {
      file.crc32 = deflate.digest;
      file.uncompressedSize = deflate.rawSize;
      file.compressedSize = deflate.compressedSize;

      onend();
    });

    // archiver and deflate are having disagreements
    // over piping at this point in time so archiver
    // had to be the adult and move on with hopes of
    // making up in the future :) - 20130818
    // deflate.pipe(self, { end: false });

    deflate.on('data', function(data) {
      self.write(data);
    });
  } else {
    checksumr = new ChecksumStream();

    checksumr.on('error', callback);

    checksumr.on('end', function () {
      file.uncompressedSize = checksumr.rawSize;
      file.compressedSize = checksumr.rawSize;
      file.crc32 = checksumr.digest;

      onend();
    });

    checksumr.pipe(self, { end: false });
  }

  if (file.sourceType === 'buffer') {
    if (file.store) {
      file.uncompressedSize += source.length;
      file.compressedSize = file.uncompressedSize;
      file.crc32 = util.crc32(source).digest();

      self.write(source);
      onend();
    } else {
      deflate.end(source);
    }
  } else if (file.sourceType === 'stream') {
    if (file.store) {
      source.pipe(checksumr);
    } else {
      source.pipe(deflate);
    }
  }
};

Zip.prototype.finalize = function(callback) {
  callback = callback || function() {};

  this._writeCentralDirectory();
  this.end();

  callback();
};

Zip.prototype.write = function(chunk, cb) {
  if (chunk) {
    this.offset += chunk.length;
  }

  return Transform.prototype.write.call(this, chunk, cb);
};<commit_msg>zip: restore deflate pipe. will need some feedback if the issues have subsided.<commit_after>/**
 * node-archiver
 *
 * Copyright (c) 2012-2013 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/ctalkington/node-archiver/blob/master/LICENSE-MIT
 */

var inherits = require('util').inherits;
var Transform = require('stream').Transform || require('readable-stream').Transform;

var headers = require('./headers');
var util = require('../../util');
var DeflateRawChecksum = require('../../util/DeflateRawChecksum');
var ChecksumStream = require('../../util/ChecksumStream');

var Zip = module.exports = function(options) {
  options = this.options = util.defaults(options, {
    comment: '',
    forceUTC: false,
    zlib: {
      level: 1
    }
  });

  Transform.call(this, options);

  if (options.level && options.level >= 0) {
    options.zlib.level = options.level;
    delete options.level;
  }

  this.offset = 0;
  this.files = [];
};

inherits(Zip, Transform);

Zip.prototype._normalizeFileData = function(data) {
  data = util.defaults(data, {
    name: null,
    date: null,
    store: false,
    comment: ''
  });

  data.name = util.sanitizeFilePath(data.name);
  data.date = util.dateify(data.date);

  if (typeof data.lastModifiedDate !== 'number') {
    data.lastModifiedDate = util.dosDateTime(data.date, this.options.forceUTC);
  }

  if (this.options.zlib && this.options.zlib.level === 0) {
    data.store = true;
  }

  data.flags = (1<<3) | (1<<11);
  data.compressionMethod = data.store ? 0 : 8;
  data.uncompressedSize = 0;
  data.compressedSize = 0;

  return data;
};

Zip.prototype._transform = function(chunk, encoding, callback) {
  callback(null, chunk);
};

Zip.prototype._writeCentralDirectory = function() {
  var files = this.files;
  var comment = this.options.comment;
  var cdoffset = this.offset;
  var cdsize = 0;

  var centralDirectoryBuffer;
  for (var i = 0; i < files.length; i++) {
    var file = files[i];

    centralDirectoryBuffer = headers.encode('centralDirectory', file);
    this.write(centralDirectoryBuffer);
    cdsize += centralDirectoryBuffer.length;
  }

  var centralDirectoryFooterData = {
    directoryRecordsDisk: files.length,
    directoryRecords: files.length,
    centralDirectorySize: cdsize,
    centralDirectoryOffset: cdoffset,
    comment: comment
  };

  this.write(headers.encode('centralFooter', centralDirectoryFooterData));
};

Zip.prototype.append = function(source, data, callback) {
  var self = this;
  var file;

  data = file = self._normalizeFileData(data);
  file.offset = self.offset;

  self.write(headers.encode('file', file));

  var deflate;
  var checksumr;

  function onend() {
    self.write(headers.encode('fileDescriptor', file));

    self.files.push(file);

    callback(null, file);
  }

  if (file.store === false) {
    deflate = new DeflateRawChecksum(self.options.zlib);

    deflate.on('error', callback);

    deflate.on('end', function() {
      file.crc32 = deflate.digest;
      file.uncompressedSize = deflate.rawSize;
      file.compressedSize = deflate.compressedSize;

      onend();
    });

    deflate.pipe(self, { end: false });

    // deflate.on('data', function(data) {
    //   self.write(data);
    // });
  } else {
    checksumr = new ChecksumStream();

    checksumr.on('error', callback);

    checksumr.on('end', function () {
      file.uncompressedSize = checksumr.rawSize;
      file.compressedSize = checksumr.rawSize;
      file.crc32 = checksumr.digest;

      onend();
    });

    checksumr.pipe(self, { end: false });
  }

  if (file.sourceType === 'buffer') {
    if (file.store) {
      file.uncompressedSize += source.length;
      file.compressedSize = file.uncompressedSize;
      file.crc32 = util.crc32(source).digest();

      self.write(source);
      onend();
    } else {
      deflate.end(source);
    }
  } else if (file.sourceType === 'stream') {
    if (file.store) {
      source.pipe(checksumr);
    } else {
      source.pipe(deflate);
    }
  }
};

Zip.prototype.finalize = function(callback) {
  callback = callback || function() {};

  this._writeCentralDirectory();
  this.end();

  callback();
};

Zip.prototype.write = function(chunk, cb) {
  if (chunk) {
    this.offset += chunk.length;
  }

  return Transform.prototype.write.call(this, chunk, cb);
};<|endoftext|>


<commit_before>(function($) {

  module('truncate');

  $.truncate.defaults.ellipsis = '~';

  var txt = 'stuff and nonsense';
  var html = 'stuff and nonsense';

  test('Accept a number as options.', function() {
    strictEqual($.truncate('four', 3), 'fo~');
  });

  test('plain text', function() {
    strictEqual($.truncate(txt, {length: 20}), txt);
    strictEqual($.truncate(txt, {length: 18}), txt);
    strictEqual($.truncate(txt, {length: 9}), 'stuff an~');
  });

  test('tags', function() {
    strictEqual($.truncate(html, {length: 20}), html);
    strictEqual($.truncate(html, {length: 18}), html);
    strictEqual($.truncate(html, {length: 13}), 'stuff and no~');
    strictEqual($.truncate(html, {length: 9}), 'stuff an~');
    strictEqual($.truncate(html, {length: 8}), 'stuff a~');
    strictEqual($.truncate(html, {length: 7}), 'stuff ~');
    strictEqual($.truncate(html, {length: 6}), 'stuff~');
    strictEqual($.truncate(html, {length: 5}), 'stuf~');
    strictEqual($.truncate(html, {length: 4}), 'stu~');
  });

  test('words', function() {
    strictEqual($.truncate(txt, {length: 20, words: true}), txt);
    strictEqual($.truncate(txt, {length: 18, words: true}), txt);
    strictEqual($.truncate(txt, {length: 14, words: true}), 'stuff and~');
    strictEqual($.truncate(txt, {length: 10, words: true}), 'stuff and~');
    strictEqual($.truncate(txt, {length: 9, words: true}), 'stuff~');
  });

  test('noBreaks', function() {
    strictEqual($.truncate('foo
bar baz', {length: 8, noBreaks: true}), 'foo bar~');
  });

  test('stripTags', function() {
    strictEqual($.truncate('foo bar baz', {stripTags: true}), 'foo bar baz');
    strictEqual($.truncate('foo bar baz', {length: 8, stripTags: true}), 'foo bar~');
  });

})(jQuery);
<commit_msg>add failing tests for entity preservation<commit_after>(function($) {

  module('truncate');

  $.truncate.defaults.ellipsis = '~';

  var txt = 'stuff and nonsense';
  var html = 'stuff and nonsense';

  test('Accept a number as options.', function() {
    strictEqual($.truncate('four', 3), 'fo~');
  });

  test('plain text', function() {
    strictEqual($.truncate(txt, {length: 20}), txt);
    strictEqual($.truncate(txt, {length: 18}), txt);
    strictEqual($.truncate(txt, {length: 9}), 'stuff an~');
  });

  test('tags', function() {
    strictEqual($.truncate(html, {length: 20}), html);
    strictEqual($.truncate(html, {length: 18}), html);
    strictEqual($.truncate(html, {length: 13}), 'stuff and no~');
    strictEqual($.truncate(html, {length: 9}), 'stuff an~');
    strictEqual($.truncate(html, {length: 8}), 'stuff a~');
    strictEqual($.truncate(html, {length: 7}), 'stuff ~');
    strictEqual($.truncate(html, {length: 6}), 'stuff~');
    strictEqual($.truncate(html, {length: 5}), 'stuf~');
    strictEqual($.truncate(html, {length: 4}), 'stu~');
  });

  test('words', function() {
    strictEqual($.truncate(txt, {length: 20, words: true}), txt);
    strictEqual($.truncate(txt, {length: 18, words: true}), txt);
    strictEqual($.truncate(txt, {length: 14, words: true}), 'stuff and~');
    strictEqual($.truncate(txt, {length: 10, words: true}), 'stuff and~');
    strictEqual($.truncate(txt, {length: 9, words: true}), 'stuff~');
  });

  test('noBreaks', function() {
    strictEqual($.truncate('foo
bar baz', {length: 8, noBreaks: true}), 'foo bar~');
  });

  test('stripTags', function() {
    strictEqual($.truncate('foo bar baz', {stripTags: true}), 'foo bar baz');
    strictEqual($.truncate('foo bar baz', {length: 8, stripTags: true}), 'foo bar~');
  });

  test('entities', function() {
    var str = '
foo<bar<baz
';
    strictEqual($.truncate(str, {length: 5}), '
foo<~
');
    strictEqual($.truncate(str, {length: 6}), '
foo<b~
');
    strictEqual($.truncate(str, {length: 8}), '
foo<bar~
');
    strictEqual($.truncate(str, {length: 9}), '
foo<bar<~
');
  })

})(jQuery);
<|endoftext|>


<commit_before>var test = require('tape');
var path = require('path');
var fs   = require('fs');
var util = require('util');

var parser = require('../index');

function inspect(o) {
	console.log(util.inspect(o, { depth: null }));
}

test('Preprocess: #define', function(t) {
	var ast;
	var source = '#define FOO 1\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #undef', function(t) {
	var ast;
	var source = '#undef FOO\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #ifdef', function(t) {
	var ast;
	var source = '#ifdef GL_ES\nprecision highp vec3;\n#endif\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #ifndef', function(t) {
	var ast;
	var source = '#ifndef GL_ES\nprecision mediump vec3;\n#endif\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #if-else', function(t) {
	var ast;
	var source = '#ifdef FOO\nconst float foo = 1.0;\n#else\nconst float foo = 0.5;\n#endif\n';
	t.throws(ast = parser.parse(source), '#ifdef - Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, '#ifdef - Generated code matches');

	source = '#if FOO == 1\nconst float foo = 1.0;\n#else\nconst float foo = 0.5;\n#endif\n';
	t.throws(ast = parser.parse(source), '#if - Parsed successfully');
	generated = parser.string(ast);
	t.equal(generated, source, '#if - Generated code matches');
	t.end();
});

test('Preprocess: #if-elif-else', function(t) {
	var ast;
	var source = '#if FOO == 1\nconst float foo = 1.0;\n#elif FOO == 2\nconst float foo = 1.0;\n#else\nconst float foo = 0.0;\n#endif\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #version, #pragma, #extension, #error, #line, #include', function(t) {
	var sources = {
		'#version': '#version 150\n',
		'#pragma': '#pragma glslify: noise = require(glsl-noise/simplex/2d)\n',
		'#extension': '#extension GL_EXT_draw_buffers : require\n',
		'#error': '#error "Compile error"\n',
		'#line': '#line 10\n',
		'#include': '#include "common/constants.glsl"\n'
	};
	var ast;
	for (var name in sources) {
		var source = sources[name];
		t.throws(ast = parser.parse(source), name + ' - Parsed successfully');
		var generated = parser.string(ast);
		t.equal(generated, source, name + ' - Generated code matches');
	}
	t.end();
});

test('Precision', function(t) {
	var ast;
	var source = 'precision highp float;\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Attributes, Uniforms, Varyings', function(t) {
	var sources = {
		'Attributes': 'attribute vec3 position;\n',
		'Uniforms': 'uniform mat4 projection;\n',
		'Varyings': 'varying vec2 uv0;\n',
	};
	var ast;
	for (var name in sources) {
		var source = sources[name];
		t.throws(ast = parser.parse(source), name + ' - Parsed successfully');
		var generated = parser.string(ast);
		t.equal(generated, source, name + ' - Generated code matches');
	}
	t.end();
});

test('simple.glsl', function(t) {
	var file = path.join(__dirname, 'simple.glsl');
	var source = fs.readFileSync(file).toString();
	var ast;
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('test.glsl', function(t) {
	var file = path.join(__dirname, 'simple.glsl');
	var source = fs.readFileSync(file).toString();
	var ast;
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

// test('Source to AST', function(t) {
// 	var file = path.join(__dirname, 'test.glsl');
// 	var source = fs.readFileSync(file).toString();
// 	var ast = parser.parse(source);
// 	t.notEqual(ast, null, 'Parser returned something');
// 	//console.log(util.inspect(ast, { depth: null }));
// 	t.end();
// });
//
// test('AST to source', function(t) {
// 	var file = path.join(__dirname, 'simple.glsl');
// 	var source = fs.readFileSync(file).toString();
// 	var ast = parser.parse(source);
// 	t.notEqual(ast, null, 'Parser returned something');
//
// 	var src = parser.string(ast);
// 	console.log('OUTPUT:\n');
// 	console.log(src);
// 	//console.log(util.inspect(ast, { depth: null }));
// 	t.end();
// });
<commit_msg>Add: more tests<commit_after>var test = require('tape');
var path = require('path');
var fs   = require('fs');
var util = require('util');

var parser = require('../index');

function inspect(o) {
	console.log(util.inspect(o, { depth: null }));
}

test('Preprocess: #define', function(t) {
	var ast;
	var source = '#define FOO 1\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #undef', function(t) {
	var ast;
	var source = '#undef FOO\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #ifdef', function(t) {
	var ast;
	var source = '#ifdef GL_ES\nprecision highp vec3;\n#endif\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #ifndef', function(t) {
	var ast;
	var source = '#ifndef GL_ES\nprecision mediump vec3;\n#endif\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #if-else', function(t) {
	var ast;
	var source = '#ifdef FOO\nconst float foo = 1.0;\n#else\nconst float foo = 0.5;\n#endif\n';
	t.throws(ast = parser.parse(source), '#ifdef - Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, '#ifdef - Generated code matches');

	source = '#if FOO == 1\nconst float foo = 1.0;\n#else\nconst float foo = 0.5;\n#endif\n';
	t.throws(ast = parser.parse(source), '#if - Parsed successfully');
	generated = parser.string(ast);
	t.equal(generated, source, '#if - Generated code matches');
	t.end();
});

test('Preprocess: #if-elif-else', function(t) {
	var ast;
	var source = '#if FOO == 1\nconst float foo = 1.0;\n#elif FOO == 2\nconst float foo = 1.0;\n#else\nconst float foo = 0.0;\n#endif\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Preprocess: #version, #pragma, #extension, #error, #line, #include', function(t) {
	var sources = {
		'#version': '#version 150\n',
		'#pragma': '#pragma glslify: noise = require(glsl-noise/simplex/2d)\n',
		'#extension': '#extension GL_EXT_draw_buffers : require\n',
		'#error': '#error "Compile error"\n',
		'#line': '#line 10\n',
		'#include': '#include "common/constants.glsl"\n'
	};
	var ast;
	for (var name in sources) {
		var source = sources[name];
		t.throws(ast = parser.parse(source), name + ' - Parsed successfully');
		var generated = parser.string(ast);
		t.equal(generated, source, name + ' - Generated code matches');
	}
	t.end();
});

test('Precision', function(t) {
	var ast;
	var source = 'precision highp float;\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('Attributes, Uniforms, Varyings', function(t) {
	var sources = {
		'Attributes': 'attribute vec3 position;\n',
		'Uniforms': 'uniform mat4 projection;\n',
		'Varyings': 'varying vec2 uv0;\n',
	};
	var ast;
	for (var name in sources) {
		var source = sources[name];
		t.throws(ast = parser.parse(source), name + ' - Parsed successfully');
		var generated = parser.string(ast);
		t.equal(generated, source, name + ' - Generated code matches');
	}
	t.end();
});

test('Nested expressions', function(t) {
	var ast;
	var source = 'float a = (-x - zmin) / (zmax - zmin);\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('if', function(t) {
	var ast;
	var source = 'void main() {\n\tif (a < 0.5) {\n\t\ta /= 4.0;\n\t}\n}\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('if-else', function(t) {
	var ast;
	var source = 'void main() {\n\tif (a < 0.5) {\n\t\ta *= 4.0;\n\t}\n\telseif (a > 0.5) {\n\t\ta /= 2.0;\n\t}\n\telse {\n\t\ta = 0.0;\n\t}\n}\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('return', function(t) {
	var ast;
	var source = 'float f() {\n\treturn 0.5;\n}\n';
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('simple.glsl', function(t) {
	var file = path.join(__dirname, 'simple.glsl');
	var source = fs.readFileSync(file).toString();
	var ast;
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

test('test.glsl', function(t) {
	var file = path.join(__dirname, 'simple.glsl');
	var source = fs.readFileSync(file).toString();
	var ast;
	t.throws(ast = parser.parse(source), 'Parsed successfully');
	var generated = parser.string(ast);
	t.equal(generated, source, 'Generated code matches');
	t.end();
});

// test('diffuse.frag', function(t) {
// 	var file = path.join(__dirname, 'diffuse.frag');
// 	var source = fs.readFileSync(file).toString();
// 	var ast;
// 	t.throws(ast = parser.parse(source), 'Parsed successfully');
// 	var generated = parser.string(ast);
// 	console.log('SOURCE:');
// 	console.log(source);
// 	console.log('');
// 	console.log('GENERATED:');
// 	console.log(generated);
// 	console.log('');
// 	t.equal(generated, source, 'Generated code matches');
// 	t.end();
// });
<|endoftext|>


<commit_before>import chai from 'chai';
import chaiBEM from 'chai-bem';
import chaiSpies from 'chai-spies';
import chaiEnzyme from 'chai-enzyme';
import { ReactWrapper, ShallowWrapper } from 'enzyme';

chai.use(chaiBEM({
    entityHook(entity) {
        if (entity instanceof ShallowWrapper || entity instanceof ReactWrapper) {
            return entity.prop('className');
        }

        return entity;
    }
}));
chai.use(chaiSpies);
chai.use(chaiEnzyme());

const componentsContext = require.context('../src/', true, /index\.js$/);
const testsContext = require.context('./src/', true, /index\.js$/);

componentsContext.keys().forEach(componentsContext);
testsContext.keys().forEach(testsContext);

// catch react warnings to be able to test PropTypes
before(function() {
    console.error = error => {
        throw Error(error);
    };
});
<commit_msg>:space_invader: temporary tweak chai-bem to work with Enzyme ReactWrapper<commit_after>import { findDOMNode } from 'react-dom';
import chai from 'chai';
import chaiBEM from 'chai-bem';
import chaiSpies from 'chai-spies';
import chaiEnzyme from 'chai-enzyme';
import { ReactWrapper, ShallowWrapper } from 'enzyme';

chai.use(chaiBEM({
    entityHook(entity) {
        if (entity instanceof ReactWrapper) {
            // TODO: please fix me
            return findDOMNode(entity.component).className;
        }

        if (entity instanceof ShallowWrapper) {
            return entity.prop('className');
        }

        return entity;
    }
}));
chai.use(chaiSpies);
chai.use(chaiEnzyme());

const componentsContext = require.context('../src/', true, /index\.js$/);
const testsContext = require.context('./src/', true, /index\.js$/);

componentsContext.keys().forEach(componentsContext);
testsContext.keys().forEach(testsContext);

// catch react warnings to be able to test PropTypes
before(function() {
    console.error = error => {
        throw Error(error);
    };
});
<|endoftext|>


<commit_before>'use strict';

const chai      = require("chai");
const coMocha   = require('co-mocha');
const expect    = chai.expect;
const Tree      = require('shark-tree');
const Logger    = require('shark-logger');
const path      = require('path');
const fs        = require('fs');
const VError    = require('verror');

const ToTreeTransformer     = require('./transformers/to-tree-transformer');
const ToFilesTransformer    = require('./transformers/to-files-transformer');

describe('Initialization', function() {
	before(function() {
		this.filesTree = new Tree({
			'dest/path': 'src/path'
		});

		this.logger = Logger({
			name: 'TransformerTestLogger'
		});
	});

	it('should throw exception if tree is invalid type', function *(done) {
		try {
			yield ToTreeTransformer.treeToTree(null, this.logger);
			done(new Error());
		}
		catch (error) {
			done();
		}
	});

	it('should throw exception if logger is invalid type', function *(done) {
		try {
			yield ToTreeTransformer.treeToTree(this.filesTree, null);
			done(new Error());
		}
		catch (error) {
			done();
		}
	});

	it('should not throw any exceptions if tree and logger is valid type', function *(done) {
		try {
			yield ToTreeTransformer.treeToTree(this.filesTree, this.logger);
			done();
		}
		catch (error) {
			done(error);
		}
	});
});

describe('ToTreeTranformer',function(){
	before(function() {
		this.filesTree = new Tree({
			'dest/path': 'src/path'
		});

		this.logger = Logger({
			name: 'TransformerTestLogger'
		});
	});

	it('should transform "src/path" to "src/path/new"',function *(){
		var tree = yield ToTreeTransformer.treeToTree(this.filesTree, this.logger);
		expect(tree.getSrcFilesByDest('dest/path').firstSrcFile().src()).equal('src/path/new');
	});
});

describe('ToFilesTranformer',function(){
	before(function() {
		var files = {};
		var dest = path.join(__dirname, './fixtures/dest.txt');
		files[dest] = path.join(__dirname, './fixtures/src.txt');
		this.dest = dest;
		this.filesTree = new Tree(files);

		this.logger = Logger({
			name: 'TransformerTestLogger'
		});

		fs.writeFileSync(dest, '');
	});

	it('should save content from src to dest',function *(){
		yield ToFilesTransformer.treeToFiles(this.filesTree, this.logger);
		expect(fs.readFileSync(this.dest).toString()).equal('hello world new');
	});
});
<commit_msg>Fixes produced by SharkTree API changes<commit_after>'use strict';

const chai      = require("chai");
const coMocha   = require('co-mocha');
const expect    = chai.expect;
const Tree      = require('shark-tree');
const Logger    = require('shark-logger');
const path      = require('path');
const fs        = require('fs');
const VError    = require('verror');

const ToTreeTransformer     = require('./transformers/to-tree-transformer');
const ToFilesTransformer    = require('./transformers/to-files-transformer');

describe('Initialization', function() {
	before(function() {
		this.filesTree = new Tree({
			'dest/path': 'src/path'
		});

		this.logger = Logger({
			name: 'TransformerTestLogger'
		});
	});

	it('should throw exception if tree is invalid type', function *(done) {
		try {
			yield ToTreeTransformer.treeToTree(null, this.logger);
			done(new Error());
		}
		catch (error) {
			done();
		}
	});

	it('should throw exception if logger is invalid type', function *(done) {
		try {
			yield ToTreeTransformer.treeToTree(this.filesTree, null);
			done(new Error());
		}
		catch (error) {
			done();
		}
	});

	it('should not throw any exceptions if tree and logger is valid type', function *(done) {
		try {
			yield ToTreeTransformer.treeToTree(this.filesTree, this.logger);
			done();
		}
		catch (error) {
			done(error);
		}
	});
});

describe('ToTreeTranformer',function(){
	before(function() {
		this.filesTree = new Tree({
			'dest/path': 'src/path'
		});

		this.logger = Logger({
			name: 'TransformerTestLogger'
		});
	});

	it('should transform "src/path" to "src/path/new"',function *(){
		var tree = yield ToTreeTransformer.treeToTree(this.filesTree, this.logger);
		expect(tree.getSrcCollectionByDest('dest/path').firstSrcFile().src()).equal('src/path/new');
	});
});

describe('ToFilesTranformer',function(){
	before(function() {
		var files = {};
		var dest = path.join(__dirname, './fixtures/dest.txt');
		files[dest] = path.join(__dirname, './fixtures/src.txt');
		this.dest = dest;
		this.filesTree = new Tree(files);

		this.logger = Logger({
			name: 'TransformerTestLogger'
		});

		fs.writeFileSync(dest, '');
	});

	it('should save content from src to dest',function *(){
		yield ToFilesTransformer.treeToFiles(this.filesTree, this.logger);
		expect(fs.readFileSync(this.dest).toString()).equal('hello world new');
	});
});
<|endoftext|>


<commit_before>/* jshint -W098 */
/* jshint expr:true */

var should = require( 'chai' ).should();
var IinChecker = require( '../index' );
var iin = new IinChecker( {} );
var nock = require('nock');

// RegEx Constant
var REGEX = "REGEX";

describe( '#pass in invalid params', function() {
	it( 'should lookup a card with undefined iin and error gracefully', function( done ) {
		iin.lookup( undefined, function( err, result ) {
			err.should.be.an( 'object' );
			err.message.should.equal( iin.options.messages.PARAMETER_IIN_IS_UNDEFINED );
			done();
		} );
	} );
	it( 'should lookup a card with empty iin and error gracefully', function( done ) {
		iin.lookup( '', function( err, result ) {
			err.should.be.an( 'object' );
			err.message.should.equal( iin.options.messages.PARAMETER_IIN_IS_EMPTY );
			done();
		} );
	} );
	it( 'should lookup a card with undefined callback and error gracefully', function( done ) {
		var result = iin.lookup( '411111' );
		result.message.should.equal( iin.options.messages.PARAMETER_CALLBACK_NOT_FUNCTION );
		done();
	} );
	it( 'should return an error of not a number', function( done ) {
		iin.lookup( 'foobar', function( err, result ) {
			err.should.be.an( 'object' );
			err.message.should.equal( iin.options.messages.PARAMETER_IIN_IS_NOT_A_NUMBER );
			done();
		} );
	} );
	it( 'should return an error of not long enough', function( done ) {
		iin.lookup( '123', function( err, result ) {
			err.should.be.an( 'object' );
			err.message.should.equal( iin.options.messages.PARAMETER_IIN_IS_NOT_LONG_ENOUGH );
			done();
		} );
	} );
} );

// Load all of our providers into an array that we can loop over.
var providers = require( '../configs/providers' );

var stubRequest = function( provider, iin ) {
	// Don't stub our network requests if our provider is RegEx as it is not a network request
	if ( provider.name !== REGEX ) {
		// Make sure our string comparisons don't get caught out by case issues by converting to uppercase
		if ( iin !== '111111' ) {
			nock( provider.domain ).get( provider.path + iin ).replyWithFile( 200, __dirname + '/fixtures/' + provider.name + '/' + iin + '.json' );
		} else {
			nock( provider.domain ).get( provider.path + iin ).reply( 404, '404 page not found' );
		}
	}
};

// This will stop all further calls to this provider from functioning...Please make sure you call this on the last line of your last test function
var breakProvider = function( provider ) {
	nock( provider.domain ).persist().get( '*' ).reply( 500 );
};

// Out repeatable tests
var commonTests = function( provider ) {
	describe( '#lookup a card using ' + provider.name, function() {
		var testGenCard;
		it( 'should lookup a card without error', function( done ) {
			var iinToLookup = '411111';
			stubRequest( provider, iinToLookup );
			iin.lookup( iinToLookup, function( err, result ) {
				if ( err ) {
					throw( err );
				} else {
					testGenCard = result;
					done();
				}
			} );
		} );

		it( 'iin lookup returns card as an object', function( done ) {
			testGenCard.should.be.an( 'object' );
			done();
		} );

		it( 'card object returned contains the correct properties', function( done ) {
			testGenCard.should.have.property( 'iin' );
			testGenCard.should.have.property( 'brand' );
			testGenCard.should.have.property( 'issuer' );
			testGenCard.should.have.property( 'type' );
			testGenCard.should.have.property( 'category' );
			testGenCard.should.have.property( 'country' );
			done();
		} );

		it( 'should lookup an invalid card and error gracefully', function( done ) {
			var iinToLookup = '111111';
			stubRequest( provider, iinToLookup );
			iin.lookup( iinToLookup, function( err, result ) {
				err.should.not.be.null;
				err.should.not.be.undefined;
				done();
			} );
		} );
	} );

	describe( '#lookup visa debit using ' + provider.name, function() {
		var testVisaDebitCard;
		it( 'should lookup a card without error', function( done ) {
			var iinToLookup = '431940';
			stubRequest( provider, iinToLookup );
			iin.lookup( iinToLookup, function( err, result ) {
				if ( err ) {
					throw( err );
				} else {
					testVisaDebitCard = result;
					done();
				}
			} );
		} );

		// Alter test depending on if it is RegEx of a Provider Test
		if ( provider.name === REGEX ) {
			it( 'card is of type debit', function( done ) {
				testVisaDebitCard.type.should.equal( iin.types.UNKNOWN );
				done();
			} );
		} else {
			it( 'card is of type debit', function( done ) {
				testVisaDebitCard.type.should.equal( iin.types.DEBIT );
				done();
			} );
		}

		it( 'card is of brand visa', function( done ) {
			testVisaDebitCard.brand.should.equal( iin.brands.VISA );
			done();
		} );
	} );

	describe( '#lookup mastercard credit using ' + provider.name, function() {
		var testMasterCreditCard;
		it( 'should lookup a card without error', function( done ) {
			var iinToLookup = '518791';
			stubRequest( provider, iinToLookup );
			iin.lookup( iinToLookup, function( err, result ) {
				if ( err ) {
					throw( err );
				} else {
					testMasterCreditCard = result;
					done();
				}
			} );
		} );

		// Alter test depending on if it is RegEx of a Provider Test
		if ( provider.name === REGEX ) {
			it( 'card is of type credit', function( done ) {
				testMasterCreditCard.type.should.equal( iin.types.UNKNOWN );
				done();
			} );
		} else {
			it( 'card is of type credit', function( done ) {
				testMasterCreditCard.type.should.equal( iin.types.CREDIT );
				done();
		} );
		}

		it( 'card is of brand mastercard', function( done ) {
			testMasterCreditCard.brand.should.equal( iin.brands.MASTERCARD );
			done();
		} );
	} );
};

// Lets read our providers in from the config and loop over them
providers.forEach( function( provider ) {
	commonTests( provider );
	// This is the final test...we are all done with the provider, so let's mock them being broken, so that fallback will work for the subsequent provider
	breakProvider( provider );
} );

// Because we have looped all providers and called 'breakProvider' on each we should be OK to test the RegEx version here.
commonTests( { name: REGEX } );
<commit_msg>Updated test messages in line with feedback on Pull Request #21<commit_after>/* jshint -W098 */
/* jshint expr:true */

var should = require( 'chai' ).should();
var IinChecker = require( '../index' );
var iin = new IinChecker( {} );
var nock = require('nock');

// RegEx Constant
var REGEX = "REGEX";

describe( '#pass in invalid params', function() {
	it( 'should lookup a card with undefined iin and error gracefully', function( done ) {
		iin.lookup( undefined, function( err, result ) {
			err.should.be.an( 'object' );
			err.message.should.equal( iin.options.messages.PARAMETER_IIN_IS_UNDEFINED );
			done();
		} );
	} );
	it( 'should lookup a card with empty iin and error gracefully', function( done ) {
		iin.lookup( '', function( err, result ) {
			err.should.be.an( 'object' );
			err.message.should.equal( iin.options.messages.PARAMETER_IIN_IS_EMPTY );
			done();
		} );
	} );
	it( 'should lookup a card with undefined callback and error gracefully', function( done ) {
		var result = iin.lookup( '411111' );
		result.message.should.equal( iin.options.messages.PARAMETER_CALLBACK_NOT_FUNCTION );
		done();
	} );
	it( 'should return an error of not a number', function( done ) {
		iin.lookup( 'foobar', function( err, result ) {
			err.should.be.an( 'object' );
			err.message.should.equal( iin.options.messages.PARAMETER_IIN_IS_NOT_A_NUMBER );
			done();
		} );
	} );
	it( 'should return an error of not long enough', function( done ) {
		iin.lookup( '123', function( err, result ) {
			err.should.be.an( 'object' );
			err.message.should.equal( iin.options.messages.PARAMETER_IIN_IS_NOT_LONG_ENOUGH );
			done();
		} );
	} );
} );

// Load all of our providers into an array that we can loop over.
var providers = require( '../configs/providers' );

var stubRequest = function( provider, iin ) {
	// Don't stub our network requests if our provider is RegEx as it is not a network request
	if ( provider.name !== REGEX ) {
		// Make sure our string comparisons don't get caught out by case issues by converting to uppercase
		if ( iin !== '111111' ) {
			nock( provider.domain ).get( provider.path + iin ).replyWithFile( 200, __dirname + '/fixtures/' + provider.name + '/' + iin + '.json' );
		} else {
			nock( provider.domain ).get( provider.path + iin ).reply( 404, '404 page not found' );
		}
	}
};

// This will stop all further calls to this provider from functioning...Please make sure you call this on the last line of your last test function
var breakProvider = function( provider ) {
	nock( provider.domain ).persist().get( '*' ).reply( 500 );
};

// Out repeatable tests
var commonTests = function( provider ) {
	describe( '#lookup a card using ' + provider.name, function() {
		var testGenCard;
		it( 'should lookup a card without error', function( done ) {
			var iinToLookup = '411111';
			stubRequest( provider, iinToLookup );
			iin.lookup( iinToLookup, function( err, result ) {
				if ( err ) {
					throw( err );
				} else {
					testGenCard = result;
					done();
				}
			} );
		} );

		it( 'iin lookup returns card as an object', function( done ) {
			testGenCard.should.be.an( 'object' );
			done();
		} );

		it( 'card object returned contains the correct properties', function( done ) {
			testGenCard.should.have.property( 'iin' );
			testGenCard.should.have.property( 'brand' );
			testGenCard.should.have.property( 'issuer' );
			testGenCard.should.have.property( 'type' );
			testGenCard.should.have.property( 'category' );
			testGenCard.should.have.property( 'country' );
			done();
		} );

		it( 'should lookup an invalid card and error gracefully', function( done ) {
			var iinToLookup = '111111';
			stubRequest( provider, iinToLookup );
			iin.lookup( iinToLookup, function( err, result ) {
				err.should.not.be.null;
				err.should.not.be.undefined;
				done();
			} );
		} );
	} );

	describe( '#lookup visa debit using ' + provider.name, function() {
		var testVisaDebitCard;
		it( 'should lookup a card without error', function( done ) {
			var iinToLookup = '431940';
			stubRequest( provider, iinToLookup );
			iin.lookup( iinToLookup, function( err, result ) {
				if ( err ) {
					throw( err );
				} else {
					testVisaDebitCard = result;
					done();
				}
			} );
		} );

		// Alter test depending on if it is RegEx of a Provider Test
		if ( provider.name === REGEX ) {
			it( 'card is of type unknown', function( done ) {
				testVisaDebitCard.type.should.equal( iin.types.UNKNOWN );
				done();
			} );
		} else {
			it( 'card is of type debit', function( done ) {
				testVisaDebitCard.type.should.equal( iin.types.DEBIT );
				done();
			} );
		}

		it( 'card is of brand visa', function( done ) {
			testVisaDebitCard.brand.should.equal( iin.brands.VISA );
			done();
		} );
	} );

	describe( '#lookup mastercard credit using ' + provider.name, function() {
		var testMasterCreditCard;
		it( 'should lookup a card without error', function( done ) {
			var iinToLookup = '518791';
			stubRequest( provider, iinToLookup );
			iin.lookup( iinToLookup, function( err, result ) {
				if ( err ) {
					throw( err );
				} else {
					testMasterCreditCard = result;
					done();
				}
			} );
		} );

		// Alter test depending on if it is RegEx of a Provider Test
		if ( provider.name === REGEX ) {
			it( 'card is of type unknown', function( done ) {
				testMasterCreditCard.type.should.equal( iin.types.UNKNOWN );
				done();
			} );
		} else {
			it( 'card is of type credit', function( done ) {
				testMasterCreditCard.type.should.equal( iin.types.CREDIT );
				done();
		} );
		}

		it( 'card is of brand mastercard', function( done ) {
			testMasterCreditCard.brand.should.equal( iin.brands.MASTERCARD );
			done();
		} );
	} );
};

// Lets read our providers in from the config and loop over them
providers.forEach( function( provider ) {
	commonTests( provider );
	// This is the final test...we are all done with the provider, so let's mock them being broken, so that fallback will work for the subsequent provider
	breakProvider( provider );
} );

// Because we have looped all providers and called 'breakProvider' on each we should be OK to test the RegEx version here.
commonTests( { name: REGEX } );
<|endoftext|>