<commit_before>const num_instances = process.argv[2] || 42;
const instances = [];
const events = [];
const domain = '<http://doma.in/_i/';
const iri_end = '> ';
const onEnd = domain + 'INSTANCE/onEnd>';
const onError = domain + 'INSTANCE/onError>';

let string = '';
let instance;
let instance_iri;
let step;
let num_events;
let event;
let event_iri;
let first_sequence;
let eStep
let num_sequence;
let sequence;
let handler_type;
let target;
let sStep;

for (step = 0; num_instances > step; ++step) {

    // instance
    instance = UID(8);
    instance_iri = domain + instance + iri_end;
    instances.push(instance_iri);
    //string += createInstance(instance_iri, instance);
    process.stdout.write(createInstance(instance_iri, instance));

    // TODO create onError onEnd event on first instance

    // events
    num_events = random(1, 23);
    for (eStep = 0; num_events > eStep; ++eStep) {
        event = UID(8);
        event_iri = domain + instance + '/' + event + iri_end;
        events.push(event_iri);
        first_sequence = '_:' + UID(8);
        //string += createEvent(instance_iri, event_iri, event, first_sequence);
        process.stdout.write(createEvent(instance_iri, event_iri, event, first_sequence));

        // sequence
        num_sequence = random(1, 23);
        for (sStep = 0; num_sequence > sStep; ++sStep) {

            // first_seq > seq > seq > seq ..
            sequence = sStep === (num_sequence - 1) ? null : '_:' + UID(8);
            handler_type = random(0, 2);

            // select random event
            if (handler_type > 1) {
                target = events[random(0, events.length - 1)];
                //string += createEventHandler(target, first_sequence, sequence);
                process.stdout.write(createEventHandler(target, first_sequence, sequence));

            // select random instance
            } else {
                target = instances[random(0, instances.length - 1)];

                if (handler_type === 0) {
                    //string += createDataHandler(target, first_sequence, sequence);
                    process.stdout.write(createDataHandler(target, first_sequence, sequence));
                } else {
                    //string += createStreamHandler(target, first_sequence, sequence);
                    process.stdout.write(createStreamHandler(target, first_sequence, sequence));
                }
            }

            first_sequence = sequence;
        }
    }
}

function UID (len) {
    len = len || 23;
    for (var i = 0, random = ''; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return random;
};

function random (min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// create basic instance triples
function createInstance (iri, name) {
    let s = iri + '<http://schema.org/name> "\\"' + name + '\\"" .\n' +
            iri + '<http://schema.jillix.net/vocab/roles> "\\"*\\"" .\n' +
            iri + '<http://schema.jillix.net/vocab/module> <https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json> .\n';

    //iri + <http://schema.jillix.net/vocab/event> <http://domain.com/_i/api_main_router/event/forwardToApiRouter> .
    //iri + <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/ModuleInstanceConfig> .
    return s;
};

function createEvent (inst, iri, name, sequence) {
    // create basic event triples
    // create sequence (data, event, stream)
    let s = inst + '<http://schema.jillix.net/vocab/event> ' + iri + '.\n' +
            iri + '<http://schema.jillix.net/vocab/onError> ' + onError + ' .\n' +
            iri + '<http://schema.jillix.net/vocab/onEnd> ' + onEnd + ' .\n' +
            iri + '<http://schema.org/name> "\\"' + name + '\\"" .\n' +
            iri + '<http://schema.jillix.net/vocab/sequence> ' + sequence + ' .\n';
    //iri + <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/FlowEvent> .'
    return s;
};

function createEventHandler(event, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/emit> ' + event + '.\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};

function createDataHandler(instance, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/instance> ' + instance + '.\n' +
            seq + ' <http://schema.jillix.net/vocab/dataHandler> ' +
            '<https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json#data> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};

function createStreamHandler(instance, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/instance> ' + instance + '.\n' +
            seq + ' <http://schema.jillix.net/vocab/streamHandler> ' +
            '<https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json#stream> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};
<commit_msg>add types<commit_after>const num_instances = process.argv[2] || 42;
const instances = [];
const events = [];
const domain = '<http://doma.in/_i/';
const iri_end = '> ';
const onEnd = domain + 'INSTANCE/onEnd>';
const onError = domain + 'INSTANCE/onError>';

let string = '';
let instance;
let instance_iri;
let step;
let num_events;
let event;
let event_iri;
let first_sequence;
let eStep
let num_sequence;
let sequence;
let handler_type;
let target;
let sStep;

for (step = 0; num_instances > step; ++step) {

    // instance
    instance = UID(8);
    instance_iri = domain + instance + iri_end;
    instances.push(instance_iri);
    //string += createInstance(instance_iri, instance);
    process.stdout.write(createInstance(instance_iri, instance));

    // TODO create onError onEnd event on first instance

    // events
    num_events = random(1, 23);
    for (eStep = 0; num_events > eStep; ++eStep) {
        event = UID(8);
        event_iri = domain + instance + '/' + event + iri_end;
        events.push(event_iri);
        first_sequence = '_:' + UID(8);
        //string += createEvent(instance_iri, event_iri, event, first_sequence);
        process.stdout.write(createEvent(instance_iri, event_iri, event, first_sequence));

        // sequence
        num_sequence = random(1, 23);
        for (sStep = 0; num_sequence > sStep; ++sStep) {

            // first_seq > seq > seq > seq ..
            sequence = sStep === (num_sequence - 1) ? null : '_:' + UID(8);
            handler_type = random(0, 2);

            // select random event
            if (handler_type > 1) {
                target = events[random(0, events.length - 1)];
                //string += createEventHandler(target, first_sequence, sequence);
                process.stdout.write(createEventHandler(target, first_sequence, sequence));

            // select random instance
            } else {
                target = instances[random(0, instances.length - 1)];

                if (handler_type === 0) {
                    //string += createDataHandler(target, first_sequence, sequence);
                    process.stdout.write(createDataHandler(target, first_sequence, sequence));
                } else {
                    //string += createStreamHandler(target, first_sequence, sequence);
                    process.stdout.write(createStreamHandler(target, first_sequence, sequence));
                }
            }

            first_sequence = sequence;
        }
    }
}

function UID (len) {
    len = len || 23;
    for (var i = 0, random = ''; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return random;
};

function random (min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// create basic instance triples
function createInstance (iri, name) {
    let s = iri + '<http://schema.org/name> "\\"' + name + '\\"" .\n' +
            iri + '<http://schema.jillix.net/vocab/roles> "\\"*\\"" .\n' +
            iri + '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/ModuleInstanceConfig> .\n' +
            iri + '<http://schema.jillix.net/vocab/module> <https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json> .\n';

    return s;
};

function createEvent (inst, iri, name, sequence) {
    let s = inst + '<http://schema.jillix.net/vocab/event> ' + iri + '.\n' +
            iri + '<http://schema.jillix.net/vocab/onError> ' + onError + ' .\n' +
            iri + '<http://schema.jillix.net/vocab/onEnd> ' + onEnd + ' .\n' +
            iri + '<http://schema.org/name> "\\"' + name + '\\"" .\n' +
            iri + '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/FlowEvent> .\n' +
            iri + '<http://schema.jillix.net/vocab/sequence> ' + sequence + ' .\n';

    return s;
};

function createEventHandler(event, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/emit> ' + event + '.\n' +
            seq + ' <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/EventEmit> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};

function createDataHandler(instance, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/instance> ' + instance + '.\n' +
            seq + ' <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/DataHandler> .\n' +
            seq + ' <http://schema.jillix.net/vocab/dataHandler> ' +
            '<https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json#data> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};

function createStreamHandler(instance, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/instance> ' + instance + '.\n' +
            seq + ' <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/StreamHandler> .\n' +
            seq + ' <http://schema.jillix.net/vocab/streamHandler> ' +
            '<https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json#stream> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};
<|endoftext|>


<commit_before>var grunt = require('grunt');
var fs = require('fs');

exports.less = {
  compile: function(test) {
    'use strict';

    test.expect(2);

    var actual = grunt.file.read('tmp/less.css');
    var expected = grunt.file.read('test/expected/less.css');
    test.equal(expected, actual, 'should compile less, with the ability to handle imported files from alternate include paths');

    actual = grunt.file.read('tmp/concat.css');
    expected = grunt.file.read('test/expected/concat.css');
    test.equal(expected, actual, 'should concat output when passed an array');

    test.done();
  },
  compress: function(test) {
    'use strict';

    test.expect(1);

    var actual = grunt.file.read('tmp/compress.css');
    var expected = grunt.file.read('test/expected/compress.css');
    test.equal(expected, actual, 'should compress output when compress option is true');

    test.done();
  },
  nopaths: function(test) {
    'use strict';

    test.expect(1);

    var actual = grunt.file.read('tmp/nopaths.css');
    var expected = grunt.file.read('test/expected/nopaths.css');
    test.equal(expected, actual, 'should default paths to the dirname of the less file');

    test.done();
  },
  cleancss: function(test) {
    'use strict';

    var actual, expected;

    test.expect(2);

    actual = grunt.file.read('tmp/cleancss.css');
    expected = grunt.file.read('test/expected/cleancss.css');
    test.equal(expected, actual, 'should cleancss output when cleancss option is true');

    actual = grunt.file.read('tmp/cleancssReport.css');
    expected = grunt.file.read('test/expected/cleancssReport.css');
    test.equal(expected, actual, 'should cleancss output when cleancss option is true and concating is enable');

    test.done();
  },
  ieCompat: function(test) {
    'use strict';

    var actual, expected;

    test.expect(2);

    actual = grunt.file.read('tmp/ieCompatFalse.css');
    expected = grunt.file.read('test/expected/ieCompatFalse.css');
    test.equal(expected, actual, 'should generate data-uris no matter the size when ieCompat option is true');

    actual = grunt.file.read('tmp/ieCompatTrue.css');
    expected = grunt.file.read('test/expected/ieCompatTrue.css');
    test.equal(expected, actual, 'should generate data-uris only when under the 32KB mark for Internet Explorer 8');

    test.done();
  },
  variablesAsLess: function(test) {
    'use strict';

    var actual, expected;

    test.expect(1);

    actual = grunt.file.read('tmp/variablesAsLess.css');
    expected = grunt.file.read('test/expected/variablesAsLess.css');
    test.equal(expected, actual, 'should process css files imported less files');

    test.done();
  },
  sourceMap: function(test) {
    test.expect(1);
    var actual = grunt.file.read('tmp/sourceMap.css');
    test.ok(actual.indexOf('/*# sourceMappingURL=') !== -1, 'compiled file should include a source map.');
    test.done();
  },
  customFunctions: function(test) {
    'use strict';

    var actual, expected;

    test.expect(1);

    actual = grunt.file.read('tmp/customFunctions.css');
    expected = grunt.file.read('test/expected/customFunctions.css');
    test.equal(expected, actual, 'should execute custom functions');

    test.done();
  }
};
<commit_msg>Clean up formatting on tests<commit_after>'use strict';

var grunt = require('grunt');
var fs = require('fs');

exports.less = {
  compile: function(test) {
    test.expect(2);

    var actual = grunt.file.read('tmp/less.css');
    var expected = grunt.file.read('test/expected/less.css');
    test.equal(expected, actual, 'should compile less, with the ability to handle imported files from alternate include paths');

    actual = grunt.file.read('tmp/concat.css');
    expected = grunt.file.read('test/expected/concat.css');
    test.equal(expected, actual, 'should concat output when passed an array');

    test.done();
  },
  compress: function(test) {
    test.expect(1);

    var actual = grunt.file.read('tmp/compress.css');
    var expected = grunt.file.read('test/expected/compress.css');
    test.equal(expected, actual, 'should compress output when compress option is true');

    test.done();
  },
  nopaths: function(test) {
    test.expect(1);

    var actual = grunt.file.read('tmp/nopaths.css');
    var expected = grunt.file.read('test/expected/nopaths.css');
    test.equal(expected, actual, 'should default paths to the dirname of the less file');

    test.done();
  },
  cleancss: function(test) {
    test.expect(2);

    var actual = grunt.file.read('tmp/cleancss.css');
    var expected = grunt.file.read('test/expected/cleancss.css');
    test.equal(expected, actual, 'should cleancss output when cleancss option is true');

    actual = grunt.file.read('tmp/cleancssReport.css');
    expected = grunt.file.read('test/expected/cleancssReport.css');
    test.equal(expected, actual, 'should cleancss output when cleancss option is true and concating is enable');

    test.done();
  },
  ieCompat: function(test) {
    test.expect(2);

    var actual = grunt.file.read('tmp/ieCompatFalse.css');
    var expected = grunt.file.read('test/expected/ieCompatFalse.css');
    test.equal(expected, actual, 'should generate data-uris no matter the size when ieCompat option is true');

    actual = grunt.file.read('tmp/ieCompatTrue.css');
    expected = grunt.file.read('test/expected/ieCompatTrue.css');
    test.equal(expected, actual, 'should generate data-uris only when under the 32KB mark for Internet Explorer 8');

    test.done();
  },
  variablesAsLess: function(test) {
    test.expect(1);

    var actual = grunt.file.read('tmp/variablesAsLess.css');
    var expected = grunt.file.read('test/expected/variablesAsLess.css');
    test.equal(expected, actual, 'should process css files imported less files');

    test.done();
  },
  sourceMap: function(test) {
    test.expect(1);

    var actual = grunt.file.read('tmp/sourceMap.css');
    test.ok(actual.indexOf('/*# sourceMappingURL=') !== -1, 'compiled file should include a source map.');

    test.done();
  },
  customFunctions: function(test) {
    test.expect(1);

    var actual = grunt.file.read('tmp/customFunctions.css');
    var expected = grunt.file.read('test/expected/customFunctions.css');
    test.equal(expected, actual, 'should execute custom functions');

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


<commit_before>var should  = require('should')
  , Disco   = require('../../lib/disco')
  , ltx     = require('ltx')
  , helper  = require('../helper')

describe('Disco', function() {

    var disco, socket, xmpp, manager

    before(function() {
        socket = new helper.Eventer()
        xmpp = new helper.Eventer()
        manager = {
            socket: socket,
            client: xmpp,
            trackId: function(id, callback) {
                this.callback = callback
            },
            makeCallback: function(error, data) {
                this.callback(error, data)
            }
        }
        disco = new Disco()
        disco.init(manager)
    })

    describe('Can handle incoming requests', function() {

        it('Shouldn\'t handle non-IQ stanzas', function() {
            disco.handles(ltx.parse('<message/>')).should.be.false
        })

        it('Shouldn\'t handle IQ without a <query/> child', function() {
            disco.handles(ltx.parse('<iq />')).should.be.false
        })

        it('Shouldn\'t handle query without appropriate xmlns', function() {
            var query = ltx.parse('<iq><query xmlns="not-disco"/></iq>')
            disco.handles(query).should.be.false
        })

        it('Should handle DISCO#info requests', function() {
            var query = ltx.parse('<iq><query xmlns="' + disco.NS_INFO + '" /></iq>')
            disco.handles(query).should.be.true
        })

        it('Sends DISCO#info requests to client', function(done) {
            var request = '<iq id="1" from="romeo@example.com" type="get">'
                + '<query xmlns="' + disco. NS_INFO + '" /></iq>'
            xmpp.once('stanza', function(stanza) {
                stanza.attrs.type.should.equal('result')
                var query = stanza.getChild('query')
                should.exist(query)
                query.attrs.xmlns.should.equal(disco.NS_INFO)
                query.children.length.should.equal(2)
                var children = query.children
                children[0].name.should.equal('kind1')
                children[0].attrs.name.should.equal('name1')
                children[0].attrs.category.should.equal('cat1')
                children[0].attrs.var.should.equal('var1')
                children[0].attrs.jid.should.equal('jid1')
                children[0].attrs.node.should.equal('node1')
                children[1].name.should.eql('kind2')
                done()
            })
            socket.once('xmpp.discover.client', function(data, callback) {
                var features = [
                    { kind: 'kind1', name: 'name1', category: 'cat1', var: 'var1', jid: 'jid1', node: 'node1' },
                    { kind: 'kind2' },
                    {}
                ]
                callback(features)
            })
            disco.handle(ltx.parse(request)).should.be.true
        })

        describe('Can make DISCO#items requests', function() {

            it('Should error when no \'of\' property passed', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.emit('xmpp.discover.items', {}, function(error, success) {
                    should.not.exist(success)
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing 'of' key")
                    error.request.should.eql({})
                    xmpp.removeAllListeners('stanza')
                    done()
                })
            })

            it('Errors when no callback provided', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.once('xmpp.error.client', function(error) {
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing callback")
                    error.request.should.eql({ of: 'example.com' })
                    xmpp.removeAllListeners('stanza')
                    done()
                })
                socket.emit('xmpp.discover.items', { of: 'example.com' })
            })

            it('Errors when non-function callback provided', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.once('xmpp.error.client', function(error) {
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing callback")
                    error.request.should.eql({ of: 'example.com' })
                    xmpp.removeAllListeners('stanza')
                    done()
                })
                socket.emit('xmpp.discover.items', { of: 'example.com' }, true)
            })

            it('Sends expected stanza', function(done) {
                var of = 'wonderland.lit'
                xmpp.once('stanza', function(stanza) {
                    stanza.is('iq').should.be.true
                    stanza.attrs.to.should.equal(of)
                    stanza.getChild('query', disco.NS_ITEMS)
                        .should.exist
                    done()
                })
                socket.emit('xmpp.discover.items', { of: of }, function() {})
            })

            it('Sends expected stanza with node', function(done) {
                var request = { of: 'wonderland.lit', node: 'some-node' }
                xmpp.once('stanza', function(stanza) {
                    stanza.getChild('query', disco.NS_ITEMS)
                        .attrs.node.should.equal(request.node)
                    done()
                })
                socket.emit('xmpp.discover.items', request, function() {})
            })

            it('Can handle error response from server', function(done) {
                var of = 'wonderland.lit'
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_ITEMS)
                     manager.makeCallback(helper.getStanza('iq-error'))
                })
                var callback = function(error, success) {
                    should.not.exist(success)
                    error.should.eql({
                        type: 'cancel',
                        condition: 'error-condition'
                    })
                    done()
                }
                socket.emit('xmpp.discover.items', { of: of }, callback)
            })

            it('Can handle DISCO#items response', function(done) {
                var request = {
                    of: 'wonderland.lit',
                    node: 'rabbithole'
                }
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(request.of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_ITEMS)
                     query.attrs.node.should.equal(request.node)
                     manager.makeCallback(helper.getStanza('disco-items'))
                })
                var callback = function(error, data) {
                    should.not.exist(error)
                    data.length.should.equal(2)
                    data[0].should.eql({ jid: 'jid1', name: 'name1' })
                    data[1].jid.should.equal('jid2')
                    data[1].name.should.equal('name2')
                    data[1].type.should.equal('type2')
                    data[1].var.should.equal('var2')
                    data[1].category.should.equal('category2')
                    data[1].node.should.equal('node2')
                    done()
                }
                socket.emit('xmpp.discover.items', request, callback)
            })

        })

        describe('Can make DISCO#info requests', function() {

           it('Should error when no \'of\' property passed', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.emit('xmpp.discover.info', {}, function(error, success) {
                    should.not.exist(success)
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing 'of' key")
                    error.request.should.eql({})
                    xmpp.removeAllListeners('stanza')
                    done()
                })
            })

            it('Errors when no callback provided', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.once('xmpp.error.client', function(error) {
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing callback")
                    error.request.should.eql({ of: 'example.com' })
                    xmpp.removeAllListeners('stanza')
                    done()
                })
                socket.emit('xmpp.discover.info', { of: 'example.com' })
            })

            it('Errors when non-function callback provided', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.once('xmpp.error.client', function(error) {
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing callback")
                    error.request.should.eql({ of: 'example.com' })
                    xmpp.removeAllListeners('stanza')
                    done()
                })
                socket.emit('xmpp.discover.info', { of: 'example.com' }, true)
            })

            it('Can handle error response from server', function(done) {
                var of = 'wonderland.lit'
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_INFO)
                     manager.makeCallback(helper.getStanza('iq-error'))
                })
                var callback = function(error, success) {
                    should.not.exist(success)
                    error.should.eql({
                        type: 'cancel',
                        condition: 'error-condition'
                    })
                    done()
                }
                socket.emit('xmpp.discover.info', { of: of }, callback)
            })

            it('Can handle successful response', function(done) {
                var request = {
                    of: 'wonderland.lit',
                    node: 'rabbithole'
                }
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(request.of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_INFO)
                     query.attrs.node.should.equal(request.node)
                     manager.makeCallback(helper.getStanza('disco-info'))
                })
                var callback = function(error, data) {
                    should.not.exist(error)
                    // Element <ignore/> will have been ignored
                    data.length.should.equal(3)
                    data[0].kind.should.equal('identity')
                    data[0].type.should.equal('type1')
                    data[0].name.should.equal('name1')
                    data[0].category.should.equal('category1')
                    data[1].should.eql({ kind: 'feature', var: 'var2' })
                    data[2].kind.should.equal('item')
                    data[2].var.should.equal('var3')
                    data[2].jid.should.equal('jid3')
                    data[2].node.should.equal('node3')
                    done()
                }
                socket.emit('xmpp.discover.info', request, callback)
            })

            it('Can handle response with data form', function(done) {
                var request = {
                    of: 'wonderland.lit',
                    node: 'rabbithole'
                }
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(request.of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_INFO)
                     query.attrs.node.should.equal(request.node)
                     var stanza = helper.getStanza('disco-info-with-data-form')
                     manager.makeCallback(stanza)
                })
                var callback = function(error, data) {
                    should.not.exist(error)
                    data.length.should.equal(1)
                    data[0].kind.should.equal('form')
                    data[0].form.fields.length.should.equal(1)
                    done()
                }
                socket.emit('xmpp.discover.info', request, callback)
            })

        })

    })

})
<commit_msg>Tests for outgoing stanza. Fixes #3.<commit_after>var should  = require('should')
  , Disco   = require('../../lib/disco')
  , ltx     = require('ltx')
  , helper  = require('../helper')

describe('Disco', function() {

    var disco, socket, xmpp, manager

    before(function() {
        socket = new helper.Eventer()
        xmpp = new helper.Eventer()
        manager = {
            socket: socket,
            client: xmpp,
            trackId: function(id, callback) {
                this.callback = callback
            },
            makeCallback: function(error, data) {
                this.callback(error, data)
            }
        }
        disco = new Disco()
        disco.init(manager)
    })

    describe('Can handle incoming requests', function() {

        it('Shouldn\'t handle non-IQ stanzas', function() {
            disco.handles(ltx.parse('<message/>')).should.be.false
        })

        it('Shouldn\'t handle IQ without a <query/> child', function() {
            disco.handles(ltx.parse('<iq />')).should.be.false
        })

        it('Shouldn\'t handle query without appropriate xmlns', function() {
            var query = ltx.parse('<iq><query xmlns="not-disco"/></iq>')
            disco.handles(query).should.be.false
        })

        it('Should handle DISCO#info requests', function() {
            var query = ltx.parse('<iq><query xmlns="' + disco.NS_INFO + '" /></iq>')
            disco.handles(query).should.be.true
        })

        it('Sends DISCO#info requests to client', function(done) {
            var request = '<iq id="1" from="romeo@example.com" type="get">'
                + '<query xmlns="' + disco. NS_INFO + '" /></iq>'
            xmpp.once('stanza', function(stanza) {
                stanza.attrs.type.should.equal('result')
                var query = stanza.getChild('query')
                should.exist(query)
                query.attrs.xmlns.should.equal(disco.NS_INFO)
                query.children.length.should.equal(2)
                var children = query.children
                children[0].name.should.equal('kind1')
                children[0].attrs.name.should.equal('name1')
                children[0].attrs.category.should.equal('cat1')
                children[0].attrs.var.should.equal('var1')
                children[0].attrs.jid.should.equal('jid1')
                children[0].attrs.node.should.equal('node1')
                children[1].name.should.eql('kind2')
                done()
            })
            socket.once('xmpp.discover.client', function(data, callback) {
                var features = [
                    { kind: 'kind1', name: 'name1', category: 'cat1', var: 'var1', jid: 'jid1', node: 'node1' },
                    { kind: 'kind2' },
                    {}
                ]
                callback(features)
            })
            disco.handle(ltx.parse(request)).should.be.true
        })

        describe('Can make DISCO#items requests', function() {

            it('Should error when no \'of\' property passed', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.emit('xmpp.discover.items', {}, function(error, success) {
                    should.not.exist(success)
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing 'of' key")
                    error.request.should.eql({})
                    xmpp.removeAllListeners('stanza')
                    done()
                })
            })

            it('Errors when no callback provided', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.once('xmpp.error.client', function(error) {
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing callback")
                    error.request.should.eql({ of: 'example.com' })
                    xmpp.removeAllListeners('stanza')
                    done()
                })
                socket.emit('xmpp.discover.items', { of: 'example.com' })
            })

            it('Errors when non-function callback provided', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.once('xmpp.error.client', function(error) {
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing callback")
                    error.request.should.eql({ of: 'example.com' })
                    xmpp.removeAllListeners('stanza')
                    done()
                })
                socket.emit('xmpp.discover.items', { of: 'example.com' }, true)
            })

            it('Sends expected stanza', function(done) {
                var of = 'wonderland.lit'
                xmpp.once('stanza', function(stanza) {
                    stanza.is('iq').should.be.true
                    stanza.attrs.to.should.equal(of)
                    stanza.getChild('query', disco.NS_ITEMS)
                        .should.exist
                    done()
                })
                socket.emit('xmpp.discover.items', { of: of }, function() {})
            })

            it('Sends expected stanza with node', function(done) {
                var request = { of: 'wonderland.lit', node: 'some-node' }
                xmpp.once('stanza', function(stanza) {
                    stanza.getChild('query', disco.NS_ITEMS)
                        .attrs.node.should.equal(request.node)
                    done()
                })
                socket.emit('xmpp.discover.items', request, function() {})
            })

            it('Can handle error response from server', function(done) {
                var of = 'wonderland.lit'
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_ITEMS)
                     manager.makeCallback(helper.getStanza('iq-error'))
                })
                var callback = function(error, success) {
                    should.not.exist(success)
                    error.should.eql({
                        type: 'cancel',
                        condition: 'error-condition'
                    })
                    done()
                }
                socket.emit('xmpp.discover.items', { of: of }, callback)
            })

            it('Can handle DISCO#items response', function(done) {
                var request = {
                    of: 'wonderland.lit',
                    node: 'rabbithole'
                }
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(request.of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_ITEMS)
                     query.attrs.node.should.equal(request.node)
                     manager.makeCallback(helper.getStanza('disco-items'))
                })
                var callback = function(error, data) {
                    should.not.exist(error)
                    data.length.should.equal(2)
                    data[0].should.eql({ jid: 'jid1', name: 'name1' })
                    data[1].jid.should.equal('jid2')
                    data[1].name.should.equal('name2')
                    data[1].type.should.equal('type2')
                    data[1].var.should.equal('var2')
                    data[1].category.should.equal('category2')
                    data[1].node.should.equal('node2')
                    done()
                }
                socket.emit('xmpp.discover.items', request, callback)
            })

        })

        describe('Can make DISCO#info requests', function() {

           it('Should error when no \'of\' property passed', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.emit('xmpp.discover.info', {}, function(error, success) {
                    should.not.exist(success)
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing 'of' key")
                    error.request.should.eql({})
                    xmpp.removeAllListeners('stanza')
                    done()
                })
            })

            it('Errors when no callback provided', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.once('xmpp.error.client', function(error) {
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing callback")
                    error.request.should.eql({ of: 'example.com' })
                    xmpp.removeAllListeners('stanza')
                    done()
                })
                socket.emit('xmpp.discover.info', { of: 'example.com' })
            })

            it('Errors when non-function callback provided', function(done) {
                xmpp.once('stanza', function() {
                    done('Unexpected outgoing stanza')
                })
                socket.once('xmpp.error.client', function(error) {
                    error.type.should.equal('modify')
                    error.condition.should.equal('client-error')
                    error.description.should.equal("Missing callback")
                    error.request.should.eql({ of: 'example.com' })
                    xmpp.removeAllListeners('stanza')
                    done()
                })
                socket.emit('xmpp.discover.info', { of: 'example.com' }, true)
            })

            it('Sends expected stanza', function(done) {
                var of = 'wonderland.lit'
                xmpp.once('stanza', function(stanza) {
                    stanza.is('iq').should.be.true
                    stanza.attrs.to.should.equal(of)
                    stanza.getChild('query', disco.NS_INFO)
                        .should.exist
                    done()
                })
                socket.emit('xmpp.discover.info', { of: of }, function() {})
            })

            it('Sends expected stanza with node', function(done) {
                var request = { of: 'wonderland.lit', node: 'some-node' }
                xmpp.once('stanza', function(stanza) {
                    stanza.getChild('query', disco.NS_INFO)
                        .attrs.node.should.equal(request.node)
                    done()
                })
                socket.emit('xmpp.discover.info', request, function() {})
            })

            it('Can handle error response from server', function(done) {
                var of = 'wonderland.lit'
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_INFO)
                     manager.makeCallback(helper.getStanza('iq-error'))
                })
                var callback = function(error, success) {
                    should.not.exist(success)
                    error.should.eql({
                        type: 'cancel',
                        condition: 'error-condition'
                    })
                    done()
                }
                socket.emit('xmpp.discover.info', { of: of }, callback)
            })

            it('Can handle successful response', function(done) {
                var request = {
                    of: 'wonderland.lit',
                    node: 'rabbithole'
                }
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(request.of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_INFO)
                     query.attrs.node.should.equal(request.node)
                     manager.makeCallback(helper.getStanza('disco-info'))
                })
                var callback = function(error, data) {
                    should.not.exist(error)
                    // Element <ignore/> will have been ignored
                    data.length.should.equal(3)
                    data[0].kind.should.equal('identity')
                    data[0].type.should.equal('type1')
                    data[0].name.should.equal('name1')
                    data[0].category.should.equal('category1')
                    data[1].should.eql({ kind: 'feature', var: 'var2' })
                    data[2].kind.should.equal('item')
                    data[2].var.should.equal('var3')
                    data[2].jid.should.equal('jid3')
                    data[2].node.should.equal('node3')
                    done()
                }
                socket.emit('xmpp.discover.info', request, callback)
            })

            it('Can handle response with data form', function(done) {
                var request = {
                    of: 'wonderland.lit',
                    node: 'rabbithole'
                }
                xmpp.once('stanza', function(stanza) {
                     stanza.is('iq').should.be.true
                     stanza.attrs.type.should.equal('get')
                     stanza.attrs.to.should.equal(request.of)
                     should.exist(stanza.attrs.id)
                     var query = stanza.getChild('query', disco.NS_INFO)
                     query.attrs.node.should.equal(request.node)
                     var stanza = helper.getStanza('disco-info-with-data-form')
                     manager.makeCallback(stanza)
                })
                var callback = function(error, data) {
                    should.not.exist(error)
                    data.length.should.equal(1)
                    data[0].kind.should.equal('form')
                    data[0].form.fields.length.should.equal(1)
                    done()
                }
                socket.emit('xmpp.discover.info', request, callback)
            })

        })

    })

})
<|endoftext|>


<commit_before>/* eslint-env mocha */

'use strict';

let chai = require('chai');
let expect = chai.expect;
let dirtyChai = require('dirty-chai');
let proxyquire = require('proxyquire');
let Graph = require('../../lib/graph');

chai.use(dirtyChai);

describe('Graph class module', () => {
  // Removes console printing for our modules
  let oldError = console.error;
  before(() => {
    console.error = () => {};
  });
  after(() => {
    console.error = oldError;
  });
  describe('constructor', () => {
    let url = 'url';
    let projectId = 3;
    let graph = new Graph(projectId, url);
    expect(graph.url).to.equal(url);
    expect(graph.projectId).to.equal(projectId);
    expect(graph.name).to.be.empty();
    expect(graph.nodes).to.be.empty();
    expect(graph.edges).to.be.empty();
  });

  describe('buildGraph function', () => {
    let projectId = 1;
    let url = 'url';
    let stubs = {};
    let data = [];
    let Graph = proxyquire('../../lib/graph', {'Promises': stubs});
    let newGraph;
    let resolvedNamePromise = () => {
      return new Promise((resolve, reject) => {
        data = 'mocked project name';
        resolve(data);
      });
    };
    let resolvedItemsPromise = () => {
      return new Promise((resolve, reject) => {
        data = [{'id': 10, 'name': 'item name', 'type': 99}];
        resolve(data);
      });
    };
    let resolvedRelationshipsPromise = () => {
      return new Promise((resolve, reject) => {
        data = [{'id': 10, 'source': 1, 'target': 2, 'type': 99}];
        resolve(data);
      });
    };
    let rejectedTimeoutPromise = () => {
      return new Promise((resolve, reject) => {
        let error = { 'connect': true, 'code': 'ETIMEDOUT' };
        reject(error);
      });
    };
    let rejectedErrorPromise = () => {
      return new Promise((resolve, reject) => {
        let error = { 'statusCode': 401, 'status': 'Not found', 'connect': false, 'code': '' };
        reject(error);
      });
    };

    it('should return a graph with nonempty data members when project ID and url are valid.', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url).buildGraph().then(() => {
        expect(newGraph.name).to.equal('mocked project name');
        expect(newGraph.nodes[0].id).to.equal(10);
        expect(newGraph.nodes[0].name).to.equal('item name');
        expect(newGraph.nodes[0].type).to.equal(99);
        expect(newGraph.edges[0].id).to.equal(10);
        expect(newGraph.edges[0].source).to.equal(1);
        expect(newGraph.edges[0].target).to.equal(2);
        expect(newGraph.edges[0].type).to.equal(99);
      });
    });

    it('should return a graph that contains nothing when either project ID or url are invalid.', () => {
      stubs.getProjectName = () => rejectedErrorPromise();
      stubs.getProjectItems = () => rejectedErrorPromise();
      stubs.getProjectRelationships = () => rejectedErrorPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectItems', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectRelationships', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName and getProjectItems',
      () => {
        stubs.getProjectName = () => rejectedTimeoutPromise();
        stubs.getProjectItems = () => rejectedTimeoutPromise();
        stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
        newGraph = new Graph(projectId, url).buildGraph();
        expect(newGraph.name).to.be.empty();
        expect(newGraph.nodes).to.be.empty();
        expect(newGraph.edges).to.be.empty();
      });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectItems and' +
      'getProjectRelationships', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName and' +
      'getProjectRelationships', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for all three helper functions', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when an error not including timeout is encountered', () => {
      stubs.getProjectName = () => rejectedErrorPromise();
      stubs.getProjectItems = () => rejectedErrorPromise();
      stubs.getProjectRelationships = () => rejectedErrorPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });
  });

  describe('toJson function', () => {
    let badNodes = [{'id': '10', 'name': 'item name', 'type': '99'}];
    let badEdges = [{'id': '10', 'source': '1', 'target': '2', 'type': '99'}];
    let nodes = [{'id': 10, 'name': 'item name', 'type': 99, 'image': 'url'}];
    let edges = [{'id': 10, 'source': 1, 'target': 2, 'type': 99, 'suspect': true}];

    it('should print an error message if the data Graph contains is invalid', () => {
      let graph = new Graph();
      graph.nodes = badNodes;
      graph.edges = badEdges;
      expect(graph.toJson()).to.be.empty();
    });

    it('should return a valid relationship graph json object if Graph contains valid data', () => {
      let graph = new Graph();
      graph.nodes = nodes;
      graph.edges = edges;
      expect(graph.toJson()).to.not.be.empty();
    });
  });

  describe('fromJson function', () => {
    let badNodes = [{'id': '10', 'name': 'item name', 'type': '99'}];
    let badEdges = [{'id': '10', 'source': '1', 'target': '2', 'type': '99'}];
    let nodes = [{'id': 10, 'name': 'item name', 'type': 99, 'image': 'url'}];
    let edges = [{'id': 10, 'source': 1, 'target': 2, 'type': 99, 'suspect': false}];

    it('should print an error message if the data Graph contains is invalid', () => {
      let relGraphObj = {'items': badNodes, 'relationships': badEdges};
      expect(Graph.fromJson(relGraphObj)).to.be.null;
    });

    it('should return a valid relationship graph json object if graph contains valid data', () => {
      let graph = new Graph();
      graph.nodes = nodes;
      graph.edges = edges;
      let relGraphBlob = {name: 'test', 'items': nodes, 'relationships': edges};
      let newGraph = Graph.fromJson(relGraphBlob);
      expect(newGraph.nodes).to.deep.equal(nodes);
      expect(newGraph.edges).to.deep.equal(edges);
    });
  });
});
<commit_msg>finish testing buildGraph<commit_after>/* eslint-env mocha */

'use strict';

let chai = require('chai');
let expect = chai.expect;
let dirtyChai = require('dirty-chai');
let proxyquire = require('proxyquire');
let Graph = require('../../lib/graph');

chai.use(dirtyChai);

describe('Graph class module', () => {
  // Removes console printing for our modules
  let oldError = console.error;
  before(() => {
    console.error = () => {};
  });
  after(() => {
    console.error = oldError;
  });
  describe('constructor', () => {
    let url = 'url';
    let projectId = 3;
    let graph = new Graph(projectId, url);
    expect(graph.url).to.equal(url);
    expect(graph.projectId).to.equal(projectId);
    expect(graph.name).to.be.empty();
    expect(graph.nodes).to.be.empty();
    expect(graph.edges).to.be.empty();
  });

  describe('buildGraph function', () => {
    let projectId;
    let url;
    let stubs;
    let data;
    let Graph;
    let newGraph;

    beforeEach(() => {
      projectId = 1;
      url = 'url';
      stubs = {};
      data = [];
      Graph = proxyquire('../../lib/graph', {'./projects': stubs});
      newGraph = undefined;
    });
    let resolvedNamePromise = () => {
      return new Promise((resolve, reject) => {
        data = 'mocked project name';
        resolve(data);
      });
    };
    let resolvedItemsPromise = () => {
      return new Promise((resolve, reject) => {
        data = [{'id': 10, 'name': 'item name', 'type': 99}];
        resolve(data);
      });
    };
    let resolvedRelationshipsPromise = () => {
      return new Promise((resolve, reject) => {
        data = [{'id': 10, 'source': 1, 'target': 2, 'type': 99}];
        resolve(data);
      });
    };
    let rejectedTimeoutPromise = () => {
      return new Promise((resolve, reject) => {
        let error = { 'connect': true, 'code': 'ETIMEDOUT' };
        reject(error);
      });
    };
    let rejectedErrorPromise = () => {
      return new Promise((resolve, reject) => {
        let error = { 'statusCode': 401, 'status': 'Not found', 'connect': false, 'code': '' };
        reject(error);
      });
    };

    it('should return a graph with nonempty data members when project ID and url are valid.', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url);
      return newGraph.buildGraph().then(() => {
        console.log('$$$$$$$$$$$$ ' + newGraph.name);
        expect(newGraph.name).to.equal('mocked project name');
        expect(newGraph.nodes[0].id).to.equal(10);
        expect(newGraph.nodes[0].name).to.equal('item name');
        expect(newGraph.nodes[0].type).to.equal(99);
        expect(newGraph.edges[0].id).to.equal(10);
        expect(newGraph.edges[0].source).to.equal(1);
        expect(newGraph.edges[0].target).to.equal(2);
        expect(newGraph.edges[0].type).to.equal(99);
      });
    });

    it('should return a graph that contains nothing when either project ID or url are invalid.', () => {
      stubs.getProjectName = () => rejectedErrorPromise();
      stubs.getProjectItems = () => rejectedErrorPromise();
      stubs.getProjectRelationships = () => rejectedErrorPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectItems', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectRelationships', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName and getProjectItems',
      () => {
        stubs.getProjectName = () => rejectedTimeoutPromise();
        stubs.getProjectItems = () => rejectedTimeoutPromise();
        stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
        newGraph = new Graph(projectId, url).buildGraph();
        expect(newGraph.name).to.be.empty();
        expect(newGraph.nodes).to.be.empty();
        expect(newGraph.edges).to.be.empty();
      });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectItems and' +
      'getProjectRelationships', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName and' +
      'getProjectRelationships', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for all three helper functions', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when an error not including timeout is encountered', () => {
      stubs.getProjectName = () => rejectedErrorPromise();
      stubs.getProjectItems = () => rejectedErrorPromise();
      stubs.getProjectRelationships = () => rejectedErrorPromise();
      newGraph = new Graph(projectId, url).buildGraph();
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });
  });

  describe('toJson function', () => {
    let badNodes = [{'id': '10', 'name': 'item name', 'type': '99'}];
    let badEdges = [{'id': '10', 'source': '1', 'target': '2', 'type': '99'}];
    let nodes = [{'id': 10, 'name': 'item name', 'type': 99, 'image': 'url'}];
    let edges = [{'id': 10, 'source': 1, 'target': 2, 'type': 99, 'suspect': true}];

    it('should print an error message if the data Graph contains is invalid', () => {
      let graph = new Graph();
      graph.nodes = badNodes;
      graph.edges = badEdges;
      expect(graph.toJson()).to.be.empty();
    });

    it('should return a valid relationship graph json object if Graph contains valid data', () => {
      let graph = new Graph();
      graph.nodes = nodes;
      graph.edges = edges;
      expect(graph.toJson()).to.not.be.empty();
    });
  });

  describe('fromJson function', () => {
    let badNodes = [{'id': '10', 'name': 'item name', 'type': '99'}];
    let badEdges = [{'id': '10', 'source': '1', 'target': '2', 'type': '99'}];
    let nodes = [{'id': 10, 'name': 'item name', 'type': 99, 'image': 'url'}];
    let edges = [{'id': 10, 'source': 1, 'target': 2, 'type': 99, 'suspect': false}];

    it('should print an error message if the data Graph contains is invalid', () => {
      let relGraphObj = {'items': badNodes, 'relationships': badEdges};
      expect(Graph.fromJson(relGraphObj)).to.be.null;
    });

    it('should return a valid relationship graph json object if graph contains valid data', () => {
      let graph = new Graph();
      graph.nodes = nodes;
      graph.edges = edges;
      let relGraphBlob = {name: 'test', 'items': nodes, 'relationships': edges};
      let newGraph = Graph.fromJson(relGraphBlob);
      expect(newGraph.nodes).to.deep.equal(nodes);
      expect(newGraph.edges).to.deep.equal(edges);
    });
  });
});
<|endoftext|>


<commit_before>import { createElement } from 'react';
import ReactDOMServer from 'react-dom/server';
import TestUtils from 'react-addons-test-utils';
import assert from 'assert';

import {
    BEM,
    blockFactory,
    buildClassName
} from '../../lib/';

import {
    BEM as BEMJSX,
    blockFactory as blockFactoryJSX,
    buildClassName as buildClassNameJSX
} from '../../lib/jsx';

function test(props, html) {
    assert.strictEqual(
        ReactDOMServer.renderToStaticMarkup(
            BEM(props)
        ),
        html
    );

    assert.strictEqual(
        ReactDOMServer.renderToStaticMarkup(
            createElement(BEMJSX, props)
        ),
        html
    );
}

describe('rebem', function() {
    describe('buildClassName', function() {
        it('is function', function() {
            assert(typeof buildClassName === 'function');
            assert(typeof buildClassNameJSX === 'function');
        });
    });

    describe('BEM', function() {
        it('is function', function() {
            assert(typeof BEM === 'function');
            assert(typeof BEMJSX === 'function');
        });

        describe('bemjson', function() {
            it('ReactElement is returned', function() {
                assert.ok(
                    TestUtils.isElement(
                        BEM({})
                    )
                );

                assert.ok(
                    TestUtils.isElement(
                        createElement(BEMJSX)
                    )
                );
            });

            it('default tag', function() {
                test(
                    {},
                    '

'
                );
            });

            it('tag', function() {
                test(
                    {
                        tag: 'span'
                    },
                    ''
                );
            });

            it('props', function() {
                test(
                    {
                        className: 'test'
                    },
                    '

'
                );
            });

            describe('block', function() {
                it('simple', function() {
                    test(
                        {
                            block: 'block'
                        },
                        '

'
                    );
                });

                it('props.className + block', function() {
                    test(
                        {
                            block: 'block2',
                            className: 'block1'
                        },
                        '

'
                    );
                });
            });

            describe('mods', function() {
                describe('block', function() {
                    it('block + mod', function() {
                        test(
                            {
                                block: 'block',
                                mods: {
                                    mod: 'val'
                                }
                            },
                            '

'
                        );
                    });

                    it('block + few mods', function() {
                        test(
                            {
                                block: 'block',
                                mods: {
                                    mod1: 'val1',
                                    mod2: 'val2'
                                }
                            },
                            '

'
                        );
                    });

                    it('block + shorthand mod = true', function() {
                        test(
                            {
                                block: 'block',
                                mods: {
                                    mod: true
                                }
                            },
                            '

'
                        );
                    });

                    it('block + shorthand mod = false', function() {
                        test(
                            {
                                block: 'block',
                                mods: {
                                    mod: false
                                }
                            },
                            '

'
                        );
                    });
                });

                describe('elem', function() {
                    it('block + elem + mod', function() {
                        test(
                            {
                                block: 'block',
                                elem: 'elem',
                                mods: {
                                    mod: 'val'
                                }
                            },
                            '

'
                        );
                    });

                    it('block + elem + few mods', function() {
                        test(
                            {
                                block: 'block',
                                elem: 'elem',
                                mods: {
                                    mod1: 'val1',
                                    mod2: 'val2'
                                }
                            },
                            '

'
                        );
                    });

                    it('block + shorthand mod = true', function() {
                        test(
                            {
                                block: 'block',
                                elem: 'elem',
                                mods: {
                                    mod: true
                                }
                            },
                            '

'
                        );
                    });

                    it('block + shorthand mod = false', function() {
                        test(
                            {
                                block: 'block',
                                elem: 'elem',
                                mods: {
                                    mod: false
                                }
                            },
                            '

'
                        );
                    });
                });
            });

            describe('mix', function() {
                it('mix without block', function() {
                    test(
                        {
                            mix: {
                                block: 'block'
                            }
                        },
                        '

'
                    );
                });

                it('block + mix', function() {
                    test(
                        {
                            block: 'block1',
                            mix: {
                                block: 'block2'
                            }
                        },
                        '

'
                    );
                });

                it('block + mods + mix', function() {
                    test(
                        {
                            block: 'block1',
                            mods: {
                                mod: 'val'
                            },
                            mix: {
                                block: 'block2'
                            }
                        },
                        '

'
                    );
                });

                it('block + elem + mix', function() {
                    test(
                        {
                            block: 'block1',
                            elem: 'elem',
                            mix: {
                                block: 'block2'
                            }
                        },
                        '

'
                    );
                });

                it('block + elem + mods + mix', function() {
                    test(
                        {
                            block: 'block1',
                            elem: 'elem',
                            mods: {
                                mod: 'val'
                            },
                            mix: {
                                block: 'block2'
                            }
                        },
                        '

'
                    );
                });

                it('complex mix', function() {
                    test(
                        {
                            block: 'block1',
                            mix: {
                                block: 'block2',
                                elem: 'elem',
                                mods: {
                                    mod1: 'val1',
                                    mod2: 'val2'
                                }
                            }
                        },
                        '

'
                    );
                });

                it('multiple mixes', function() {
                    test(
                        {
                            block: 'block1',
                            mix: [
                                {
                                    block: 'block2'
                                },
                                {
                                    block: 'block3'
                                }
                            ]
                        },
                        '

'
                    );
                });

                it('recursive mixes', function() {
                    test(
                        {
                            block: 'block1',
                            mix: {
                                block: 'block2',
                                mix: {
                                    block: 'block3'
                                }
                            }
                        },
                        '

'
                    );
                });
            });

            it('bemjson is not mutated', function() {
                const bemjson = {
                    block: 'block',
                    test: true
                };

                BEM(bemjson);

                assert(typeof bemjson.tag === 'undefined');
                assert(typeof bemjson.className === 'undefined');
            });
        });

        describe('children', function() {
            it('simple', function() {
                test(
                    {
                        tag: 'span',
                        children: createElement('i')
                    },
                    ''
                );
            });

            it('multiple', function() {
                test(
                    {
                        tag: 'span',
                        children: [
                            createElement('i', { key: 'i' }),
                            createElement('b', { key: 'b' })
                        ]
                    },
                    ''
                );
            });
        });
    });

    describe('blockFactory', function() {
        it('is function', function() {
            assert(typeof blockFactory === 'function');
            assert(typeof blockFactoryJSX === 'function');
        });

        it('isEqual BEM', function() {
            const block = blockFactory('block');
            const blockJSX = blockFactoryJSX('block');
            const result = '

';

            assert.strictEqual(
                ReactDOMServer.renderToStaticMarkup(
                    block({ elem: 'elem' })
                ),
                result
            );

            assert.strictEqual(
                ReactDOMServer.renderToStaticMarkup(
                    createElement(blockJSX, { elem: 'elem' })
                ),
                result
            );
        });
    });
});
<commit_msg>:space_invader: :lipstick:<commit_after>import { createElement } from 'react';
import ReactDOMServer from 'react-dom/server';
import TestUtils from 'react-addons-test-utils';
import assert from 'assert';

import {
    BEM,
    blockFactory,
    buildClassName
} from '../../lib/';

import {
    BEM as BEMJSX,
    blockFactory as blockFactoryJSX,
    buildClassName as buildClassNameJSX
} from '../../lib/jsx';

function test(props, result) {
    assert.strictEqual(
        ReactDOMServer.renderToStaticMarkup(
            BEM(props)
        ),
        result
    );

    assert.strictEqual(
        ReactDOMServer.renderToStaticMarkup(
            createElement(BEMJSX, props)
        ),
        result
    );
}

describe('rebem', function() {
    describe('buildClassName', function() {
        it('is function', function() {
            assert(typeof buildClassName === 'function');
            assert(typeof buildClassNameJSX === 'function');
        });
    });

    describe('BEM', function() {
        it('is function', function() {
            assert(typeof BEM === 'function');
            assert(typeof BEMJSX === 'function');
        });

        describe('bemjson', function() {
            it('ReactElement is returned', function() {
                assert.ok(
                    TestUtils.isElement(
                        BEM({})
                    )
                );

                assert.ok(
                    TestUtils.isElement(
                        createElement(BEMJSX)
                    )
                );
            });

            it('default tag', function() {
                test(
                    {},
                    '

'
                );
            });

            it('tag', function() {
                test(
                    {
                        tag: 'span'
                    },
                    ''
                );
            });

            it('props', function() {
                test(
                    {
                        className: 'test'
                    },
                    '

'
                );
            });

            describe('block', function() {
                it('simple', function() {
                    test(
                        {
                            block: 'block'
                        },
                        '

'
                    );
                });

                it('props.className + block', function() {
                    test(
                        {
                            block: 'block2',
                            className: 'block1'
                        },
                        '

'
                    );
                });
            });

            describe('mods', function() {
                describe('block', function() {
                    it('block + mod', function() {
                        test(
                            {
                                block: 'block',
                                mods: {
                                    mod: 'val'
                                }
                            },
                            '

'
                        );
                    });

                    it('block + few mods', function() {
                        test(
                            {
                                block: 'block',
                                mods: {
                                    mod1: 'val1',
                                    mod2: 'val2'
                                }
                            },
                            '

'
                        );
                    });

                    it('block + shorthand mod = true', function() {
                        test(
                            {
                                block: 'block',
                                mods: {
                                    mod: true
                                }
                            },
                            '

'
                        );
                    });

                    it('block + shorthand mod = false', function() {
                        test(
                            {
                                block: 'block',
                                mods: {
                                    mod: false
                                }
                            },
                            '

'
                        );
                    });
                });

                describe('elem', function() {
                    it('block + elem + mod', function() {
                        test(
                            {
                                block: 'block',
                                elem: 'elem',
                                mods: {
                                    mod: 'val'
                                }
                            },
                            '

'
                        );
                    });

                    it('block + elem + few mods', function() {
                        test(
                            {
                                block: 'block',
                                elem: 'elem',
                                mods: {
                                    mod1: 'val1',
                                    mod2: 'val2'
                                }
                            },
                            '

'
                        );
                    });

                    it('block + shorthand mod = true', function() {
                        test(
                            {
                                block: 'block',
                                elem: 'elem',
                                mods: {
                                    mod: true
                                }
                            },
                            '

'
                        );
                    });

                    it('block + shorthand mod = false', function() {
                        test(
                            {
                                block: 'block',
                                elem: 'elem',
                                mods: {
                                    mod: false
                                }
                            },
                            '

'
                        );
                    });
                });
            });

            describe('mix', function() {
                it('mix without block', function() {
                    test(
                        {
                            mix: {
                                block: 'block'
                            }
                        },
                        '

'
                    );
                });

                it('block + mix', function() {
                    test(
                        {
                            block: 'block1',
                            mix: {
                                block: 'block2'
                            }
                        },
                        '

'
                    );
                });

                it('block + mods + mix', function() {
                    test(
                        {
                            block: 'block1',
                            mods: {
                                mod: 'val'
                            },
                            mix: {
                                block: 'block2'
                            }
                        },
                        '

'
                    );
                });

                it('block + elem + mix', function() {
                    test(
                        {
                            block: 'block1',
                            elem: 'elem',
                            mix: {
                                block: 'block2'
                            }
                        },
                        '

'
                    );
                });

                it('block + elem + mods + mix', function() {
                    test(
                        {
                            block: 'block1',
                            elem: 'elem',
                            mods: {
                                mod: 'val'
                            },
                            mix: {
                                block: 'block2'
                            }
                        },
                        '

'
                    );
                });

                it('complex mix', function() {
                    test(
                        {
                            block: 'block1',
                            mix: {
                                block: 'block2',
                                elem: 'elem',
                                mods: {
                                    mod1: 'val1',
                                    mod2: 'val2'
                                }
                            }
                        },
                        '

'
                    );
                });

                it('multiple mixes', function() {
                    test(
                        {
                            block: 'block1',
                            mix: [
                                {
                                    block: 'block2'
                                },
                                {
                                    block: 'block3'
                                }
                            ]
                        },
                        '

'
                    );
                });

                it('recursive mixes', function() {
                    test(
                        {
                            block: 'block1',
                            mix: {
                                block: 'block2',
                                mix: {
                                    block: 'block3'
                                }
                            }
                        },
                        '

'
                    );
                });
            });

            it('bemjson is not mutated', function() {
                const bemjson = {
                    block: 'block',
                    test: true
                };

                BEM(bemjson);

                assert(typeof bemjson.tag === 'undefined');
                assert(typeof bemjson.className === 'undefined');
            });
        });

        describe('children', function() {
            it('simple', function() {
                test(
                    {
                        tag: 'span',
                        children: createElement('i')
                    },
                    ''
                );
            });

            it('multiple', function() {
                test(
                    {
                        tag: 'span',
                        children: [
                            createElement('i', { key: 'i' }),
                            createElement('b', { key: 'b' })
                        ]
                    },
                    ''
                );
            });
        });
    });

    describe('blockFactory', function() {
        it('is function', function() {
            assert(typeof blockFactory === 'function');
            assert(typeof blockFactoryJSX === 'function');
        });

        it('isEqual BEM', function() {
            const block = blockFactory('block');
            const blockJSX = blockFactoryJSX('block');
            const result = '

';

            assert.strictEqual(
                ReactDOMServer.renderToStaticMarkup(
                    block({ elem: 'elem' })
                ),
                result
            );

            assert.strictEqual(
                ReactDOMServer.renderToStaticMarkup(
                    createElement(blockJSX, { elem: 'elem' })
                ),
                result
            );
        });
    });
});
<|endoftext|>