<commit_before>// Copyright (c) Cognitect, Inc.
// All rights reserved.

"use strict";

goog.provide("com.cognitect.transit.impl.writer");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.handlers");
goog.require("com.cognitect.transit.types");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.stringbuilder");
goog.require("goog.math.Long");

goog.scope(function() {

var writer   = com.cognitect.transit.impl.writer,
    caching  = com.cognitect.transit.caching,
    handlers = com.cognitect.transit.handlers,
    types    = com.cognitect.transit.types,
    d        = com.cognitect.transit.delimiters,
    sb       = com.cognitect.transit.stringbuilder,
    Long     = goog.math.Long;

writer.escape = function(string) {
    if(string.length > 0) {
        var c = string[0];
        if(c === d.RES && string[1] === d.ESC) {
            return string.substring(1);
        } else if(c === d.ESC || c === d.SUB || c === d.RES) {
            return d.ESC+string;
        } else {
            return string;
        }
    } else {
        return string;
    }
};

/**
 * @constructor
 */
writer.JSONMarshaller = function(opts) {
    this.opts = opts || {};
    this.buffer = this.opts.buffer || (new sb.StringBuilder());
    this.prefersStrings = this.opts["prefersStrings"] != null ? this.opts["prefersStrings"] : true;

    this.objectBuilder = this.opts["objectBuilder"] || null;

    this.handlers = new handlers.Handlers();
    if(this.opts["handlers"]) {
        for(var i = 0; i < this.opts["handlers"].length; i+=2) {
            this.handlers.set(this.opts["handlers"][i], this.opts["handlers"][i+1]);
        }
    }

    this.verbose = (this.opts && this.opts["verbose"]) || false;
};

writer.JSONMarshaller.prototype.handler = function(obj) {
        return this.handlers.get(handlers.constructor(obj));
};

writer.JSONMarshaller.prototype.registerHandler = function(ctor, handler) {
    this.handlers.set(ctor, handler);
};

writer.JSONMarshaller.prototype.emitNil = function(asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "_", "", asMapKey, cache);
    } else {
        return null;
    }
};

writer.JSONMarshaller.prototype.emitString = function(prefix, tag, s, asMapKey, cache) {
    var string = prefix+tag+s;
    if(cache) {
        return cache.write(string, asMapKey);
    } else {
        return string;
    }
};

writer.JSONMarshaller.prototype.emitBoolean = function(b, asMapKey, cache) {
    if(asMapKey) {
        var s = b.toString();
        return this.emitString(d.ESC, "?", s[0], asMapKey, cache);
    } else {
        return b;
    }
};

writer.JSONMarshaller.prototype.emitInteger = function(i, asMapKey, cache) {
    if(asMapKey || (typeof i === "string") || (i instanceof Long)) {
        return this.emitString(d.ESC, "i", i.toString(), asMapKey, cache);
    } else {
        return i;
    }
};

writer.JSONMarshaller.prototype.emitDouble = function(d, asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "d", d, asMapKey, cache);
    } else {
        return d;
    }
};

writer.JSONMarshaller.prototype.emitBinary = function(b, asMapKey, cache) {
    return this.emitString(d.ESC, "b", b, asMapKey, cache);
};

writer.JSONMarshaller.prototype.emitQuoted = function(obj, cache) {
    var ret = {},
        k   = this.emitString(d.ESC_TAG, "'", "", true, cache);
    ret[k] = writer.marshal(this, obj, false, cache);
    return ret;
};

writer.emitInts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitShorts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitShort(em, src[i], false, cache));
    }
    return ret;
};

writer.emitLongs = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitFloats = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitFloat(em, src[i], false, cache));
    }
    return ret;
};

writer.emitDouble = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitDouble(em, src[i], false, cache));
    }
    return ret;
};

writer.emitChars = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(writer.marshal(em, src[i], false, cache));
    }
    return ret;
};

writer.emitBooleans = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitBoolean(em, src[i], false, cache));
    }
    return ret;
};

writer.emitObjects = function(em, iterable, cache) {
    var ret = [];
    if(Array.isArray(iterable)) {
        for(var i = 0; i < iterable.length; i++) {
            ret.push(writer.marshal(em, iterable[i], false, cache));
        }
    } else {
        iterable.forEach(function(v, i) {
            ret.push(writer.marshal(em, v, false, cache));
        });
    }
    return ret;
};

writer.emitArray = function(em, iterable, skip, cache) {
    if(iterable instanceof Int8Array) {
        return writer.emitChars(em, iterable, cache);
    } else if(iterable instanceof Int16Array) {
        return writer.emitShorts(em, iterable, cache);
    } else if(iterable instanceof Int32Array) {
        return writer.emitInts(em, iterable, cache);
    } else if(iterable instanceof Float32Array) {
        return writer.emitFloats(em, iterable, cache);
    } else if(iterable instanceof Float64Array) {
        return writer.emitDoubles(em, iterable, cache);
    } else {
        return writer.emitObjects(em, iterable, cache);
    }
};

writer.emitMap = function(em, obj, skip, cache) {
    if((obj.constructor === Object) || (obj.forEach != null)) {
        if(em.verbose) {
            var ret = {};
            if(obj.forEach != null) {
                obj.forEach(function(v, k) {
                    ret[writer.marshal(em, k, true, false)] = writer.marshal(em, v, false, cache);
                });
            } else {
                var ks  = Object.keys(obj);
                for(var i = 0; i < ks.length; i++) {
                    ret[writer.marshal(em, ks[i], true, false)] = writer.marshal(em, obj[ks[i]], false, cache);
                }
            }
            return ret;
        } else {
            var ret = ["^ "];
            if(obj.forEach != null) {
                obj.forEach(function(v, k) {
                    ret.push(writer.marshal(em, k, true, cache));
                    ret.push(writer.marshal(em, v, false, cache));
                });
            } else {
                var ks  = Object.keys(obj);
                for(var i = 0; i < ks.length; i++) {
                    ret.push(writer.marshal(em, ks[i], true, cache));
                    ret.push(writer.marshal(em, obj[ks[i]], false, cache));
                }
            }
            return ret;
        }
    } else if(em.objectBuilder != null) {
        return em.objectBuilder(obj, function(k) { return writer.marshal(em, k, true, cache);  },
                                     function(v) { return writer.marshal(em, v, false, cache); });
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.emitTaggedMap = function(em, tag, rep, skip, cache) {
    var ret = {};
    ret[em.emitString(d.ESC_TAG, tag, "", true, cache)] = writer.marshal(em, rep, false, cache);
    return ret;
};

writer.emitEncoded = function(em, h, tag, rep, obj, asMapKey, cache) {
    if(tag.length === 1) {
        if(typeof rep === "string") {
            return em.emitString(d.ESC, tag, rep, asMapKey, cache);
        } else if(asMapKey || em.prefersStrings) {
            var vh = em.verbose && h.getVerboseHandler();
            if(vh) {
                tag = vh.tag(obj);
                rep = vh.stringRep(obj, vh);
            } else {
                rep = h.stringRep(obj, h);
            }
            if(rep !== null) {
                return em.emitString(d.ESC, tag, rep, asMapKey, cache);
            } else {
                var err = new Error("Cannot be encoded as string");
                err.data = {tag: tag, rep: rep, obj: obj};
                throw err;
            }
        } else {
            return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
        }
    } else if (asMapKey) {
        var err = new Error("Cannot be used as map key");
        err.data = {tag: tag, rep: rep, obj: obj};
        throw err;
    } else {
        return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
    }
}

writer.marshal = function(em, obj, asMapKey, cache) {
    var h   = em.handler(obj),
        tag = h ? h.tag(obj) : null,
        rep = h ? h.rep(obj) : null;

    if(h != null && tag != null) {
        switch(tag) {
        case "_":
            return em.emitNil(asMapKey, cache);
            break;
        case "s":
            return em.emitString("", "", writer.escape(rep), asMapKey, cache);
            break;
        case "?":
            return em.emitBoolean(rep, asMapKey, cache);
            break;
        case "i":
            return em.emitInteger(rep, asMapKey, cache);
            break;
        case "d":
            return em.emitDouble(rep, asMapKey, cache);
            break;
        case "b":
            return em.emitBinary(rep, asMapKey, cache);
            break;
        case "'":
            return em.emitQuoted(rep, cache);
            break;
        case "array":
            return writer.emitArray(em, rep, asMapKey, cache);
            break;
        case "map":
            return writer.emitMap(em, rep, asMapKey, cache);
            break;
        default:
            return writer.emitEncoded(em, h, tag, rep, obj, asMapKey, cache);
            break;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.maybeQuoted = function(em, obj) {
    var h = em.handler(obj);

    if(h != null) {
        if(h.tag(obj).length === 1) {
            return types.quoted(obj);
        } else {
            return obj;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.marshalTop = function(em, obj, asMapKey, cache) {
    return JSON.stringify(writer.marshal(em, writer.maybeQuoted(em, obj), asMapKey, cache));
};

/**
 * @constructor
 */
writer.Writer = function(marshaller, options) {
    this.marshaller = marshaller;
    this.options = options || {};
    if(this.options["cache"] === false) {
        this.cache = null;
    } else {
        this.cache = this.options["cache"] ? this.options["cache"] : new caching.WriteCache();
    }
};

writer.Writer.prototype.write = function(obj, opts) {
    var ret      = null,
        ropts    = opts || {};
        asMapKey = ropts["asMapKey"] || false;

    if(ropts["marshalTop"] === false) {
        ret = writer.marshal(this.marshaller, obj, asMapKey, this.cache)
    } else {
        ret = writer.marshalTop(this.marshaller, obj, asMapKey, this.cache)
    }
    if(this.cache != null) {
        this.cache.clear();
    }
    return ret;
};
writer.Writer.prototype["write"] = writer.Writer.prototype.write;

/*
writer.Writer.prototype.toKey = function(obj) {
    return this.decoder.decode(
        this.write(obj, {marshalTop: false, asMapKey: true}),
        false, true, false
    );
};
writer.Writer.prototype["toKey"] = writer.Writer.prototype.toKey;
*/

writer.Writer.prototype.register = function(type, handler) {
    this.marshaller.registerHandler(type, handler);
};
writer.Writer.prototype["register"] = writer.Writer.prototype.register;

});
<commit_msg>remove dead code<commit_after>// Copyright (c) Cognitect, Inc.
// All rights reserved.

"use strict";

goog.provide("com.cognitect.transit.impl.writer");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.handlers");
goog.require("com.cognitect.transit.types");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.stringbuilder");
goog.require("goog.math.Long");

goog.scope(function() {

var writer   = com.cognitect.transit.impl.writer,
    caching  = com.cognitect.transit.caching,
    handlers = com.cognitect.transit.handlers,
    types    = com.cognitect.transit.types,
    d        = com.cognitect.transit.delimiters,
    sb       = com.cognitect.transit.stringbuilder,
    Long     = goog.math.Long;

writer.escape = function(string) {
    if(string.length > 0) {
        var c = string[0];
        if(c === d.RES && string[1] === d.ESC) {
            return string.substring(1);
        } else if(c === d.ESC || c === d.SUB || c === d.RES) {
            return d.ESC+string;
        } else {
            return string;
        }
    } else {
        return string;
    }
};

/**
 * @constructor
 */
writer.JSONMarshaller = function(opts) {
    this.opts = opts || {};
    this.buffer = this.opts.buffer || (new sb.StringBuilder());
    this.prefersStrings = this.opts["prefersStrings"] != null ? this.opts["prefersStrings"] : true;

    this.objectBuilder = this.opts["objectBuilder"] || null;

    this.handlers = new handlers.Handlers();
    if(this.opts["handlers"]) {
        for(var i = 0; i < this.opts["handlers"].length; i+=2) {
            this.handlers.set(this.opts["handlers"][i], this.opts["handlers"][i+1]);
        }
    }

    this.verbose = (this.opts && this.opts["verbose"]) || false;
};

writer.JSONMarshaller.prototype.handler = function(obj) {
        return this.handlers.get(handlers.constructor(obj));
};

writer.JSONMarshaller.prototype.registerHandler = function(ctor, handler) {
    this.handlers.set(ctor, handler);
};

writer.JSONMarshaller.prototype.emitNil = function(asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "_", "", asMapKey, cache);
    } else {
        return null;
    }
};

writer.JSONMarshaller.prototype.emitString = function(prefix, tag, s, asMapKey, cache) {
    var string = prefix+tag+s;
    if(cache) {
        return cache.write(string, asMapKey);
    } else {
        return string;
    }
};

writer.JSONMarshaller.prototype.emitBoolean = function(b, asMapKey, cache) {
    if(asMapKey) {
        var s = b.toString();
        return this.emitString(d.ESC, "?", s[0], asMapKey, cache);
    } else {
        return b;
    }
};

writer.JSONMarshaller.prototype.emitInteger = function(i, asMapKey, cache) {
    if(asMapKey || (typeof i === "string") || (i instanceof Long)) {
        return this.emitString(d.ESC, "i", i.toString(), asMapKey, cache);
    } else {
        return i;
    }
};

writer.JSONMarshaller.prototype.emitDouble = function(d, asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "d", d, asMapKey, cache);
    } else {
        return d;
    }
};

writer.JSONMarshaller.prototype.emitBinary = function(b, asMapKey, cache) {
    return this.emitString(d.ESC, "b", b, asMapKey, cache);
};

writer.JSONMarshaller.prototype.emitQuoted = function(obj, cache) {
    var ret = {},
        k   = this.emitString(d.ESC_TAG, "'", "", true, cache);
    ret[k] = writer.marshal(this, obj, false, cache);
    return ret;
};

writer.emitInts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitShorts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitShort(em, src[i], false, cache));
    }
    return ret;
};

writer.emitLongs = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitFloats = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitFloat(em, src[i], false, cache));
    }
    return ret;
};

writer.emitDouble = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitDouble(em, src[i], false, cache));
    }
    return ret;
};

writer.emitChars = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(writer.marshal(em, src[i], false, cache));
    }
    return ret;
};

writer.emitBooleans = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitBoolean(em, src[i], false, cache));
    }
    return ret;
};

writer.emitObjects = function(em, iterable, cache) {
    var ret = [];
    if(Array.isArray(iterable)) {
        for(var i = 0; i < iterable.length; i++) {
            ret.push(writer.marshal(em, iterable[i], false, cache));
        }
    } else {
        iterable.forEach(function(v, i) {
            ret.push(writer.marshal(em, v, false, cache));
        });
    }
    return ret;
};

writer.emitArray = function(em, iterable, skip, cache) {
    if(iterable instanceof Int8Array) {
        return writer.emitChars(em, iterable, cache);
    } else if(iterable instanceof Int16Array) {
        return writer.emitShorts(em, iterable, cache);
    } else if(iterable instanceof Int32Array) {
        return writer.emitInts(em, iterable, cache);
    } else if(iterable instanceof Float32Array) {
        return writer.emitFloats(em, iterable, cache);
    } else if(iterable instanceof Float64Array) {
        return writer.emitDoubles(em, iterable, cache);
    } else {
        return writer.emitObjects(em, iterable, cache);
    }
};

writer.emitMap = function(em, obj, skip, cache) {
    if((obj.constructor === Object) || (obj.forEach != null)) {
        if(em.verbose) {
            var ret = {};
            if(obj.forEach != null) {
                obj.forEach(function(v, k) {
                    ret[writer.marshal(em, k, true, false)] = writer.marshal(em, v, false, cache);
                });
            } else {
                var ks  = Object.keys(obj);
                for(var i = 0; i < ks.length; i++) {
                    ret[writer.marshal(em, ks[i], true, false)] = writer.marshal(em, obj[ks[i]], false, cache);
                }
            }
            return ret;
        } else {
            var ret = ["^ "];
            if(obj.forEach != null) {
                obj.forEach(function(v, k) {
                    ret.push(writer.marshal(em, k, true, cache));
                    ret.push(writer.marshal(em, v, false, cache));
                });
            } else {
                var ks  = Object.keys(obj);
                for(var i = 0; i < ks.length; i++) {
                    ret.push(writer.marshal(em, ks[i], true, cache));
                    ret.push(writer.marshal(em, obj[ks[i]], false, cache));
                }
            }
            return ret;
        }
    } else if(em.objectBuilder != null) {
        return em.objectBuilder(obj, function(k) { return writer.marshal(em, k, true, cache);  },
                                     function(v) { return writer.marshal(em, v, false, cache); });
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.emitTaggedMap = function(em, tag, rep, skip, cache) {
    var ret = {};
    ret[em.emitString(d.ESC_TAG, tag, "", true, cache)] = writer.marshal(em, rep, false, cache);
    return ret;
};

writer.emitEncoded = function(em, h, tag, rep, obj, asMapKey, cache) {
    if(tag.length === 1) {
        if(typeof rep === "string") {
            return em.emitString(d.ESC, tag, rep, asMapKey, cache);
        } else if(asMapKey || em.prefersStrings) {
            var vh = em.verbose && h.getVerboseHandler();
            if(vh) {
                tag = vh.tag(obj);
                rep = vh.stringRep(obj, vh);
            } else {
                rep = h.stringRep(obj, h);
            }
            if(rep !== null) {
                return em.emitString(d.ESC, tag, rep, asMapKey, cache);
            } else {
                var err = new Error("Cannot be encoded as string");
                err.data = {tag: tag, rep: rep, obj: obj};
                throw err;
            }
        } else {
            return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
        }
    } else if (asMapKey) {
        var err = new Error("Cannot be used as map key");
        err.data = {tag: tag, rep: rep, obj: obj};
        throw err;
    } else {
        return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
    }
}

writer.marshal = function(em, obj, asMapKey, cache) {
    var h   = em.handler(obj),
        tag = h ? h.tag(obj) : null,
        rep = h ? h.rep(obj) : null;

    if(h != null && tag != null) {
        switch(tag) {
        case "_":
            return em.emitNil(asMapKey, cache);
            break;
        case "s":
            return em.emitString("", "", writer.escape(rep), asMapKey, cache);
            break;
        case "?":
            return em.emitBoolean(rep, asMapKey, cache);
            break;
        case "i":
            return em.emitInteger(rep, asMapKey, cache);
            break;
        case "d":
            return em.emitDouble(rep, asMapKey, cache);
            break;
        case "b":
            return em.emitBinary(rep, asMapKey, cache);
            break;
        case "'":
            return em.emitQuoted(rep, cache);
            break;
        case "array":
            return writer.emitArray(em, rep, asMapKey, cache);
            break;
        case "map":
            return writer.emitMap(em, rep, asMapKey, cache);
            break;
        default:
            return writer.emitEncoded(em, h, tag, rep, obj, asMapKey, cache);
            break;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.maybeQuoted = function(em, obj) {
    var h = em.handler(obj);

    if(h != null) {
        if(h.tag(obj).length === 1) {
            return types.quoted(obj);
        } else {
            return obj;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.marshalTop = function(em, obj, asMapKey, cache) {
    return JSON.stringify(writer.marshal(em, writer.maybeQuoted(em, obj), asMapKey, cache));
};

/**
 * @constructor
 */
writer.Writer = function(marshaller, options) {
    this.marshaller = marshaller;
    this.options = options || {};
    if(this.options["cache"] === false) {
        this.cache = null;
    } else {
        this.cache = this.options["cache"] ? this.options["cache"] : new caching.WriteCache();
    }
};

writer.Writer.prototype.write = function(obj, opts) {
    var ret      = null,
        ropts    = opts || {};
        asMapKey = ropts["asMapKey"] || false;

    if(ropts["marshalTop"] === false) {
        ret = writer.marshal(this.marshaller, obj, asMapKey, this.cache)
    } else {
        ret = writer.marshalTop(this.marshaller, obj, asMapKey, this.cache)
    }
    if(this.cache != null) {
        this.cache.clear();
    }
    return ret;
};
writer.Writer.prototype["write"] = writer.Writer.prototype.write;

writer.Writer.prototype.register = function(type, handler) {
    this.marshaller.registerHandler(type, handler);
};
writer.Writer.prototype["register"] = writer.Writer.prototype.register;

});
<|endoftext|>


<commit_before>////
//// Some unit testing for bbop-graph-noctua.
////
//// Keep in mind that we regularly import the tests from upstream
//// bbop-graph.
////

var assert = require('chai').assert;
var model = new require('..');

var us = require('underscore');
var each = us.each;

describe('test annotation', function(){

    it('works on its own', function(){

	var a1 = new model.annotation({'key': 'foo', 'value': 'bar'});

	// Id
	assert.isString(a1.id(), 'string id');
	assert.isAbove(a1.id().length, 5,'long string id');

	// Current.
	assert.equal(a1.key(), 'foo', 'has key');
	assert.equal(a1.value(), 'bar', 'has value');
	assert.equal(a1.value_type(), null, 'does not have value-type');

	// Write-over simple.
	assert.equal(a1.value('bib'), 'bib', 'has set value');
	assert.equal(a1.value(), 'bib', 'still has set value');

	// Write-over full.
	assert.deepEqual(a1.annotation('1', '2', '3'),
			 {'key': '1', 'value': '2', 'value-type': '3'}, 'redo');
	assert.equal(a1.value_type(), '3', 'now has value-type');
    });

});

describe('annotation bulk ops', function(){

    it('graph context extant', function(){
	var g = new model.graph();
	assert.isFunction(g.get_annotation_by_id, 'annotation attached to');
    });

    it('works in graph context', function(){

	var g = new model.graph();

	var a1 = new model.annotation({'key': 'foo', 'value': 'bar'});
	var a2 = new model.annotation({'key': 'bib', 'value': 'bab'});

	var a1_id = a1.id();
	var a2_id = a2.id();

	g.add_annotation(a1);
	g.add_annotation(a2);

	assert.equal(a1_id, g.get_annotation_by_id(a1_id).id(),
		     'get annotation by id');
	assert.equal(g.annotations().length, 2,
		     'two annotations in');

	function filter(ann){
	    var ret = false;
	    if( ann.key() == 'foo' ){
		ret = true;
	    }
	    return ret;
	}
	assert.equal(g.get_annotations_by_filter(filter).length, 1,
		     'one annotation by filter');
    });
});

describe('trivial isolated graph ops', function(){
    it('subclassing works', function(){

	var g = new model.graph();
	assert.isNull(g.id(), 'no default id');
	assert.equal(g.add_id('foo'), 'foo', 'new id');
	assert.equal(g.id(), 'foo', 'also new id');
	assert.equal(g.get_id(), 'foo', 'and also new id');
    });
});

describe('looking for edges', function(){

    it('by id', function(){

	var g = new model.graph();
	var n1 = new model.node('a');
	var n2 = new model.node('b');
	var e1 = new model.edge('a', 'b');
	g.add_node(n1);
	g.add_node(n2);
	g.add_edge(e1);

	assert.equal(g.get_edge_by_id(e1.id()).id(), e1.id(), 'same edge id');
	assert.deepEqual(g.get_edge_by_id(e1.id()), e1, 'same edge');
	assert.isNull(g.get_edge_by_id('foo'), 'no edge');
    });
});

describe('flex new framework', function(){

    it('can we eat a minerva response?', function(){

	// Setup.
	var raw_resp = require('./minerva-01.json');
	var g = new model.graph();
	g.load_data_base(raw_resp['data']);

	// Right?
	assert.isDefined(raw_resp['data']['individuals'],
			      'pulled in right example');
    });

    it('basic graph checks', function(){

	// Setup.
	var raw_resp = require('./minerva-01.json');
	var g = new model.graph();
	g.load_data_base(raw_resp['data']);

	assert.equal(g.id(),'gomodel:taxon_559292-5525a0fc0000001_all_indivdual',
		     'graph id');
	assert.equal(g.annotations().length, 4, '4 graph annotation');
	var anns = g.get_annotations_by_key('date');
	assert.equal(anns.length, 1, 'one date annotation');
	assert.equal(anns[0].value(), '2015-04-10', 'correct date annotation');

	// Wee tests.
	assert.equal(g.all_nodes().length, 22, 'right num nodes');
	assert.equal(g.all_edges().length, 14, 'right num edges');

	// More exploring.
	assert.equal(g.get_singleton_nodes().length, 8, 'ev makes singletons');
	assert.equal(g.get_root_nodes().length, 17, 'technically lots of roots');
	assert.equal(g.get_leaf_nodes().length, 9, 'leaves are ev + 1 here');
    });

    it("let's go for a walk in the neighborhood", function(){

	// Setup.
	var raw_resp = require('./minerva-01.json');
	var g = new model.graph();
	g.load_data_base(raw_resp['data']);

	// Head up from our one leaf
	var nid = 'gomodel:taxon_559292-5525a0fc0000001-GO-0005515-5525a0fc0000023';
	var n = g.get_node(nid);
	assert.equal(n.id(), nid, 'got the node');

	// Step around.
	var all_pnodes = g.get_parent_nodes(n.id());
	var enb_pnodes = g.get_parent_nodes(n.id(),'RO:0002333');
	assert.equal(all_pnodes.length, 5, '5 parents');
	assert.equal(enb_pnodes.length, 1, 'but 1 enabled_by parent');

	var e = enb_pnodes[0];

	// Take a look at the types of e closely.
	var ts = e.types();
	assert.equal(ts.length, 1, 'one associated type');
	var t = ts[0];
	assert.equal(t.class_label(), 'SGD:S000004659', 'labeled with SGD');

	// Take a look at the annotations of e closely.
	var all_anns = e.annotations();
	assert.equal(all_anns.length, 2, 'two associated annotations');
	var anns = e.get_annotations_by_key('date');
	assert.equal(anns.length, 1, 'one date annotation');
	assert.equal(anns[0].value(), '2015-04-14', 'correct date annotation');

    });

    it("evidence that evidence works", function(){

	// Setup.
	var raw_resp = require('./minerva-01.json');
	var g = new model.graph();
	g.load_data_fold_evidence(raw_resp['data']);

	// Okay, we should have a lot less nodes now.
	assert.equal(g.all_nodes().length, 14, '22 - 8 ev nodes = 14');

	// Let's track down the evidence for one node.
	var nid = 'gomodel:taxon_559292-5525a0fc0000001-GO-0005515-5525a0fc0000023';
	var n = g.get_node(nid);
	assert.equal(n.id(), nid, 'some weirdness here at one point');

	// The hard way.
	var ri = n.referenced_individuals();
	assert.equal(ri.length, 1, 'one piece of ev');
	var ev_ind = ri[0];
	var types = ev_ind.types();
	assert.equal(types.length, 1, 'one class exp');
	var t = types[0];
	assert.equal(t.class_id(), 'ECO:0000021', 'say hi');

	// The easy way.
	var profs = n.get_referenced_individual_profiles();
	assert.equal(profs.length, 1, 'one profile using this method');
	var first_prof = profs[0];
	assert.isNotNull(first_prof.id, 'has id using this method');
	assert.equal(first_prof.class_expressions.length, 1,
		     'one ce using this method');
	assert.equal(first_prof.annotations.length, 1,
		     'one ann using this method');

	// The overly easy super-simple (GO) way.
	var evs = n.get_basic_evidence(['source']);
	//console.log(evs);
	assert.equal(evs.length, 1, 'one evs');
	var ev = evs[0];
	assert.isString(ev['id'], 'got RI id');
	assert.equal(ev['cls'], 'ECO:0000021', 'got ev class');
	assert.equal(ev['source'], 'PMID:12048186', 'got source ref');
    });
});

// var assert = require('chai').assert;
// var model = new require('..');
// var us = require('underscore');
// var each = us.each;
// var keys = us.keys;
// var raw_resp = require('./minerva-01.json');
// var g = new model.graph();
// g.load_data_fold_evidence(raw_resp['data']);
<commit_msg>check that merge works<commit_after>////
//// Some unit testing for bbop-graph-noctua.
////
//// Keep in mind that we regularly import the tests from upstream
//// bbop-graph.
////

var assert = require('chai').assert;
var model = new require('..');

var us = require('underscore');
var each = us.each;

describe('test annotation', function(){

    it('works on its own', function(){

	var a1 = new model.annotation({'key': 'foo', 'value': 'bar'});

	// Id
	assert.isString(a1.id(), 'string id');
	assert.isAbove(a1.id().length, 5,'long string id');

	// Current.
	assert.equal(a1.key(), 'foo', 'has key');
	assert.equal(a1.value(), 'bar', 'has value');
	assert.equal(a1.value_type(), null, 'does not have value-type');

	// Write-over simple.
	assert.equal(a1.value('bib'), 'bib', 'has set value');
	assert.equal(a1.value(), 'bib', 'still has set value');

	// Write-over full.
	assert.deepEqual(a1.annotation('1', '2', '3'),
			 {'key': '1', 'value': '2', 'value-type': '3'}, 'redo');
	assert.equal(a1.value_type(), '3', 'now has value-type');
    });

});

describe('annotation bulk ops', function(){

    it('graph context extant', function(){
	var g = new model.graph();
	assert.isFunction(g.get_annotation_by_id, 'annotation attached to');
    });

    it('works in graph context', function(){

	var g = new model.graph();

	var a1 = new model.annotation({'key': 'foo', 'value': 'bar'});
	var a2 = new model.annotation({'key': 'bib', 'value': 'bab'});

	var a1_id = a1.id();
	var a2_id = a2.id();

	g.add_annotation(a1);
	g.add_annotation(a2);

	assert.equal(a1_id, g.get_annotation_by_id(a1_id).id(),
		     'get annotation by id');
	assert.equal(g.annotations().length, 2,
		     'two annotations in');

	function filter(ann){
	    var ret = false;
	    if( ann.key() == 'foo' ){
		ret = true;
	    }
	    return ret;
	}
	assert.equal(g.get_annotations_by_filter(filter).length, 1,
		     'one annotation by filter');
    });
});

describe('trivial isolated graph ops', function(){
    it('subclassing works', function(){

	var g = new model.graph();
	assert.isNull(g.id(), 'no default id');
	assert.equal(g.add_id('foo'), 'foo', 'new id');
	assert.equal(g.id(), 'foo', 'also new id');
	assert.equal(g.get_id(), 'foo', 'and also new id');
    });
});

describe('looking for edges', function(){

    it('by id', function(){

	var g = new model.graph();
	var n1 = new model.node('a');
	var n2 = new model.node('b');
	var e1 = new model.edge('a', 'b');
	g.add_node(n1);
	g.add_node(n2);
	g.add_edge(e1);

	assert.equal(g.get_edge_by_id(e1.id()).id(), e1.id(), 'same edge id');
	assert.deepEqual(g.get_edge_by_id(e1.id()), e1, 'same edge');
	assert.isNull(g.get_edge_by_id('foo'), 'no edge');
    });
});

describe('flex new framework', function(){

    it('can we eat a minerva response?', function(){

	// Setup.
	var raw_resp = require('./minerva-01.json');
	var g = new model.graph();
	g.load_data_base(raw_resp['data']);

	// Right?
	assert.isDefined(raw_resp['data']['individuals'],
			      'pulled in right example');
    });

    it('basic graph checks', function(){

	// Setup.
	var raw_resp = require('./minerva-01.json');
	var g = new model.graph();
	g.load_data_base(raw_resp['data']);

	assert.equal(g.id(),'gomodel:taxon_559292-5525a0fc0000001_all_indivdual',
		     'graph id');
	assert.equal(g.annotations().length, 4, '4 graph annotation');
	var anns = g.get_annotations_by_key('date');
	assert.equal(anns.length, 1, 'one date annotation');
	assert.equal(anns[0].value(), '2015-04-10', 'correct date annotation');

	// Wee tests.
	assert.equal(g.all_nodes().length, 22, 'right num nodes');
	assert.equal(g.all_edges().length, 14, 'right num edges');

	// More exploring.
	assert.equal(g.get_singleton_nodes().length, 8, 'ev makes singletons');
	assert.equal(g.get_root_nodes().length, 17, 'technically lots of roots');
	assert.equal(g.get_leaf_nodes().length, 9, 'leaves are ev + 1 here');
    });

    it("let's go for a walk in the neighborhood", function(){

	// Setup.
	var raw_resp = require('./minerva-01.json');
	var g = new model.graph();
	g.load_data_base(raw_resp['data']);

	// Head up from our one leaf
	var nid = 'gomodel:taxon_559292-5525a0fc0000001-GO-0005515-5525a0fc0000023';
	var n = g.get_node(nid);
	assert.equal(n.id(), nid, 'got the node');

	// Step around.
	var all_pnodes = g.get_parent_nodes(n.id());
	var enb_pnodes = g.get_parent_nodes(n.id(),'RO:0002333');
	assert.equal(all_pnodes.length, 5, '5 parents');
	assert.equal(enb_pnodes.length, 1, 'but 1 enabled_by parent');

	var e = enb_pnodes[0];

	// Take a look at the types of e closely.
	var ts = e.types();
	assert.equal(ts.length, 1, 'one associated type');
	var t = ts[0];
	assert.equal(t.class_label(), 'SGD:S000004659', 'labeled with SGD');

	// Take a look at the annotations of e closely.
	var all_anns = e.annotations();
	assert.equal(all_anns.length, 2, 'two associated annotations');
	var anns = e.get_annotations_by_key('date');
	assert.equal(anns.length, 1, 'one date annotation');
	assert.equal(anns[0].value(), '2015-04-14', 'correct date annotation');

    });

    it("evidence that evidence works", function(){

	// Setup.
	var raw_resp = require('./minerva-01.json');
	var g = new model.graph();
	g.load_data_fold_evidence(raw_resp['data']);

	// Okay, we should have a lot less nodes now.
	assert.equal(g.all_nodes().length, 14, '22 - 8 ev nodes = 14');

	// Let's track down the evidence for one node.
	var nid = 'gomodel:taxon_559292-5525a0fc0000001-GO-0005515-5525a0fc0000023';
	var n = g.get_node(nid);
	assert.equal(n.id(), nid, 'some weirdness here at one point');

	// The hard way.
	var ri = n.referenced_individuals();
	assert.equal(ri.length, 1, 'one piece of ev');
	var ev_ind = ri[0];
	var types = ev_ind.types();
	assert.equal(types.length, 1, 'one class exp');
	var t = types[0];
	assert.equal(t.class_id(), 'ECO:0000021', 'say hi');

	// The easy way.
	var profs = n.get_referenced_individual_profiles();
	assert.equal(profs.length, 1, 'one profile using this method');
	var first_prof = profs[0];
	assert.isNotNull(first_prof.id, 'has id using this method');
	assert.equal(first_prof.class_expressions.length, 1,
		     'one ce using this method');
	assert.equal(first_prof.annotations.length, 1,
		     'one ann using this method');

	// The overly easy super-simple (GO) way.
	var evs = n.get_basic_evidence(['source']);
	//console.log(evs);
	assert.equal(evs.length, 1, 'one evs');
	var ev = evs[0];
	assert.isString(ev['id'], 'got RI id');
	assert.equal(ev['cls'], 'ECO:0000021', 'got ev class');
	assert.equal(ev['source'], 'PMID:12048186', 'got source ref');
    });
});

describe('merging works as expected', function(){

    it("we've got to merge it merge it", function(){

	// Setup.
	var g_base = new model.graph();
	var raw_resp = require('./minerva-01.json');
	var g_new = new model.graph();
	g_new.load_data_fold_evidence(raw_resp['data']);

	// Empty g_base should now essentially be g_new.
	g_base.merge_in(g_new);

	// Check it, make sure that bbop-graph-noctua structures are
	// all present.
	assert.equal(g_base.all_nodes().length, 14, 'right num nodes');
	assert.equal(g_base.all_edges().length, 14, 'right num edges');
	var a_node = g_base.all_nodes()[0];
	assert.isString(g_base.get_node_elt_id(a_node.id()),
			'generated elt_id');
    });

});

// var assert = require('chai').assert;
// var model = new require('..');
// var us = require('underscore');
// var each = us.each;
// var keys = us.keys;
// var raw_resp = require('./minerva-01.json');
// var g = new model.graph();
// g.load_data_fold_evidence(raw_resp['data']);
<|endoftext|>


<commit_before>var debug = require('debug')('amqp-nice:config:tests')
var assert = require('assert')
var _ = require('lodash').runInContext()
var async = require('async')
var amqplib = require('amqplib/callback_api')
var testConfig = require('../lib/config/tests')
var format = require('util').format
var uuid = require('node-uuid').v4
var Broker = require('..').Broker
var AmqpUtils = require('./utils/amqputils')

_.mixin({ 'defaultsDeep': require('merge-defaults') });

describe('Publications', function() {

    this.timeout(2000)
    this.slow(1000)

    var broker = undefined
    var amqputils = undefined
    var namespace = uuid()

    var vhosts = {
        v1: {
            namespace: namespace,
            exchanges: {
                e1: {
                    assert: true
                }
            },
            queues: {
                q1: {
                    exclusive: false,
                    assert: true
                }
            },
            bindings: {
                b1: {
                    source: 'e1',
                    destination: 'q1'
                }
            }
        }
    }

    before(function(done) {
        amqplib.connect(function(err, connection) {
            if (err) return done(err)
            amqputils = AmqpUtils.init(connection)
            done()
        })
    })

    after(function(done) {
        if (broker) return broker.nuke(done)
        done()
    })

    it('should publish text messages to normal exchanges', function(done) {

        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    exchange: 'e1'
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', 'test message', function(err) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, 'test message', done)
            })
        })
    })

    it('should publish text messages to confirm exchanges', function(done) {
        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    exchange: 'e1',
                    confirm: true
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', 'test message', function(err, ok) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, 'test message', done)
            })
        })
    })

    it('should publish text messages to queues', function(done) {
        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    queue: 'q1'
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', 'test message', function(err, ok) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, 'test message', done)
            })
        })
    })

    it('should publish to confirm queues', function(done) {
        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    queue: 'q1',
                    confirm: true
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', 'test message', function(err, ok) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, 'test message', done)
            })
        })
    })

    function createBroker(config, next) {
        config = _.defaultsDeep(config, testConfig)
        Broker.create(config, function(err, _broker) {
            broker = _broker
            next(err, broker)
        })
    }

    function checkExchange(present, name, namespace, next) {
        testConnection.createChannel(function(err, channel) {
            assert.ifError(err)
            channel.checkExchange(namespace + ':' + name, function(err, ok) {
                present ? assert(!err) : assert(!!err)
                next()
            })
        })
    }

    function checkQueue(present, name, namespace, next) {
        testConnection.createChannel(function(err, channel) {
            assert.ifError(err)
            channel.checkQueue(namespace + ':' + name, function(err, ok) {
                present ? assert(!err) : assert(!!err)
                next()
            })
        })
    }

    var publishMessage = _.curry(function(exchange, namespace, message, next) {
        testConnection.createChannel(function(err, channel) {
            assert.ifError(err)
            channel.publish(namespace + ':' + exchange, '', new Buffer(message))
            next()
        })
    })

    var getMessage = _.curry(function(queue, namespace, next) {
         testConnection.createChannel(function(err, channel) {
            assert.ifError(err)
            channel.get(namespace + ':' + queue, { noAck: true }, function(err, message) {
                if (err) return next(err)
                next(null, message.content.toString())
            })
        })
    })

    var assertExchangePresent = checkExchange.bind(null, true)
    var assertExchangeAbsent = checkExchange.bind(null, false)
    var assertQueuePresent = checkQueue.bind(null, true)
    var assertQueueAbsent = checkQueue.bind(null, false)

})<commit_msg>Beefing up tests<commit_after>var debug = require('debug')('amqp-nice:config:tests')
var assert = require('assert')
var _ = require('lodash').runInContext()
var async = require('async')
var amqplib = require('amqplib/callback_api')
var testConfig = require('../lib/config/tests')
var format = require('util').format
var uuid = require('node-uuid').v4
var Broker = require('..').Broker
var AmqpUtils = require('./utils/amqputils')

_.mixin({ 'defaultsDeep': require('merge-defaults') });

describe('Publications', function() {

    this.timeout(2000)
    this.slow(1000)

    var broker = undefined
    var amqputils = undefined
    var namespace = uuid()

    var vhosts = {
        v1: {
            namespace: namespace,
            exchanges: {
                e1: {
                    assert: true
                }
            },
            queues: {
                q1: {
                    exclusive: false,
                    assert: true
                }
            },
            bindings: {
                b1: {
                    source: 'e1',
                    destination: 'q1'
                }
            }
        }
    }

    before(function(done) {
        amqplib.connect(function(err, connection) {
            if (err) return done(err)
            amqputils = AmqpUtils.init(connection)
            done()
        })
    })

    after(function(done) {
        if (broker) return broker.nuke(done)
        done()
    })

    it('should publish text messages to normal exchanges', function(done) {

        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    exchange: 'e1'
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', 'test message', function(err) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, 'test message', done)
            })
        })
    })

    it('should publish text messages to confirm exchanges', function(done) {
        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    exchange: 'e1',
                    confirm: true
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', 'test message', function(err, ok) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, 'test message', done)
            })
        })
    })

    it('should publish text messages to queues', function(done) {
        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    queue: 'q1'
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', 'test message', function(err, ok) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, 'test message', done)
            })
        })
    })

    it('should publish to confirm queues', function(done) {
        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    queue: 'q1',
                    confirm: true
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', 'test message', function(err, ok) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, 'test message', done)
            })
        })
    })

    it('should publish json messages to normal exchanges', function(done) {

        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    exchange: 'e1'
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', { message: 'test message' }, function(err) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, JSON.stringify({ message: 'test message' }), done)
            })
        })
    })

    it('should publish buffer messages to normal exchanges', function(done) {

        createBroker({
            vhosts: vhosts,
            publications: {
                p1: {
                    vhost: 'v1',
                    exchange: 'e1'
                }
            }
        }, function(err, broker) {
            assert.ifError(err)
            broker.publish('p1', new Buffer('test message'), function(err) {
                assert.ifError(err)
                amqputils.assertMessage('q1', namespace, 'test message', done)
            })
        })
    })

    function createBroker(config, next) {
        config = _.defaultsDeep(config, testConfig)
        Broker.create(config, function(err, _broker) {
            broker = _broker
            next(err, broker)
        })
    }

    function checkExchange(present, name, namespace, next) {
        testConnection.createChannel(function(err, channel) {
            assert.ifError(err)
            channel.checkExchange(namespace + ':' + name, function(err, ok) {
                present ? assert(!err) : assert(!!err)
                next()
            })
        })
    }

    function checkQueue(present, name, namespace, next) {
        testConnection.createChannel(function(err, channel) {
            assert.ifError(err)
            channel.checkQueue(namespace + ':' + name, function(err, ok) {
                present ? assert(!err) : assert(!!err)
                next()
            })
        })
    }

    var publishMessage = _.curry(function(exchange, namespace, message, next) {
        testConnection.createChannel(function(err, channel) {
            assert.ifError(err)
            channel.publish(namespace + ':' + exchange, '', new Buffer(message))
            next()
        })
    })

    var getMessage = _.curry(function(queue, namespace, next) {
         testConnection.createChannel(function(err, channel) {
            assert.ifError(err)
            channel.get(namespace + ':' + queue, { noAck: true }, function(err, message) {
                if (err) return next(err)
                next(null, message.content.toString())
            })
        })
    })

    var assertExchangePresent = checkExchange.bind(null, true)
    var assertExchangeAbsent = checkExchange.bind(null, false)
    var assertQueuePresent = checkQueue.bind(null, true)
    var assertQueueAbsent = checkQueue.bind(null, false)

})<|endoftext|>


<commit_before>'use strict';

var expect = require('chai').expect;

describe('ScatterChart', function() {
  it('renders scatterchart', function() {
    var React = require('react/addons');
    var ScatterChart = require('../src/scatterchart').ScatterChart;
    var immstruct = require('immstruct');
    var generate = require('./utils/datagen').generateArrayOfPoints;
    var TestUtils = React.addons.TestUtils;
    var points = 5;
    var pointRadius = 5;

    var structure = immstruct('scatterChart', { voronoi: {}, voronoiSeries: {}});

    // Render a scatterchart
    var data = [
      {
        name: "series1",
        values: generate(points)
      },
      {
        name: "series2",
        values: generate(points)
      }
    ];

    var scatterchart = TestUtils.renderIntoDocument(
      <ScatterChart structure={structure} data={data} width={400} height={200} pointRadius={pointRadius} />
    );

    var scatterchartGroup = TestUtils.findRenderedDOMComponentWithClass(
      scatterchart, 'rd3-scatterchart');
    expect(scatterchartGroup).to.exist;
    expect(scatterchartGroup.tagName).to.equal('G');

    var circles = TestUtils.scryRenderedDOMComponentsWithClass(
      scatterchart, 'rd3-scatterchart-circle');
    expect(circles).to.have.length(Object.keys(data).length * points);

    var circleOne = circles[0];
    var circleOneColor = circleOne.props.fill;

    expect(circleOne.props.r).to.equal(pointRadius);
    structure.cursor('voronoi').cursor(circleOne.props.id).update(()=> 'active' );
    expect(circleOne.props.r).to.be.above(pointRadius);
    expect(circleOne.props.fill).to.not.equal(circleOneColor);

    structure.cursor('voronoi').cursor(circleOne.props.id).update(()=> 'inactive' );
    expect(circleOne.props.r).to.equal(pointRadius);
    expect(circleOne.props.fill).to.equal(circleOneColor);
  });
});
<commit_msg>Modify test for scatterchart-tests. Clearer test<commit_after>'use strict';

var expect = require('chai').expect;

describe('ScatterChart', function() {
  it('renders scatterchart', function() {
    var React = require('react/addons');
    var ScatterChart = require('../src/scatterchart').ScatterChart;
    var immstruct = require('immstruct');
    var generate = require('./utils/datagen').generateArrayOfPoints;
    var TestUtils = React.addons.TestUtils;
    var points = 5;
    var pointRadius = 5;

    var structure = immstruct('scatterChart', { voronoi: {}, voronoiSeries: {}});

    // Render a scatterchart
    var data = [
      {
        name: "series1",
        values: generate(points)
      },
      {
        name: "series2",
        values: generate(points)
      }
    ];

    var scatterchart = TestUtils.renderIntoDocument(
      <ScatterChart structure={structure} data={data} width={400} height={200} pointRadius={pointRadius} />
    );

    var scatterchartGroup = TestUtils.findRenderedDOMComponentWithClass(
      scatterchart, 'rd3-scatterchart');
    expect(scatterchartGroup).to.exist;
    expect(scatterchartGroup.tagName).to.equal('G');

    var circles = TestUtils.scryRenderedDOMComponentsWithClass(
      scatterchart, 'rd3-scatterchart-circle');
    expect(circles).to.have.length(Object.keys(data).length * points);

    var circleOne = circles[0];
    var circleOneColor = circleOne.props.fill;

    expect(circleOne.props.r).to.equal(pointRadius);
    // seems unnatural, dislike this approach
    //structure.cursor('voronoi').cursor(circleOne.props.id).update(()=> 'active' );
    TestUtils.Simulate.mouseOver(circleOne);
    expect(circleOne.props.r).to.be.above(pointRadius);
    expect(circleOne.props.fill).to.not.equal(circleOneColor);

    //structure.cursor('voronoi').cursor(circleOne.props.id).update(()=> 'inactive' );
    // https://github.com/facebook/react/issues/1297
    TestUtils.SimulateNative.mouseOut(circleOne);
    expect(circleOne.props.r).to.equal(pointRadius);
    expect(circleOne.props.fill).to.equal(circleOneColor);
  });
});
<|endoftext|>


<commit_before>import {layout as reducer, initialState} from 'reducers/layout'
import {
	UI_CLOSE_SIDEBAR,
	UI_OPEN_SIDEBAR,
	UI_WINDOW_RESIZE
} from 'actions/layout'
import {LOCATION_CHANGE, APPLICATION_INIT} from 'actions/common'

const closeSidebar = {
	type: UI_CLOSE_SIDEBAR
}

const openSidebar = {
	type: UI_OPEN_SIDEBAR
}

const locationChange = {
	type: LOCATION_CHANGE
}

const windowResize = {
	type: UI_WINDOW_RESIZE,
	payload: {
		innerWidth: 1280
	}
}

const appInit = {
	type: UI_WINDOW_RESIZE,
	payload: {
		innerWidth: 360
	}
}

describe('LAYOUT REDUCER', () => {
	it('should return the initial state', () => {
		expect(reducer(undefined, {x: 'string'})).toEqual(initialState)
	})

	it('should handle UI_OPEN_SIDEBAR', () => {
		expect(reducer(initialState, openSidebar)).toEqual({
			...initialState,
			sidebarOpened: true
		})
	})

	describe('Mobile properties', () => {
		it('should handle WINDOW_RESIZE with 360px screen', () => {
			expect(reducer(initialState, appInit)).toEqual({
				...initialState,
				isMobile: true,
				isMobileXS: true,
				isMobileSM: false
			})
		})

		it('should handle WINDOW_RESIZE with 1280px screen', () => {
			expect(reducer(initialState, windowResize)).toEqual({
				...initialState,
				isMobile: false,
				isMobileXS: false,
				isMobileSM: false
			})
		})
	})

	it('should handle UI_CLOSE_SIDEBAR', () => {
		expect(reducer(initialState, closeSidebar)).toEqual({
			...initialState,
			sidebarOpened: false
		})
	})

	it('should handle LOCATION_CHANGE', () => {
		expect(reducer(initialState, locationChange)).toEqual({
			...initialState,
			sidebarOpened: false
		})
	})
})
<commit_msg>fix(reducers/layout): remove APPLICATION_INIT<commit_after>import {layout as reducer, initialState} from 'reducers/layout'
import {
	UI_CLOSE_SIDEBAR,
	UI_OPEN_SIDEBAR,
	UI_WINDOW_RESIZE
} from 'actions/layout'
import {LOCATION_CHANGE} from 'actions/common'

const closeSidebar = {
	type: UI_CLOSE_SIDEBAR
}

const openSidebar = {
	type: UI_OPEN_SIDEBAR
}

const locationChange = {
	type: LOCATION_CHANGE
}

const windowResize = {
	type: UI_WINDOW_RESIZE,
	payload: {
		innerWidth: 1280
	}
}

const appInit = {
	type: UI_WINDOW_RESIZE,
	payload: {
		innerWidth: 360
	}
}

describe('LAYOUT REDUCER', () => {
	it('should return the initial state', () => {
		expect(reducer(undefined, {x: 'string'})).toEqual(initialState)
	})

	it('should handle UI_OPEN_SIDEBAR', () => {
		expect(reducer(initialState, openSidebar)).toEqual({
			...initialState,
			sidebarOpened: true
		})
	})

	describe('Mobile properties', () => {
		it('should handle WINDOW_RESIZE with 360px screen', () => {
			expect(reducer(initialState, appInit)).toEqual({
				...initialState,
				isMobile: true,
				isMobileXS: true,
				isMobileSM: false
			})
		})

		it('should handle WINDOW_RESIZE with 1280px screen', () => {
			expect(reducer(initialState, windowResize)).toEqual({
				...initialState,
				isMobile: false,
				isMobileXS: false,
				isMobileSM: false
			})
		})
	})

	it('should handle UI_CLOSE_SIDEBAR', () => {
		expect(reducer(initialState, closeSidebar)).toEqual({
			...initialState,
			sidebarOpened: false
		})
	})

	it('should handle LOCATION_CHANGE', () => {
		expect(reducer(initialState, locationChange)).toEqual({
			...initialState,
			sidebarOpened: false
		})
	})
})
<|endoftext|>


<commit_before>const poker = require('../poker');
const chai = require('chai');

describe('Poker', () => {
    describe('#decide()', () => {
        it('Kamikaze', () => {
            chai.assert.deepEqual(
                {
                    action: 'allIn',
                    strategy: 'kamikaze'
                },
                poker.decide(
                    {
                        "round": 18,
                        "players": [
                            {
                                "name": "Friendly Dog",
                                "status": "active"
                            },
                            {
                                "name": "Sneaky",
                                "status": "out"
                            },
                            {
                                "name": "Texas Nodem",
                                "status": "active",
                                "hole_cards": [
                                    {
                                        "rank": "8",
                                        "suit": "hearts"
                                    },
                                    {
                                        "rank": "8",
                                        "suit": "spades"
                                    }
                                ]
                            },
                            {
                                "name": "Always all in",
                                "status": "active"
                            },
                            {
                                "name": "GOgliG",
                                "status": "out"
                            }
                        ],
                        "community_cards": [],
                        "minimum_raise": 30
                    }
                )
            );
        });
    });
});
<commit_msg>Test kamikaze for good cards<commit_after>const poker = require('../poker');
const chai = require('chai');

describe('Poker', () => {
    describe('#decide()', () => {
        it('Kamikaze when Sneaky is out', () => {
            chai.assert.deepEqual(
                {
                    action: 'allIn',
                    strategy: 'kamikaze'
                },
                poker.decide(
                    {
                        "round": 18,
                        "players": [
                            {
                                "name": "Friendly Dog",
                                "status": "active"
                            },
                            {
                                "name": "Sneaky",
                                "status": "out"
                            },
                            {
                                "name": "Texas Nodem",
                                "status": "active",
                                "hole_cards": [
                                    {
                                        "rank": "8",
                                        "suit": "hearts"
                                    },
                                    {
                                        "rank": "8",
                                        "suit": "spades"
                                    }
                                ]
                            },
                            {
                                "name": "Always all in",
                                "status": "active"
                            },
                            {
                                "name": "GOgliG",
                                "status": "out"
                            }
                        ],
                        "community_cards": [],
                        "minimum_raise": 30
                    }
                )
            );
        });
        it('Kamikaze when cards are good', () => {
            chai.assert.deepEqual(
                {
                    action: 'allIn',
                    strategy: 'kamikaze'
                },
                poker.decide(
                    {
                        "round": 18,
                        "players": [
                            {
                                "name": "Friendly Dog",
                                "status": "active"
                            },
                            {
                                "name": "Sneaky",
                                "status": "active"
                            },
                            {
                                "name": "Texas Nodem",
                                "status": "active",
                                "hole_cards": [
                                    {
                                        "rank": "A",
                                        "suit": "hearts"
                                    },
                                    {
                                        "rank": "8",
                                        "suit": "spades"
                                    }
                                ]
                            },
                            {
                                "name": "Always all in",
                                "status": "active"
                            },
                            {
                                "name": "GOgliG",
                                "status": "out"
                            }
                        ],
                        "community_cards": [],
                        "minimum_raise": 30
                    }
                )
            );
        });
    });
});
<|endoftext|>


<commit_before>var cfg = require('../dummyserver-config');
var httpinvoke = require('../httpinvoke-node');

describe('"downloading" option', function() {
    this.timeout(10000);
    // TODO after receiving first defined total - no undefined can be received
    // TODO total can be undefined
    // TODO the last total is always defined, and if there is no entity body - it is 0
    // TODO check if current is correct when Content-Encoding is gzip
    // TODO do all of these tests for various binary and variously encoded text responses
    cfg.eachBase(function(postfix, url, crossDomain) {
        it('is called at least twice' + postfix, function(done) {
            var count = 0;
            var abort = httpinvoke(url, {
                downloading: function() {
                    count += 1;
                    if(count === 2) {
                        done();
                        done = null;
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    if(count < 2) {
                        done(new Error('It was called ' + count + ' times'));
                    }
                    abort();
                }
            });
        });
        it('has "current" and "total" be non-negative integers' + postfix, function(done) {
            var fail = function(msg) {
                done(new Error(msg));
                done = null;
            };
            httpinvoke(url, {
                downloading: function(current, total) {
                    if(typeof total === 'undefined') {
                        return;
                    }
                    if(done === null) {
                        return;
                    }
                    if(typeof current !== 'number') {
                        return fail('"current" was not a number');
                    }
                    if(current % 1 !== 0) {
                        return fail('"current" was not an integer');
                    }
                    if(current < 0) {
                        return fail('"current" was not an non-negative');
                    }
                    if(typeof total !== 'number') {
                        return fail('"total" was not a number');
                    }
                    if(total % 1 !== 0) {
                        return fail('"total" was not an integer, because the result of (total % 1) is ' + (total % 1));
                    }
                    if(total < 0) {
                        return fail('"total" was not an non-negative');
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    done();
                }
            });
        });
        it('has the last "current" be equal to total' + postfix, function(done) {
            var current, total;
            httpinvoke(url, {
                downloading: function(_current, _total) {
                    current = _current;
                    total = _total;
                },
                finished: function(err) {
                    if(err) {
                        return done(err);
                    }
                    if(current !== total) {
                        done(new Error('The last received "current"=' + current + ' is not equal to "total"=' + total));
                    } else {
                        done();
                    }
                }
            });
        });
        it('has the first "current" be equal to 0' + postfix, function(done) {
            var abort = httpinvoke(url, {
                downloading: function(current) {
                    if(done === null) {
                        return;
                    }
                    if(current !== 0) {
                        done(new Error('First "current" is not equal to 0: ' + current));
                    } else {
                        done();
                    }
                    done = null;
                    abort();
                }
            });
        });
        it('has "current" not greater than "total"' + postfix, function(done) {
            httpinvoke(url, {
                downloading: function(current, total) {
                    if(current > total) {
                        done(new Error('"current" was greater than "total"'));
                        done = null;
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    done();
                }
            });
        });
        it('has "total" always be the same' + postfix, function(done) {
            var total = null;
            httpinvoke(url, {
                downloading: function(current, _total) {
                    if(typeof _total === 'undefined') {
                        return;
                    }
                    if(done === null) {
                        return;
                    }
                    if(total === null) {
                        total = _total;
                        return;
                    }
                    if(total !== _total) {
                        done(new Error('Received "total"=' + _total + ' that is different from previously received "total"=' + total));
                        done = null;
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    done();
                }
            });
        });
        it('has the last "total" be equal to output length, when outputType="bytearray"' + postfix, function(done) {
            var total = null;
            httpinvoke(url, {
                outputType: 'bytearray',
                downloading: function(_, _total) {
                    total = _total;
                },
                finished: function(err, output) {
                    if(err) {
                        return done(err);
                    }
                    if(output.length !== total) {
                        done(new Error('The last "total"=' + total + ' was not equal to output length = ' + output.length));
                    } else {
                        done();
                    }
                }
            });
        });
        it('has "current" be non-decreasing' + postfix, function(done) {
            var current = null;
            httpinvoke(url, {
                downloading: function(_current) {
                    if(done === null) {
                        return;
                    }
                    if(current === null) {
                        current = _current;
                        return;
                    }
                    if(_current < current) {
                        done(new Error('Received "current"=' + _current + ' that is lower than previously received "current"=' + current));
                        done = null;
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    done();
                }
            });
        });
        // TODO test total downloading length for outputType=text and various strings and characters, e.g. character '𝌆'
    });
});
<commit_msg>test: downloadingSpec: resolve TODO items<commit_after>var cfg = require('../dummyserver-config');
var httpinvoke = require('../httpinvoke-node');

describe('"downloading" option', function() {
    this.timeout(10000);
    cfg.eachBase(function(postfix, url, crossDomain) {
        it('is called at least twice' + postfix, function(done) {
            var count = 0;
            var abort = httpinvoke(url, {
                downloading: function() {
                    count += 1;
                    if(count === 2) {
                        done();
                        done = null;
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    if(count < 2) {
                        done(new Error('It was called ' + count + ' times'));
                    }
                    abort();
                }
            });
        });
        it('has total be 0, if there is no entity body' + postfix, function(done) {
            httpinvoke(url + 'noentity', 'POST', {
                downloading: function(_, total) {
                    if(done === null) {
                        return;
                    }
                    if(typeof total === 'undefined') {
                        return;
                    }
                    if(total !== 0) {
                        done(new Error('total is not 0'));
                        done = null;
                    }
                },
                finished: function(err, output) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    if(typeof output !== 'undefined') {
                        return done(new Error('Output is not undefined'));
                    }
                    done();
                }
            });
        });
        it('has the last total be always defined' + postfix, function(done) {
            var defined = false;
            var abort = httpinvoke(url, {
                downloading: function(_, total) {
                    defined = typeof total !== 'undefined';
                },
                finished: function(err) {
                    if(err) {
                        return done(err);
                    }
                    if(!defined) {
                        return done(new Error('Last total is not defined'));
                    }
                    done();
                }
            });
        });
        it('has total be always defined, after first time' + postfix, function(done) {
            var defined = false;
            var abort = httpinvoke(url, {
                downloading: function(_, total) {
                    if(typeof total !== 'undefined') {
                        defined = true;
                    } else if(defined) {
                        done(new Error('became undefined after was defined'));
                        done = null;
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    done();
                }
            });
        });
        it('has "current" and "total" be non-negative integers' + postfix, function(done) {
            var fail = function(msg) {
                done(new Error(msg));
                done = null;
            };
            httpinvoke(url, {
                downloading: function(current, total) {
                    if(typeof total === 'undefined') {
                        return;
                    }
                    if(done === null) {
                        return;
                    }
                    if(typeof current !== 'number') {
                        return fail('"current" was not a number');
                    }
                    if(current % 1 !== 0) {
                        return fail('"current" was not an integer');
                    }
                    if(current < 0) {
                        return fail('"current" was not an non-negative');
                    }
                    if(typeof total !== 'number') {
                        return fail('"total" was not a number');
                    }
                    if(total % 1 !== 0) {
                        return fail('"total" was not an integer, because the result of (total % 1) is ' + (total % 1));
                    }
                    if(total < 0) {
                        return fail('"total" was not an non-negative');
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    done();
                }
            });
        });
        it('has the last "current" be equal to total' + postfix, function(done) {
            var current, total;
            httpinvoke(url, {
                downloading: function(_current, _total) {
                    current = _current;
                    total = _total;
                },
                finished: function(err) {
                    if(err) {
                        return done(err);
                    }
                    if(current !== total) {
                        done(new Error('The last received "current"=' + current + ' is not equal to "total"=' + total));
                    } else {
                        done();
                    }
                }
            });
        });
        it('has the first "current" be equal to 0' + postfix, function(done) {
            var abort = httpinvoke(url, {
                downloading: function(current) {
                    if(done === null) {
                        return;
                    }
                    if(current !== 0) {
                        done(new Error('First "current" is not equal to 0: ' + current));
                    } else {
                        done();
                    }
                    done = null;
                    abort();
                }
            });
        });
        it('has "current" not greater than "total"' + postfix, function(done) {
            httpinvoke(url, {
                downloading: function(current, total) {
                    if(current > total) {
                        done(new Error('"current" was greater than "total"'));
                        done = null;
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    done();
                }
            });
        });
        it('has "total" always be the same' + postfix, function(done) {
            var total = null;
            httpinvoke(url, {
                downloading: function(current, _total) {
                    if(typeof _total === 'undefined') {
                        return;
                    }
                    if(done === null) {
                        return;
                    }
                    if(total === null) {
                        total = _total;
                        return;
                    }
                    if(total !== _total) {
                        done(new Error('Received "total"=' + _total + ' that is different from previously received "total"=' + total));
                        done = null;
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    done();
                }
            });
        });
        it('has the last "total" be equal to output length, when outputType="bytearray"' + postfix, function(done) {
            var total = null;
            httpinvoke(url, {
                outputType: 'bytearray',
                downloading: function(_, _total) {
                    total = _total;
                },
                finished: function(err, output) {
                    if(err) {
                        return done(err);
                    }
                    if(output.length !== total) {
                        done(new Error('The last "total"=' + total + ' was not equal to output length = ' + output.length));
                    } else {
                        done();
                    }
                }
            });
        });
        it('has "current" be non-decreasing' + postfix, function(done) {
            var current = null;
            httpinvoke(url, {
                downloading: function(_current) {
                    if(done === null) {
                        return;
                    }
                    if(current === null) {
                        current = _current;
                        return;
                    }
                    if(_current < current) {
                        done(new Error('Received "current"=' + _current + ' that is lower than previously received "current"=' + current));
                        done = null;
                    }
                },
                finished: function(err) {
                    if(done === null) {
                        return;
                    }
                    if(err) {
                        return done(err);
                    }
                    done();
                }
            });
        });
    });
});
<|endoftext|>