<commit_before>require([
            'dojo/aspect',
            'dojo/_base/declare',
            'JBrowse/Browser',
            'JBrowse/Store/SeqFeature/BAM',
            'JBrowse/Store/SeqFeature/_MismatchesMixin',
            'JBrowse/Model/XHRBlob',
            'JBrowse/Model/SimpleFeature'
        ], function( aspect, declare, Browser, BAMStore, XHRBlob, MismatchesMixin, SimpleFeature ) {

// function distinctBins( features ) {
//     var bins = {};
//     features.forEach( function(f) {
//         bins[ f.data._bin ] = ( bins[ f.data._bin ] || 0 ) + 1;
//     });
//     return bins;
// }

describe( 'BAM mismatches test', function() {
              var feature=new SimpleFeature({data: {
                start: 7903922,
                length: 90,
                cigar: "89M2741N1M",
                md: "89A0",
                seq: "TACTTGATAAATCAGCTCACTCTCTGGTGCTTTTTAGAGAAGTCCCTGATTCCTTCTTAAACTTGGAATGATAGATGAAATTCACACCCG"
              }});

              //Config workaround since we aren't directly instantiating anything with Browser/config
              var Config=declare(null, {
                  constructor: function() {
                      this.config={};
                  }
              });
              //Use Config workaround
              var MismatchParser=declare([Config,MismatchesMixin]);

              it('getMismatches test', function() {
                  var parser=new MismatchParser();
                  var obj=parser._getMismatches(feature);
                  expect(obj[1].base=="G" && obj[1].length==1&&obj[1].start==2830&&obj[1].type=="mismatch").toBeTruthy();
              });
}),

describe( 'BAM with volvox-sorted.bam', function() {
              var b;
              beforeEach( function() {
                  b = new BAMStore({
                                       browser: new Browser({ unitTestMode: true }),
                                       bam: new XHRBlob('../../sample_data/raw/volvox/volvox-sorted.bam'),
                                       bai: new XHRBlob('../../sample_data/raw/volvox/volvox-sorted.bam.bai'),
                                       refSeq: { name: 'ctgA', start: 1, end: 500001 }
                                   });
              });

              it( 'constructs', function() {
                      expect(b).toBeTruthy();
                  });

              it( 'loads some data', function() {
                      var loaded;
                      var features = [];
                      var done;
                      aspect.after( b, 'loadSuccess', function() {
                          loaded = true;
                      });
                      b.getFeatures({ start: 0, end: 50000 },
                                 function( feature ) {
                                     features.push( feature );
                                 },
                                 function() {
                                     done = true;
                                 }
                               );
                      waitsFor( function() { return done; }, 2000 );
                      runs( function() {
                                expect(features.length).toBeGreaterThan(1000);
                            });
                  });
});

describe( 'BAM with test_deletion_2_0.snps.bwa_align.sorted.grouped.bam', function() {
              var b;
              beforeEach( function() {
                  b = new BAMStore({
                      browser: new Browser({ unitTestMode: true }),
                      bam: new XHRBlob('../data/test_deletion_2_0.snps.bwa_align.sorted.grouped.bam'),
                      bai: new XHRBlob('../data/test_deletion_2_0.snps.bwa_align.sorted.grouped.bam.bai'),
                      refSeq: { name: 'Chromosome', start: 1, end: 20000 }
                  });
              });

              it( 'constructs', function() {
                      expect(b).toBeTruthy();
                  });

              it( 'loads some data', function() {
                      var loaded;
                      var features = [];
                      var done;
                      aspect.after( b, 'loadSuccess', function() {
                          loaded = true;
                      });
                      b.getFeatures({ start: 17000, end: 18000 },
                                 function( feature ) {
                                     features.push( feature );
                                 },
                                 function() {
                                     done = true;
                                 }
                               );
                      waitsFor( function() { return done; }, 2000 );
                      runs( function() {
                                expect(features.length).toEqual(124);
                                //console.log( distinctBins(features) );
                            });
                  });
});

describe( 'empty BAM', function() {
              var b;
              beforeEach( function() {
                  b = new BAMStore({
                      browser: new Browser({ unitTestMode: true }),
                      bam: new XHRBlob('../data/empty.bam'),
                      bai: new XHRBlob('../data/empty.bam.bai'),
                      refSeq: { name: 'Chromosome', start: 1, end: 20000 }
                  });
              });

              it( 'constructs', function() {
                      expect(b).toBeTruthy();
                  });

              it( "returns no data, but doesn't crash", function() {
                      var loaded;
                      var features = [];
                      var done;
                      aspect.after( b, 'loadSuccess', function() {
                          loaded = true;
                      });
                      b.getFeatures( { start: 0, end: 50000 },
                                 function( feature ) {
                                     features.push( feature );
                                 },
                                 function() {
                                     done = true;
                                 }
                               );
                      waitsFor( function() { return done; }, 2000 );
                      runs( function() {
                                expect(features.length).toEqual( 0 );
                            });
                  });
});

describe( 'BAM with tests/data/final.merged.sorted.rgid.mkdup.realign.recal.bam', function() {
              var b;
              beforeEach( function() {
                  b = new BAMStore({
                      browser: new Browser({ unitTestMode: true }),
                      bam: new XHRBlob('../data/final.merged.sorted.rgid.mkdup.realign.recal.bam'),
                      bai: new XHRBlob('../data/final.merged.sorted.rgid.mkdup.realign.recal.bam.bai'),
                      refSeq: { end: 27682,
                                length: 27682,
                                name: "chr21_gl000210_random",
                                seqChunkSize: 80000,
                                start: 0
                              }
                  });
              });

              it( 'constructs', function() {
                      expect(b).toBeTruthy();
                  });

              it( 'loads some data', function() {
                      var loaded;
                      var features = [];
                      var done;
                      aspect.after( b, 'loadSuccess', function() {
                          loaded = true;
                      });
                      b.getFeatures({ start: 16589, end: 18964 },
                                 function( feature ) {
                                     features.push( feature );
                                 },
                                 function() {
                                     done = true;
                                 }
                               );
                      waitsFor( function() { return done; }, 2000 );
                      runs( function() {
                                expect(features.length).toEqual(281);
                                //console.log( distinctBins(features) );
                            });
                  });
});

// only run the cabone_test_2 if it's in the URL someplace
if( document.location.href.indexOf('extended_tests=1') > -1 ) {
    describe( 'BAM with carbone_test_2', function() {
                  var b;
                  beforeEach( function() {
                      b = new BAMStore({
                          browser: new Browser({ unitTestMode: true }),
                          bam: new XHRBlob('../../../data/carbone_test_2/RIB40_278_k51_cd_hit_est_sorted.bam'),
                          bai: new XHRBlob('../../../data/carbone_test_2/RIB40_278_k51_cd_hit_est_sorted.bam.bai'),
                          refSeq: { name: 'gi|338162049|dbj|BA000051.1|', start: 1, end: 5123684 }
                      });
                  });

                  it( 'loads some data', function() {
                          var loaded;
                          var features = [];
                          var done;
                          aspect.after( b, 'loadSuccess', function() {
                              loaded = true;
                          });

    // need 2:3905491-4019507 NODE_423_length_210786_cov_16.121635 3919331 3979772

                          b.getFeatures({ start: 3799999, end: 4049999 },
                                     function( feature ) {
                                         features.push( feature );
                                     },
                                     function() {
                                         done = true;
                                     }
                                   );
                          waitsFor( function() { return done; }, 2000 );
                          runs( function() {
                                    expect(features.length).toEqual(13);
                                    //console.log( distinctBins(features) );
                                });
                      });
    });

}

});

<commit_msg>Fix BAM tests. See #523<commit_after>require([
            'dojo/aspect',
            'dojo/_base/declare',
            'JBrowse/Browser',
            'JBrowse/Store/SeqFeature/BAM',
            'JBrowse/Model/XHRBlob',
            'JBrowse/Store/SeqFeature/_MismatchesMixin',
            'JBrowse/Model/SimpleFeature'
        ], function( aspect, declare, Browser, BAMStore, XHRBlob, MismatchesMixin, SimpleFeature ) {

// function distinctBins( features ) {
//     var bins = {};
//     features.forEach( function(f) {
//         bins[ f.data._bin ] = ( bins[ f.data._bin ] || 0 ) + 1;
//     });
//     return bins;
// }

describe( 'BAM mismatches test', function() {
              var feature=new SimpleFeature({data: {
                start: 7903922,
                length: 90,
                cigar: "89M2741N1M",
                md: "89A0",
                seq: "TACTTGATAAATCAGCTCACTCTCTGGTGCTTTTTAGAGAAGTCCCTGATTCCTTCTTAAACTTGGAATGATAGATGAAATTCACACCCG"
              }});

              //Config workaround since we aren't directly instantiating anything with Browser/config
              var Config=declare(null, {
                  constructor: function() {
                      this.config={};
                  }
              });
              //Use Config workaround
              var MismatchParser=declare([Config,MismatchesMixin]);

              it('getMismatches test', function() {
                  var parser=new MismatchParser();
                  var obj=parser._getMismatches(feature);
                  expect(obj[1].base=="G" && obj[1].length==1&&obj[1].start==2830&&obj[1].type=="mismatch").toBeTruthy();
              });
});

describe( 'BAM with volvox-sorted.bam', function() {
              var b;
              beforeEach( function() {
                  b = new BAMStore({
                                       browser: new Browser({ unitTestMode: true }),
                                       bam: new XHRBlob('../../sample_data/raw/volvox/volvox-sorted.bam'),
                                       bai: new XHRBlob('../../sample_data/raw/volvox/volvox-sorted.bam.bai'),
                                       refSeq: { name: 'ctgA', start: 1, end: 500001 }
                                   });
              });

              it( 'constructs', function() {
                      expect(b).toBeTruthy();
                  });

              it( 'loads some data', function() {
                      var loaded;
                      var features = [];
                      var done;
                      aspect.after( b, 'loadSuccess', function() {
                          loaded = true;
                      });
                      b.getFeatures({ start: 0, end: 50000 },
                                 function( feature ) {
                                     features.push( feature );
                                 },
                                 function() {
                                     done = true;
                                 }
                               );
                      waitsFor( function() { return done; }, 2000 );
                      runs( function() {
                                expect(features.length).toBeGreaterThan(1000);
                            });
                  });
});

describe( 'BAM with test_deletion_2_0.snps.bwa_align.sorted.grouped.bam', function() {
              var b;
              beforeEach( function() {
                  b = new BAMStore({
                      browser: new Browser({ unitTestMode: true }),
                      bam: new XHRBlob('../data/test_deletion_2_0.snps.bwa_align.sorted.grouped.bam'),
                      bai: new XHRBlob('../data/test_deletion_2_0.snps.bwa_align.sorted.grouped.bam.bai'),
                      refSeq: { name: 'Chromosome', start: 1, end: 20000 }
                  });
              });

              it( 'constructs', function() {
                      expect(b).toBeTruthy();
                  });

              it( 'loads some data', function() {
                      var loaded;
                      var features = [];
                      var done;
                      aspect.after( b, 'loadSuccess', function() {
                          loaded = true;
                      });
                      b.getFeatures({ start: 17000, end: 18000 },
                                 function( feature ) {
                                     features.push( feature );
                                 },
                                 function() {
                                     done = true;
                                 }
                               );
                      waitsFor( function() { return done; }, 2000 );
                      runs( function() {
                                expect(features.length).toEqual(124);
                                //console.log( distinctBins(features) );
                            });
                  });
});

describe( 'empty BAM', function() {
              var b;
              beforeEach( function() {
                  b = new BAMStore({
                      browser: new Browser({ unitTestMode: true }),
                      bam: new XHRBlob('../data/empty.bam'),
                      bai: new XHRBlob('../data/empty.bam.bai'),
                      refSeq: { name: 'Chromosome', start: 1, end: 20000 }
                  });
              });

              it( 'constructs', function() {
                      expect(b).toBeTruthy();
                  });

              it( "returns no data, but doesn't crash", function() {
                      var loaded;
                      var features = [];
                      var done;
                      aspect.after( b, 'loadSuccess', function() {
                          loaded = true;
                      });
                      b.getFeatures( { start: 0, end: 50000 },
                                 function( feature ) {
                                     features.push( feature );
                                 },
                                 function() {
                                     done = true;
                                 }
                               );
                      waitsFor( function() { return done; }, 2000 );
                      runs( function() {
                                expect(features.length).toEqual( 0 );
                            });
                  });
});

describe( 'BAM with tests/data/final.merged.sorted.rgid.mkdup.realign.recal.bam', function() {
              var b;
              beforeEach( function() {
                  b = new BAMStore({
                      browser: new Browser({ unitTestMode: true }),
                      bam: new XHRBlob('../data/final.merged.sorted.rgid.mkdup.realign.recal.bam'),
                      bai: new XHRBlob('../data/final.merged.sorted.rgid.mkdup.realign.recal.bam.bai'),
                      refSeq: { end: 27682,
                                length: 27682,
                                name: "chr21_gl000210_random",
                                seqChunkSize: 80000,
                                start: 0
                              }
                  });
              });

              it( 'constructs', function() {
                      expect(b).toBeTruthy();
                  });

              it( 'loads some data', function() {
                      var loaded;
                      var features = [];
                      var done;
                      aspect.after( b, 'loadSuccess', function() {
                          loaded = true;
                      });
                      b.getFeatures({ start: 16589, end: 18964 },
                                 function( feature ) {
                                     features.push( feature );
                                 },
                                 function() {
                                     done = true;
                                 }
                               );
                      waitsFor( function() { return done; }, 2000 );
                      runs( function() {
                                expect(features.length).toEqual(281);
                                //console.log( distinctBins(features) );
                            });
                  });
});

// only run the cabone_test_2 if it's in the URL someplace
if( document.location.href.indexOf('extended_tests=1') > -1 ) {
    describe( 'BAM with carbone_test_2', function() {
                  var b;
                  beforeEach( function() {
                      b = new BAMStore({
                          browser: new Browser({ unitTestMode: true }),
                          bam: new XHRBlob('../../../data/carbone_test_2/RIB40_278_k51_cd_hit_est_sorted.bam'),
                          bai: new XHRBlob('../../../data/carbone_test_2/RIB40_278_k51_cd_hit_est_sorted.bam.bai'),
                          refSeq: { name: 'gi|338162049|dbj|BA000051.1|', start: 1, end: 5123684 }
                      });
                  });

                  it( 'loads some data', function() {
                          var loaded;
                          var features = [];
                          var done;
                          aspect.after( b, 'loadSuccess', function() {
                              loaded = true;
                          });

    // need 2:3905491-4019507 NODE_423_length_210786_cov_16.121635 3919331 3979772

                          b.getFeatures({ start: 3799999, end: 4049999 },
                                     function( feature ) {
                                         features.push( feature );
                                     },
                                     function() {
                                         done = true;
                                     }
                                   );
                          waitsFor( function() { return done; }, 2000 );
                          runs( function() {
                                    expect(features.length).toEqual(13);
                                    //console.log( distinctBins(features) );
                                });
                      });
    });

}

});

<|endoftext|>


<commit_before>
var Core = require('./venacava.js').Core
, redis = require('redis')
, assert = require('assert')
, EventEmitter = require('events').EventEmitter
;

var redisClient = function () {
    return redis.createClient();
};

var randomId = function () {
    return 'test' + Math.floor(Math.random() * 1000000);
};

describe('core', function () {

    var redis
    , newCore = function (channel, attrs) {
	if (typeof channel === 'object') {
	    attrs = channel;
	    channel = randomId();
	}
	else if (!channel) {
	    channel = randomId();
	}
	return new Core(channel, redis, attrs);
    }
    ;

    before(function(done) {
	redis = redisClient();
	return done();
    });

    it('should be constructable', function () {
	newCore({x: 1})
    });

    it('should have a channel attribute', function () {
	assert(newCore().hasOwnProperty('channel'), 'core did not have a channel property');
    });

    describe('#fetch', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.hasOwnProperty('fetch'), 'core did not have a fetch property');
	    assert(typeof core.fetch === 'function', 'core.fetch was not a function');
	});

	it('should restore previously set values', function (done) {
	    var core = newCore()
	    ;
	    core.set('x', Math.random(), function (err) {
		assert.ifError(err);

		var dup = newCore(core.channel, {x: Math.random()});
		dup.fetch(function (err) {
		    assert.ifError(err);
		    assert.equal(core.get('x'), dup.get('x'), 'failed to fetch');
		    done();
		});
	    });
	});
    });

    describe('#get', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.hasOwnProperty('get'));
	    assert.equal(typeof core.get, 'function', '"get" was not a function');
	});

	it('should synchronously return a single cached value for a single argument', function () {
	    var x = Math.random()
	    , core = newCore({x: 1})
	    ;
	    assert.equal(core.get('x'), x, 'did not get the initial cached value');
	});

    });

    describe('#toJSON', function () {
	it('should synchronously return a cloned copy of the cached attrs', function () {
	    var attrs = {
		x: Math.random()
	    }
	    , core = newCore(attrs)
	    , cloned = core.toJSON()
	    ;
	    assert.deepEqual(cloned, attrs, 'did not get the initial cached attrs');
	    var y = cloned.x = Math.random();
	    assert.notDeepEqual(cloned, core.toJSON(), 'failed to successfully modify cloned attributes');
	});
    });

    describe('#set', function () {
	it('should synchronously modify a single cached value for a single argument', function () {
	    var attrs = {
		x: Math.random()
	    }
	    , core = newCore(attrs)
	    , y = Math.random()
	    ;
	    core.set('x', y);
	    assert.equal(core.get('x'), y);
	});

	it('should synchronously modify a set of cached values for an object argument', function () {
	    var attrs = {
		x: Math.random()
		, y: Math.random()
		, z: Math.random()
	    }
	    , core = newCore(attrs)
	    , newAttrs = {
		x: Math.random()
		, y: Math.random()
	    }
	    ;
	    core.set(newAttrs)
	    assert.equal(newAttrs.x, core.get('x'), 'failed to set x through object argument');
	    assert.equal(newAttrs.y, core.get('y'), 'failed to set y through object argument');
	    assert.equal(attrs.z, core.get('z'), 'failed to preserve z after object argument');
	});

	describe('#async', function () {
	    it('should be provided', function (done) {
		newCore({x: 1}).set('x', 2, done);
	    });

	    it('should guarantee that the value is stored in the fetch source', function (done) {
		var core = newCore()
		, x = Math.random()
		;
		core.set('x', x, function (err) {
		    assert.ifError(err);
		    var newCore = newCore(core.channel);
		    newCore.fetch(function (err) {
			assert.ifError(err);
			assert.equal(newCore.get('x'), x);
			return done();
		    });
		});
	    });
	});
    });

    describe('#has', function () {
	it('should exist', function () {
	    var core = newCore();
	    assert(core.hasOwnProperty('has'), '"has" does not exist');
	    assert.equal(typeof core.has, 'function', '"has" is not a function');
	});

	it('should indicate the existence of an attribute', function () {
	    var core = newCore({x: 1});
	    assert(core.has('x'), 'core did not properly indicate existing attribute.');
	    assert(!core.has('y'), 'core did not properly indicate existing attribute.');
	});
    });

    describe('#unset', function () {
	it('should exist', function () {
	    var core = newCore();
	    assert(core.hasOwnProperty('unset'), '"unset" does not exist');
	    assert.equal(typeof core.unset, 'function', '"unset" is not a function');
	});

	it('should change the truthiness of associated has', function () {
	    var core = newCore({x: 1});
	    core.unset('x')
	    assert(!core.has('x'), 'unset did not change "has" value');
	});

	it('should change whether the attribute appears on toJSON ', function () {
	    var core = newCore({x: 1});
	    core.unset('x')
	    assert(!core.toJSON().hasOwnProperty('x'), 'unset did not change "has" value');
	});
    });

    describe('redis subscription', function () {

	it('should send set updates', function (done) {
	    var subRedis = redisClient()
	    , core = newCore()
	    , attrs = {x: 1}
	    ;
	    subRedis.on('message', function (channel, msg) {
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert.deepEqual(msg, attrs);
		done();
	    });

	    subRedis.subscribe(core.channel);

	    core.set(attrs);
	});

	it('should send unset updates', function (done) {
	    var subRedis = redisClient()
	    , core = newCore()
	    , attrs = {x: 1}
	    ;
	    subRedis.on('message', function (channel, msg) {
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert(msg.hasOwnProperty('x'), 'unset did not send a message for the unset property.');
		assert.equal(msg.x, void 0, 'unset did not send a message with undefined for the unset property.');
		done();
	    });

	    subRedis.subscribe(core.channel);

	    core.unset('x');
	});

    });
});
      <commit_msg>Add tests for clear method.<commit_after>
var Core = require('./venacava.js').Core
, redis = require('redis')
, assert = require('assert')
, EventEmitter = require('events').EventEmitter
;

var redisClient = function () {
    return redis.createClient();
};

var randomId = function () {
    return 'test' + Math.floor(Math.random() * 1000000);
};

describe('core', function () {

    var redis
    , newCore = function (channel, attrs) {
	if (typeof channel === 'object') {
	    attrs = channel;
	    channel = randomId();
	}
	else if (!channel) {
	    channel = randomId();
	}
	return new Core(channel, redis, attrs);
    }
    ;

    before(function(done) {
	redis = redisClient();
	return done();
    });

    it('should be constructable', function () {
	newCore({x: 1})
    });

    it('should have a channel attribute', function () {
	assert(newCore().hasOwnProperty('channel'), 'core did not have a channel property');
    });

    describe('#fetch', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.hasOwnProperty('fetch'), 'core did not have a fetch property');
	    assert(typeof core.fetch === 'function', 'core.fetch was not a function');
	});

	it('should restore previously set values', function (done) {
	    var core = newCore()
	    ;
	    core.set('x', Math.random(), function (err) {
		assert.ifError(err);

		var dup = newCore(core.channel, {x: Math.random()});
		dup.fetch(function (err) {
		    assert.ifError(err);
		    assert.equal(core.get('x'), dup.get('x'), 'failed to fetch');
		    done();
		});
	    });
	});
    });

    describe('#get', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.hasOwnProperty('get'));
	    assert.equal(typeof core.get, 'function', '"get" was not a function');
	});

	it('should synchronously return a single cached value for a single argument', function () {
	    var x = Math.random()
	    , core = newCore({x: 1})
	    ;
	    assert.equal(core.get('x'), x, 'did not get the initial cached value');
	});

    });

    describe('#toJSON', function () {
	it('should synchronously return a cloned copy of the cached attrs', function () {
	    var attrs = {
		x: Math.random()
	    }
	    , core = newCore(attrs)
	    , cloned = core.toJSON()
	    ;
	    assert.deepEqual(cloned, attrs, 'did not get the initial cached attrs');
	    var y = cloned.x = Math.random();
	    assert.notDeepEqual(cloned, core.toJSON(), 'failed to successfully modify cloned attributes');
	});
    });

    describe('#set', function () {
	it('should synchronously modify a single cached value for a single argument', function () {
	    var attrs = {
		x: Math.random()
	    }
	    , core = newCore(attrs)
	    , y = Math.random()
	    ;
	    core.set('x', y);
	    assert.equal(core.get('x'), y);
	});

	it('should synchronously modify a set of cached values for an object argument', function () {
	    var attrs = {
		x: Math.random()
		, y: Math.random()
		, z: Math.random()
	    }
	    , core = newCore(attrs)
	    , newAttrs = {
		x: Math.random()
		, y: Math.random()
	    }
	    ;
	    core.set(newAttrs)
	    assert.equal(newAttrs.x, core.get('x'), 'failed to set x through object argument');
	    assert.equal(newAttrs.y, core.get('y'), 'failed to set y through object argument');
	    assert.equal(attrs.z, core.get('z'), 'failed to preserve z after object argument');
	});

	describe('#async', function () {
	    it('should be provided', function (done) {
		newCore({x: 1}).set('x', 2, done);
	    });

	    it('should guarantee that the value is stored in the fetch source', function (done) {
		var core = newCore()
		, x = Math.random()
		;
		core.set('x', x, function (err) {
		    assert.ifError(err);
		    var newCore = newCore(core.channel);
		    newCore.fetch(function (err) {
			assert.ifError(err);
			assert.equal(newCore.get('x'), x);
			return done();
		    });
		});
	    });
	});
    });

    describe('#has', function () {
	it('should exist', function () {
	    var core = newCore();
	    assert(core.hasOwnProperty('has'), '"has" does not exist');
	    assert.equal(typeof core.has, 'function', '"has" is not a function');
	});

	it('should indicate the existence of an attribute', function () {
	    var core = newCore({x: 1});
	    assert(core.has('x'), 'core did not properly indicate existing attribute.');
	    assert(!core.has('y'), 'core did not properly indicate existing attribute.');
	});
    });

    describe('#unset', function () {
	it('should exist', function () {
	    var core = newCore();
	    assert(core.hasOwnProperty('unset'), '"unset" does not exist');
	    assert.equal(typeof core.unset, 'function', '"unset" is not a function');
	});

	it('should change the truthiness of associated has', function () {
	    var core = newCore({x: 1});
	    core.unset('x')
	    assert(!core.has('x'), 'unset did not change "has" value');
	});

	it('should change whether the attribute appears on toJSON ', function () {
	    var core = newCore({x: 1});
	    core.unset('x')
	    assert(!core.toJSON().hasOwnProperty('x'), 'unset did not change "has" value');
	});

	describe('#async', function () {
	    it('should be provided', function (done) {
		newCore({x: 1}).unset('x', 2, done);
	    });

	    it('should guarantee that the unset in the fetch source', function (done) {
		var core = newCore()
		, x = Math.random()
		;
		core.set('x', 1, function (err) {
		    assert.ifError('x');
		    core.unset('x', function (err) {
			assert.ifError(err);
			var newCore = newCore(core.channel);
			newCore.fetch(function (err) {
			    assert.ifError(err);
			    assert(!newCore.has('x'), 'property was not removed.');
			    return done();
			});
		    });
		});
	    });
	});
    });

    describe('#clear', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.hasOwnProperty('clear'), 'core did not have a "clear" property');
	    assert(typeof core.clear, 'function', '"clear" property was not a function')
	});

	it('should provide async', function (done) {
	    newCore({x: 1}).clear(done);
	});

	it('should clear all properties', function () {
	    var core = newCore({x: 1});
	    core.clear(function (err) {
		assert.ifError(err);
		var newCore = newCore(core.channel);
		newCore.fetch(function (err) {
		    assert.ifError(err);
		    assert.deepEqual(newCore.toJSON(), {}, 'core was not cleared');
		    return done();
		});

	    });
	});

    });

    describe('redis subscription', function () {

	it('should send set updates', function (done) {
	    var subRedis = redisClient()
	    , core = newCore()
	    , attrs = {x: 1}
	    ;
	    subRedis.on('message', function (channel, msg) {
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert.deepEqual(msg, attrs);
		done();
	    });

	    subRedis.subscribe(core.channel);

	    core.set(attrs);
	});

	it('should send unset updates', function (done) {
	    var subRedis = redisClient()
	    , core = newCore()
	    , attrs = {x: 1}
	    ;
	    subRedis.on('message', function (channel, msg) {
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert(msg.hasOwnProperty('x'), 'unset did not send a message for the unset property.');
		assert.equal(msg.x, void 0, 'unset did not send a message with undefined for the unset property.');
		done();
	    });

	    subRedis.subscribe(core.channel);

	    core.unset('x');
	});

    });
});
      <|endoftext|>


<commit_before>var seedrandom = require('seedrandom');
var geom = require('pex-geom');
var Vec2 = geom.Vec2;
var Vec3 = geom.Vec3;

var Random = {};

Random.seed = function(s) {
  Math.seedrandom(s);
};

Random.float = function(min, max) {
  if (arguments.length == 0) {
    min = 0;
    max = 1;
  }
  else if (arguments.length == 1) {
    max = min;
    min = 0;
  }
  return min + (max - min) * Math.random();
}

Random.int = function(min, max) {
  return Math.floor(Random.randomFloat(min, max));
};

Random.vec2 = function(r) {
  if (typeof r == 'undefined') r = 1;
  var x = 2 * Math.random() - 1;
  var y = 2 * Math.random() - 1;
  return Vec2.create(r * x, r * y);
};

Random.vec3 = function(r) {
  if (typeof r == 'undefined') r = 1;
  var x = 2 * Math.random() - 1;
  var y = 2 * Math.random() - 1;
  var z = 2 * Math.random() - 1;
  return Vec3.create(r * x, r * y, r * z);
};

Random.vec3InBoundingBox = function(bbox) {
  var x = bbox.min.x + Math.random() * (bbox.max.x - bbox.min.x);
  var y = bbox.min.y + Math.random() * (bbox.max.y - bbox.min.y);
  var z = bbox.min.z + Math.random() * (bbox.max.z - bbox.min.z);
  return Vec3.create(x, y, z);
};

Random.vec2InRect = function(rect) {
  return Vec2.create(rect.x + Math.random() * rect.width, rect.y + Math.random() * rect.height);
};

Random.chance = function(probability) {
  return Math.random() <= probability;
};

Random.element = function(list) {
  return list[Math.floor(Math.random() * list.length)];
};

module.exports = Random;<commit_msg>Random int was always returning zero if no max given<commit_after>var seedrandom = require('seedrandom');
var geom = require('pex-geom');
var Vec2 = geom.Vec2;
var Vec3 = geom.Vec3;

var Random = {};

Random.seed = function(s) {
  Math.seedrandom(s);
};

Random.float = function(min, max) {
  if (arguments.length == 0) {
    min = 0;
    max = 1;
  }
  else if (arguments.length == 1) {
    max = min;
    min = 0;
  }
  return min + (max - min) * Math.random();
}

//Using max safe integer as max value unless otherwise specified
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
Random.int = function(min, max) {
  if (arguments.length == 0) {
    min = 0;
    max = Math.pow(2, 53) - 1;
  }
  else if (arguments.length == 1) {
    max = min;
    min = 0;
  }
  return Math.floor(Random.float(min, max));
};

Random.vec2 = function(r) {
  if (typeof r == 'undefined') r = 1;
  var x = 2 * Math.random() - 1;
  var y = 2 * Math.random() - 1;
  return Vec2.create(r * x, r * y);
};

Random.vec3 = function(r) {
  if (typeof r == 'undefined') r = 1;
  var x = 2 * Math.random() - 1;
  var y = 2 * Math.random() - 1;
  var z = 2 * Math.random() - 1;
  return Vec3.create(r * x, r * y, r * z);
};

Random.vec3InBoundingBox = function(bbox) {
  var x = bbox.min.x + Math.random() * (bbox.max.x - bbox.min.x);
  var y = bbox.min.y + Math.random() * (bbox.max.y - bbox.min.y);
  var z = bbox.min.z + Math.random() * (bbox.max.z - bbox.min.z);
  return Vec3.create(x, y, z);
};

Random.vec2InRect = function(rect) {
  return Vec2.create(rect.x + Math.random() * rect.width, rect.y + Math.random() * rect.height);
};

Random.chance = function(probability) {
  return Math.random() <= probability;
};

Random.element = function(list) {
  return list[Math.floor(Math.random() * list.length)];
};

module.exports = Random;<|endoftext|>


<commit_before>// need to add 'is_other' to repos so we can make this work

var repo_data = eval({{ repo_data|safe }});
var get_slug_from_repo_data = function (repo_root_url, repo_branch_url) {
    var slug = null;
    for (i=0;i<repo_data.length;i++) {
        if (repo_data[i].url == repo_root_url) {
            var regexp_title = new RegExp(repo_data[i].repo_regex);
            var match_obj = regexp_title.exec(repo_branch_url);
            if (match_obj !== null) {
                slug = match_obj[1]
            }
            break;
        }
    }
    return slug;
}

String.prototype.starts_with = function(str){
    return (this.indexOf(str) === 0);
}

String.prototype.ends_with = function(str){
    return (this.lastIndexOf(str) === this.length-str.length);
}

$("#id_repo_url").focus();

pypi_url_g = "http://pypi.python.org/pypi/";

$("#id_pypi_url").val($("#id_pypi_url").val().replace(pypi_url_g,""));

$("#id_pypi_url").change(function(e){
    $("#id_pypi_url").val($("#id_pypi_url").val().replace(pypi_url_g,""));
});

$("#id_repo_url").keyup(function(e) {
    var url = $("#id_repo_url").val();
    return url
});

$("#id_repo_url").change(function(e) {

    $("#target").text($("#id_repo_url").val());

    var url = $("#id_repo_url").val();

    // this fixes the problem with trailing slashes
    while (1==1){
            if (url.ends_with('/')){
                url = url.slice(0, url.length-1);
                $("#id_repo_url").val(url);
                }
            else {
                break;
            };
        };
    // for github
    if (url.starts_with('http://github.com')){
        url = url.replace('http://github.com','https://github.com');
        $("#id_repo_url").val(url);
    };
    if (url.starts_with('git@github.com:')){
        url = url.replace("git@github.com:","https://github.com/");
    };
    if (url.starts_with('git://github.com/')){
        url = url.replace("git://github.com/","https://github.com/");
        $("#id_repo_url").val(url);
    };
    if (url.ends_with('.git')){
        url = url.slice(0, url.length-4);
        $("#id_repo_url").val(url);
    };
    // for bitbucket
    if (url.starts_with('http://bitbucket.org')){
        url = url.replace('http://bitbucket.org','https://bitbucket.org');
        $("#id_repo_url").val(url);
    };
    // for launchpad
    if (url.starts_with('lp:')){
        url = url.replace('lp:', 'https://code.launchpad.net/');
        $("#id_repo_url").val(url);
    };

    var url_array = url.split('/');
    $.each(repo_data, function(index, item) {
        if (url.starts_with(item.url)){
            if (url !== item.url){
                var slug = null;
                if ($("#id_title").val().length === 0) {
                    // determine title/slug automagically
                    slug = get_slug_from_repo_data(item.url, url);
                    $("#id_title").val(slug);
                };
                if (slug === null) {
                    // fallback slug detector
                    slug = DPSlugify(url_array[url_array.length-1]);
                }
                $("#id_slug").val(slug);
                $("#id_pypi_url").val(slug);
                $("#package-form-message").text("Your package is hosted at " + item.title)
            };
        };
    });
});

$("#package-form").submit(function(e) {
    // hack to get around some database vs front end weirdness
    var pypi_url = $("#id_pypi_url").val();
    if (pypi_url.length > 0){
      $("#id_pypi_url").attr("name", "nuke");
      $("#temp").val(pypi_url_g + pypi_url);
      $("#temp").attr("name", "pypi_url");
    };

    return true
});
<commit_msg>updated package add form javascript<commit_after>// need to add 'is_other' to repos so we can make this work

var repo_data = eval({{ repo_data|safe }});
var get_slug_from_repo_data = function (repo_root_url, repo_branch_url) {
    var slug = null;
    for (i=0;i<repo_data.length;i++) {
        if (repo_data[i].url == repo_root_url) {
            var regexp_title = new RegExp(repo_data[i].repo_regex);
            var match_obj = regexp_title.exec(repo_branch_url);
            if (match_obj !== null) {
                slug = match_obj[1]
            }
            break;
        }
    }
    return slug;
}

String.prototype.starts_with = function(str){
    return (this.indexOf(str) === 0);
}

String.prototype.ends_with = function(str){
    return (this.lastIndexOf(str) === this.length-str.length);
}

$("#id_repo_url").focus();

$("#id_repo_url").keyup(function(e) {
    var url = $("#id_repo_url").val();
    return url
});

$("#id_repo_url").change(function(e) {

    $("#target").text($("#id_repo_url").val());

    var url = $("#id_repo_url").val();

    // this fixes the problem with trailing slashes
    while (1==1){
            if (url.ends_with('/')){
                url = url.slice(0, url.length-1);
                $("#id_repo_url").val(url);
                }
            else {
                break;
            };
        };
    // for github
    if (url.starts_with('http://github.com')){
        url = url.replace('http://github.com','https://github.com');
        $("#id_repo_url").val(url);
    };
    if (url.starts_with('git@github.com:')){
        url = url.replace("git@github.com:","https://github.com/");
    };
    if (url.starts_with('git://github.com/')){
        url = url.replace("git://github.com/","https://github.com/");
        $("#id_repo_url").val(url);
    };
    if (url.ends_with('.git')){
        url = url.slice(0, url.length-4);
        $("#id_repo_url").val(url);
    };
    // for bitbucket
    if (url.starts_with('http://bitbucket.org')){
        url = url.replace('http://bitbucket.org','https://bitbucket.org');
        $("#id_repo_url").val(url);
    };
    // for launchpad
    if (url.starts_with('lp:')){
        url = url.replace('lp:', 'https://code.launchpad.net/');
        $("#id_repo_url").val(url);
    };

    var url_array = url.split('/');
    $.each(repo_data, function(index, item) {
        if (url.starts_with(item.url)){
            if (url !== item.url){
                var slug = null;
                if ($("#id_title").val().length === 0) {
                    // determine title/slug automagically
                    slug = get_slug_from_repo_data(item.url, url);
                    $("#id_title").val(slug);
                };
                if (slug === null) {
                    // fallback slug detector
                    slug = DPSlugify(url_array[url_array.length-1]);
                }
                $("#id_slug").val(slug);
                $("#id_pypi_slug").val(slug);
                $("#package-form-message").text("Your package is hosted at " + item.title)
            };
        };
    });
});

$("#package-form").submit(function(e) {
    // hack to get around some database vs front end weirdness
    var pypi_slug = $("#id_pypi_slug").val();
    if (pypi_slug.length > 0){
      $("#id_pypi_slug").attr("name", "nuke");
      $("#temp").val(pypi_slug_g + pypi_slug);
      earchCompleteStop()

    };

    return true
});
<|endoftext|>


<commit_before>'use strict';

const storageManager = require('./../StorageManager'),
      BlobHttpProperties = require('./../model/BlobHttpProperties');

class CreateBlockBlob {
    constructor() {
    }

    process(req, res, container, blob) {
        const httpProps = this._buildHttpProps(req.headers);
        const metaProps = this._buildMetaProps(req.headers);
        storageManager.createBlockBlob(container, blob, req.body, httpProps, metaProps)
            .then((result) => {
                this._addResponseHeaders(res, result)
                res.status(201).send();
            })
            .catch((e) => {
                if (e.code === 'ENOENT') {
                    console.error(`Container ${containerName} does not exist.`);
                    res.status(404).send();
                } else if (e.code === 'EACCES') {
                    console.error(`Azurite failed to create blob in local file system due to missing permissions.`);
                    res.status(404).send();
                } else if (e.name === 'md5') {
                    res.status(400).send(e.message);
                } else {
                    res.status(500).send();
                    throw e;
                }
            })
    }

    _buildHttpProps(httpHeader) {
        return new BlobHttpProperties(
            null, // ETag will be overwritten by most recent value in DB if this is an update of an existing blob
            null,
            // x-ms-* attributes have precedence over according HTTP-Headers
            httpHeader['x-ms-blob-content-type'] || httpHeader['Content-Type'] || 'application/octet-stream',
            httpHeader['x-ms-blob-content-encoding'] || httpHeader['Content-Encoding'] || 'utf8',
            httpHeader['x-ms-blob-content-language'] || httpHeader['Content-Language'],
            httpHeader['x-ms-blob-content-md5'] || httpHeader['Content-MD5'],
            httpHeader['x-ms-blob-cache-control'] || httpHeader['Cache-Control']);
    }

    _buildMetaProps(httpHeader) {
        let metaProps = {};
        Object.keys(httpHeader).forEach((key) => {
            const value = req.headers[key];
            if (key.indexOf('x-ms-meta-') !== -1) {
                metaProps[key] = value;
            }
        });
    }

    _addResponseHeaders(res, props) {
        res.set({
            'ETag': props.ETag,
            'Last-Modified': props.lastModified,
            'x-ms-version': '2011-08-18',
            'x-ms-request-server-encrypted': false,
            'Content-MD5': props.md5
        });
    }
}<commit_msg>fixed bugs<commit_after>'use strict';

const storageManager = require('./../StorageManager'),
      BlobHttpProperties = require('./../model/BlobHttpProperties');

class CreateBlockBlob {
    constructor() {
    }

    process(req, res, container, blob) {
        const httpProps = this._buildHttpProps(req.headers);
        const metaProps = this._buildMetaProps(req.headers);
        storageManager.createBlockBlob(container, blob, req.body, httpProps, metaProps)
            .then((result) => {
                this._addResponseHeaders(res, result)
                res.status(201).send();
            })
            .catch((e) => {
                if (e.code === 'ENOENT') {
                    console.error(`Container ${containerName} does not exist.`);
                    res.status(404).send();
                } else if (e.code === 'EACCES') {
                    console.error(`Azurite failed to create blob in local file system due to missing permissions.`);
                    res.status(404).send();
                } else if (e.name === 'md5') {
                    console.error(e.message);
                    res.status(400).send(e.message);
                } else {
                    res.status(500).send();
                    throw e;
                }
            })
    }

    _buildHttpProps(httpHeader) {
        return new BlobHttpProperties(
            null, // ETag will be overwritten by most recent value in DB if this is an update of an existing blob
            null,
            // x-ms-* attributes have precedence over according HTTP-Headers
            httpHeader['x-ms-blob-content-type'] || httpHeader['Content-Type'] || 'application/octet-stream',
            httpHeader['x-ms-blob-content-encoding'] || httpHeader['Content-Encoding'] || 'utf8',
            httpHeader['x-ms-blob-content-language'] || httpHeader['Content-Language'],
            httpHeader['x-ms-blob-content-md5'] || httpHeader['Content-MD5'],
            httpHeader['x-ms-blob-cache-control'] || httpHeader['Cache-Control']);
    }

    _buildMetaProps(httpHeader) {
        let metaProps = {};
        Object.keys(httpHeader).forEach((key) => {
            const value = httpHeader[key];
            if (key.indexOf('x-ms-meta-') !== -1) {
                metaProps[key] = value;
            }
        });
        return metaProps;
    }

    _addResponseHeaders(res, props) {
        res.set({
            'ETag': props.ETag,
            'Last-Modified': props.lastModified,
            'x-ms-version': '2011-08-18',
            'x-ms-request-server-encrypted': false,
            'Content-MD5': props.md5
        });
    }
}

module.exports = new CreateBlockBlob();<|endoftext|>


<commit_before>require([
            'JBrowse/Browser',
            'JBrowse/Store/SeqFeature/VCFTabix',
            'JBrowse/Model/XHRBlob'
        ],
        function(
            Browser,
            VCFStore,
            XHRBlob
        ) {
describe('VCF store', function() {

  xit('reads big dbsnp', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../../data/big_vcf/00-All.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'chr10', start: 0, end: 135534747 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'chr10',
                             start: 33870887,
                             end: 33896487
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features.length).toEqual( 560 );
         });
  });

  it('reads gvcf * alleles', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../docs/tutorial/data_files/gvcf.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start: 0, end: 5000 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'ctgA',
                             start: 0,
                             end: 5000
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features.length).toEqual( 7 );
                  expect(features[2].get('alternative_alleles').values).toEqual("TC,<*>");
         });

  });

  it('no newline in VCF genotypes', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../docs/tutorial/data_files/volvox.test.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start: 0, end: 50000 }

         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'ctgA',
                             start: 0,
                             end: 7000
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  var gt = features[0].get('genotypes');
                  var names = Object.keys(gt);
                  var last = names[names.length-1];
                  expect(last.match("\n")).toEqual(null);
         });

  });

  it('reads gatk non_ref alleles', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../data/raw.g.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start: 0, end: 5000 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'ctgA',
                             start: 0,
                             end: 100
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features.length).toEqual( 37 );
                  expect(features[0].get('alternative_alleles').values).toEqual('<NON_REF>');
         });
  });

  it('parses END field', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../data/vcf.end.gz',
                 baseUrl: '.'
             },
             refSeq: { name: '1', start: 0, end: 50000 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: '1',
                             start: 0,
                             end: 5000
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features[0].get('end')).toEqual(4388);
                  expect(features[1].get('end')).toEqual(4600);
                  expect(features.length).toEqual( 2 );
         });

  });

  it('reads a CSI index', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../data/fake_large_chromosome/test.vcf.gz',
                 csiUrlTemplate: '../data/fake_large_chromosome/test.vcf.gz.csi',
                 baseUrl: '.'
             },
             refSeq: { name: '1', start:1206808844, end: 1206851071 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: '1',
                             start: 1206808844,
                             end: 12068510710
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features.length).toEqual( 111 );
         });

  });

  it('reads VCF tabix with dummy', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../docs/tutorial/data_files/volvox.filtered.vcf.gz',
                 tbiUrlTemplate: '../data/volvox.filtered.vcf.gz.tbi.has_dummy',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start:0, end: 50000 }
         });

         var stats = {};
         waitsFor( function() { return stats.done; } );
         store._estimateGlobalStats({ name: 'ctgA',
                        start: 0,
                        end:50000
                    }).then(function(f) {
                        stats = f;
                        stats.done = true;
                    });
         runs(function() {
             expect(stats.featureDensity).toBeCloseTo( 0.0009 );
         });

  });

  it('reads VCF tabix without dummy', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../docs/tutorial/data_files/volvox.filtered.vcf.gz',
                 tbiUrlTemplate: '../data/volvox.filtered.vcf.gz.tbi.no_dummy',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start:0, end: 50000 }
         });

         var stats = {};
         waitsFor( function() { return stats.done; } );
         store._estimateGlobalStats({ name: 'ctgA',
                        start: 0,
                        end:50000
                    }).then(function(f) {
                        stats = f;
                        stats.done = true;
                    });
         runs(function() {
            expect(stats.featureDensity).toBeCloseTo( 0.0009 );
         });

  });

  xit('large VCF header', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../data/large_vcf_header/large_vcf_header.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'LcChr1', start:0, end:1000 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'LcChr1',
                             start: 1,
                             end: 10000
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
             var a = features[0].get('genotypes');
             expect(Object.keys(a).length).toBeTruthy(); // expect non empty object
         });
  });

});
});
<commit_msg>fix and add to VCF CSI test<commit_after>require([
            'JBrowse/Browser',
            'JBrowse/Store/SeqFeature/VCFTabix',
            'JBrowse/Model/XHRBlob'
        ],
        function(
            Browser,
            VCFStore,
            XHRBlob
        ) {
describe('VCF store', function() {

  xit('reads big dbsnp', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../../data/big_vcf/00-All.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'chr10', start: 0, end: 135534747 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'chr10',
                             start: 33870887,
                             end: 33896487
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features.length).toEqual( 560 );
         });
  });

  it('reads gvcf * alleles', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../docs/tutorial/data_files/gvcf.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start: 0, end: 5000 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'ctgA',
                             start: 0,
                             end: 5000
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features.length).toEqual( 7 );
                  expect(features[2].get('alternative_alleles').values).toEqual("TC,<*>");
         });

  });

  it('no newline in VCF genotypes', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../docs/tutorial/data_files/volvox.test.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start: 0, end: 50000 }

         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'ctgA',
                             start: 0,
                             end: 7000
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  var gt = features[0].get('genotypes');
                  var names = Object.keys(gt);
                  var last = names[names.length-1];
                  expect(last.match("\n")).toEqual(null);
         });

  });

  it('reads gatk non_ref alleles', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../data/raw.g.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start: 0, end: 5000 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'ctgA',
                             start: 0,
                             end: 100
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features.length).toEqual( 37 );
                  expect(features[0].get('alternative_alleles').values).toEqual('<NON_REF>');
         });
  });

  it('parses END field', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../data/vcf.end.gz',
                 baseUrl: '.'
             },
             refSeq: { name: '1', start: 0, end: 50000 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: '1',
                             start: 0,
                             end: 5000
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features[0].get('end')).toEqual(4388);
                  expect(features[1].get('end')).toEqual(4600);
                  expect(features.length).toEqual( 2 );
         });

  });

  it('reads a CSI index', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../data/fake_large_chromosome/test.vcf.gz',
                 csiUrlTemplate: '../data/fake_large_chromosome/test.vcf.gz.csi',
                 baseUrl: '.'
             },
             refSeq: { name: '1', start:1206808844, end: 1206851071 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: '1',
                             start: 1206810422,
                             end: 1206849288
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
                  expect(features.length).toEqual( 37 );
                  expect(features[0].fields).toEqual([
                      "1",
                      "1206810423",
                      null,
                      "T",
                      "A",
                      "25",
                      null,
                      "DP=19;VDB=0.0404;AF1=0.5;AC1=1;DP4=3,7,3,6;MQ=37;FQ=28;PV4=1,1,1,0.27",
                      "GT:PL:GQ",
                      "0/1:55,0,73:58"
                  ])

         });

  });

  it('reads VCF tabix with dummy', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../docs/tutorial/data_files/volvox.filtered.vcf.gz',
                 tbiUrlTemplate: '../data/volvox.filtered.vcf.gz.tbi.has_dummy',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start:0, end: 50000 }
         });

         var stats = {};
         waitsFor( function() { return stats.done; } );
         store._estimateGlobalStats({ name: 'ctgA',
                        start: 0,
                        end:50000
                    }).then(function(f) {
                        stats = f;
                        stats.done = true;
                    });
         runs(function() {
             expect(stats.featureDensity).toBeCloseTo( 0.0009 );
         });

  });

  it('reads VCF tabix without dummy', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../../docs/tutorial/data_files/volvox.filtered.vcf.gz',
                 tbiUrlTemplate: '../data/volvox.filtered.vcf.gz.tbi.no_dummy',
                 baseUrl: '.'
             },
             refSeq: { name: 'ctgA', start:0, end: 50000 }
         });

         var stats = {};
         waitsFor( function() { return stats.done; } );
         store._estimateGlobalStats({ name: 'ctgA',
                        start: 0,
                        end:50000
                    }).then(function(f) {
                        stats = f;
                        stats.done = true;
                    });
         runs(function() {
            expect(stats.featureDensity).toBeCloseTo( 0.0009 );
         });

  });

  xit('large VCF header', function() {
         var store = new VCFStore({
             browser: new Browser({unitTestMode: true}),
             config: {
                 urlTemplate: '../data/large_vcf_header/large_vcf_header.vcf.gz',
                 baseUrl: '.'
             },
             refSeq: { name: 'LcChr1', start:0, end:1000 }
         });

         var features = [];
         waitsFor( function() { return features.done; } );
         store.getFeatures({ ref: 'LcChr1',
                             start: 1,
                             end: 10000
                           },
                           function(f) { features.push( f ); },
                           function( ) { features.done = true; },
                           function(e) { console.error(e.stack||''+e); }
                          );
         runs(function() {
             var a = features[0].get('genotypes');
             expect(Object.keys(a).length).toBeTruthy(); // expect non empty object
         });
  });

});
});
<|endoftext|>


<commit_before>/*
 * TopJs Framework (http://www.topjs.org/)
 *
 * @link      http://github.com/qcoreteam/topjs for the canonical source repository
 * @copyright Copyright (c) 2016-2017 QCoreTeam (http://www.qcoreteam.org)
 * @license   http://www.topjs.org/license/new-bsd New BSD License
 */
const StandardLoader = require("../../../lib/Entry").StandardLoader;
let assert = require("chai").assert;
let loader = new StandardLoader({
    [StandardLoader.AUTO_REGISTER_TOPJS]: true
});
loader.register();

describe("TopJs.Array", function ()
{
    describe("TopJs.Array.remove", function()
    {
        let myArray;
        describe("空数组相关的删除", function ()
        {
            beforeEach(function(){
                myArray = [];
            });
            it("在空数组上删除不抛出异常", function ()
            {
                assert.doesNotThrow(function(){
                    TopJs.Array.remove(myArray, 1, 21);
                });
                assert.deepEqual(TopJs.Array.remove(myArray, 1, 21), []);
            });

            it("删除空数组返回数组本身", function ()
            {
                assert.equal(TopJs.Array.remove(myArray), myArray);
            });
        });

        describe("操作一个非空的数组", function ()
        {
            beforeEach(function() {
                myArray = [1, 2, 3, 4, 5];
            });

            it("删除指定的元素", function ()
            {
                TopJs.Array.remove(myArray, 1);
                assert.deepEqual(myArray, [2, 3, 4, 5]);
            });

            it("删除之后返回原数组", function ()
            {
                assert.equal(TopJs.Array.remove(myArray, 1), myArray);
            });
            it("删除元素之后后面的元素索引跟着改变", function()
            {
                TopJs.Array.remove(myArray, 1);
                assert.equal(myArray[0], 2);
                assert.equal(myArray[1], 3);
                assert.equal(myArray[2], 4);
                assert.equal(myArray[3], 5);
            });
            it("多元素删除", function()
            {
                TopJs.Array.remove(myArray, 1, 5);
                assert.deepEqual(myArray, [2, 3, 4]);
            });
            it("删除不存在的元素", function ()
            {
                TopJs.Array.remove(myArray, 10);
                assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
            });
            it("删除之后长度变化", function ()
            {
                TopJs.Array.remove(myArray, 1);
                assert.equal(myArray.length, 4);
            });
            it("删除元素使用`===`严格相等", function ()
            {
                TopJs.Array.remove(myArray, '1');
                assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
            });
            it("只删除第一次出现的元素", function ()
            {
                let a = {};
                let b = {};
                myArray = [a, b, b, a, a, a];
                TopJs.Array.remove(myArray, b);
                assert.deepEqual(myArray, [a, b, a, a, a]);
            });
        });
    });

    describe("TopJs.Array.removeAt", function ()
    {
        beforeEach(function() {
            myArray = [1, 2, 3, 4, 5];
        });
        describe("索引不合法", function ()
        {
            describe("索引小于0", function ()
            {
                it("不抛出异常", function ()
                {
                    assert.doesNotThrow(function(){
                        TopJs.Array.removeAt(myArray, -1);
                    });
                })
            });
        });
    });
});
<commit_msg>完成TopJs.Array.removeAt单元测试<commit_after>/*
 * TopJs Framework (http://www.topjs.org/)
 *
 * @link      http://github.com/qcoreteam/topjs for the canonical source repository
 * @copyright Copyright (c) 2016-2017 QCoreTeam (http://www.qcoreteam.org)
 * @license   http://www.topjs.org/license/new-bsd New BSD License
 */
const StandardLoader = require("../../../lib/Entry").StandardLoader;
let assert = require("chai").assert;
let loader = new StandardLoader({
    [StandardLoader.AUTO_REGISTER_TOPJS]: true
});
loader.register();

describe("TopJs.Array", function ()
{
    describe("TopJs.Array.remove", function()
    {
        let myArray;
        describe("空数组相关的删除", function ()
        {
            beforeEach(function(){
                myArray = [];
            });
            it("在空数组上删除不抛出异常", function ()
            {
                assert.doesNotThrow(function(){
                    TopJs.Array.remove(myArray, 1, 21);
                });
                assert.deepEqual(TopJs.Array.remove(myArray, 1, 21), []);
            });

            it("删除空数组返回数组本身", function ()
            {
                assert.equal(TopJs.Array.remove(myArray), myArray);
            });
        });

        describe("操作一个非空的数组", function ()
        {
            beforeEach(function() {
                myArray = [1, 2, 3, 4, 5];
            });

            it("删除指定的元素", function ()
            {
                TopJs.Array.remove(myArray, 1);
                assert.deepEqual(myArray, [2, 3, 4, 5]);
            });

            it("删除之后返回原数组", function ()
            {
                assert.equal(TopJs.Array.remove(myArray, 1), myArray);
            });
            it("删除元素之后后面的元素索引跟着改变", function()
            {
                TopJs.Array.remove(myArray, 1);
                assert.equal(myArray[0], 2);
                assert.equal(myArray[1], 3);
                assert.equal(myArray[2], 4);
                assert.equal(myArray[3], 5);
            });
            it("多元素删除", function()
            {
                TopJs.Array.remove(myArray, 1, 5);
                assert.deepEqual(myArray, [2, 3, 4]);
            });
            it("删除不存在的元素", function ()
            {
                TopJs.Array.remove(myArray, 10);
                assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
            });
            it("删除之后长度变化", function ()
            {
                TopJs.Array.remove(myArray, 1);
                assert.equal(myArray.length, 4);
            });
            it("删除元素使用`===`严格相等", function ()
            {
                TopJs.Array.remove(myArray, '1');
                assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
            });
            it("只删除第一次出现的元素", function ()
            {
                let a = {};
                let b = {};
                myArray = [a, b, b, a, a, a];
                TopJs.Array.remove(myArray, b);
                assert.deepEqual(myArray, [a, b, a, a, a]);
            });
        });
    });

    describe("TopJs.Array.removeAt", function ()
    {
        beforeEach(function() {
            myArray = [1, 2, 3, 4, 5];
        });
        describe("索引不合法", function ()
        {
            describe("索引小于0", function ()
            {
                it("不抛出异常", function ()
                {
                    assert.doesNotThrow(function(){
                        TopJs.Array.removeAt(myArray, -1);
                    });
                });
                it("返回原数组", function ()
                {
                    assert.equal(TopJs.Array.removeAt(myArray, -1), myArray);
                });
                it("不修改数组的长度", function ()
                {
                    TopJs.Array.removeAt(myArray, -1);
                    assert.equal(myArray.length, 5);
                });
            });
            describe("索引大于数组长度", function ()
            {
                it("不抛出异常", function ()
                {
                    assert.doesNotThrow(function(){
                        TopJs.Array.removeAt(myArray, 100);
                    });
                });
                it("返回原数组", function ()
                {
                    assert.equal(TopJs.Array.removeAt(myArray, 100), myArray);
                });
                it("不修改数组的长度", function ()
                {
                    TopJs.Array.removeAt(myArray, 100);
                    assert.equal(myArray.length, 5);
                });
            });
        });
        describe("合法的数组索引", function ()
        {
            it("返回原数组", function ()
            {
                assert.equal(TopJs.Array.removeAt(myArray, 1), myArray);
            });
            it("删除第一个元素", function ()
            {
                TopJs.Array.removeAt(myArray, 0);
                assert.deepEqual(myArray, [2, 3, 4, 5]);
            });
            it("删除最后一个元素", function ()
            {
                TopJs.Array.removeAt(myArray, 4);
                assert.deepEqual(myArray, [1, 2, 3, 4]);
            });
            it("删除中间一个元素", function ()
            {
                TopJs.Array.removeAt(myArray, 2);
                assert.deepEqual(myArray, [1, 2, 4, 5]);
            });
            describe("删除多个元素", function ()
            {
                it("默认删除一个元素", function ()
                {
                    TopJs.Array.removeAt(myArray, 0);
                    assert.deepEqual(myArray, [2, 3, 4, 5]);
                });
                it("删除两个元素", function ()
                {
                    TopJs.Array.removeAt(myArray, 0, 2);
                    assert.deepEqual(myArray, [3, 4, 5]);
                });
                it("删除所有的元素", function ()
                {
                    TopJs.Array.removeAt(myArray, 0, 5);
                    assert.deepEqual(myArray, []);
                });
                it("删除指定元素到最最后一个元素", function ()
                {
                    TopJs.Array.removeAt(myArray, 1, 4);
                    assert.deepEqual(myArray, [1]);
                });
                it("数量超过数组的长度", function ()
                {
                    TopJs.Array.removeAt(myArray, 2, 100);
                    assert.deepEqual(myArray, [1, 2]);
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';
<commit_msg>:white_check_mark: Setup test suite<commit_after>'use strict';

import * as phantom from 'phantom';
import test from 'ava';

const page = new Promise(resolve => {
  phantom.create()
    .then(p => p.createPage())
    .then(p => {
      resolve(p.evaluate(function() {
        return this;
      }));
    });
});
<|endoftext|>