<commit_before>import expect from '../expect';

import {
  createModelBuilder
} from '../helper';

describe('properties', function() {

  var createModel = createModelBuilder('test/fixtures/model/');
  var model = createModel([ 'properties' ]);

  describe('descriptor', function() {

    it('should provide id property', function() {

      // when
      var Complex = model.getType('props:Complex');

      var descriptor = model.getElementDescriptor(Complex);
      var idProperty = descriptor.propertiesByName.id;

      // then
      expect(idProperty).to.exist;
      expect(idProperty.isId).to.be.true;

      expect(descriptor.idProperty).to.eql(idProperty);
    });

    it('should provide body property', function() {

      // when
      var SimpleBody = model.getType('props:SimpleBody');

      var descriptor = model.getElementDescriptor(SimpleBody);
      var bodyProperty = descriptor.propertiesByName.body;

      // then
      expect(bodyProperty).to.exist;
      expect(bodyProperty.isBody).to.be.true;

      expect(descriptor.bodyProperty).to.eql(bodyProperty);
    });

    it('should NOT provide default id', function() {

      // when
      var SimpleBody = model.getType('props:SimpleBody');

      var descriptor = model.getElementDescriptor(SimpleBody);
      var idProperty = descriptor.propertiesByName.id;

      // then
      expect(idProperty).not.to.exist;
    });

    it.skip('should inherit properties');

  });

  describe('instance', function() {

    it('should set simple properties in constructor', function() {

      // when
      var attributes = model.create('props:Attributes', {
        id: 'ATTR_1',
        booleanValue: false,
        integerValue: -1000
      });

      // then
      // expect constructor to have set values
      expect(attributes.id).to.equal('ATTR_1');
      expect(attributes.booleanValue).to.equal(false);
      expect(attributes.integerValue).to.equal(-1000);
    });

    it('should set collection properties in constructor (referencing)', function() {

      // given
      var reference1 = model.create('props:ComplexCount');
      var reference2 = model.create('props:ComplexNesting');

      // when
      var referencingCollection = model.create('props:ReferencingCollection', {
        references: [ reference1, reference2 ]
      });

      // then
      expect(referencingCollection.references).to.jsonEqual([ reference1, reference2 ]);

      // TODO: validate not parent -> child relationship
    });

    it('should set collection properties in constructor (containment)', function() {

      // given
      var child1 = model.create('props:ComplexCount');
      var child2 = model.create('props:ComplexNesting');

      // when
      var containedCollection = model.create('props:ContainedCollection', {
        children: [ child1, child2 ]
      });

      // then
      expect(containedCollection.children).to.jsonEqual([ child1, child2 ]);

      // TODO: establish parent relationship
    });

    it('should provide default values', function() {

      // given
      var Attributes = model.getType('props:Attributes');

      // when
      var instance = new Attributes();

      // then
      expect(instance.defaultBooleanValue).to.equal(true);
    });

    it('should provide inherited default values', function() {

      // given
      var SubAttributes = model.getType('props:SubAttributes');

      // when
      var instance = new SubAttributes();

      // then
      expect(instance.defaultBooleanValue).to.equal(true);
    });

    it.skip('should set collection properties in constructor');

    it('should lazy init collection properties', function() {

      // given
      var Root = model.getType('props:Root');
      var instance = new Root();

      // assume
      expect(instance.any).not.to.exist;

      // when
      var any = instance.get('props:any');

      // then
      expect(any).to.eql([]);
      expect(instance.any).to.equal(any);
    });

    describe('set', function() {

      it('should set property', function() {

        // given
        var instance = model.create('props:Attributes');

        // when
        instance.set('id', 'ATTR_1');

        // then
        expect(instance.id).to.equal('ATTR_1');
      });

      it('should set property (ns)', function() {

        // given
        var instance = model.create('props:Attributes');

        // when
        instance.set('props:booleanValue', true);
        instance.set('props:integerValue', -1000);

        // then
        expect(instance.booleanValue).to.equal(true);
        expect(instance.integerValue).to.equal(-1000);
      });

      it('should set extension property', function() {

        // given
        var instance = model.create('props:Attributes');

        // when
        instance.set('foo', 'bar');

        // then
        expect(instance.$attrs).to.have.property('foo', 'bar');
        expect(instance).not.to.have.keys('foo');
      });

      it('should set extension property (ns)', function() {

        // given
        var instance = model.create('props:Attributes');

        // when
        instance.set('namespace:foo', 'bar');

        // then
        expect(instance.$attrs).to.have.property('namespace:foo', 'bar');
        expect(instance).not.to.have.keys('foo', 'namespace:foo');
      });

    });

    describe('update', function() {

      it('should update property', function() {

        // given
        var attributes = model.create('props:Attributes', { id: 'ATTR_1' });

        // when
        attributes.set('id', 'ATTR_23');

        // then
        expect(attributes.id).to.equal('ATTR_23');
      });

      it('should update property (ns)', function() {

        // given
        var attributes = model.create('props:Attributes', { 'props:integerValue': -1000 });

        // when
        attributes.set('props:integerValue', 1024);

        // then
        expect(attributes.integerValue).to.equal(1024);
      });

      it('should update extension property', function() {

        // given
        var attributes = model.create('props:Attributes', { 'foo': 'bar' });

        // when
        attributes.set('foo', 'baz');

        // then
        expect(attributes.$attrs.foo).to.equal('baz');
      });

      it('should update extension property (ns)', function() {

        // given
        var attributes = model.create('props:Attributes', { 'foo:bar': 'baz' });

        // when
        attributes.set('foo:bar', 'qux');

        // then
        expect(attributes.$attrs).to.have.property('foo:bar', 'qux');
      });

    });

    describe('unset', function() {

      it('should unset property', function() {

        // given
        var attributes = model.create('props:Attributes', { id: 'ATTR_1' });

        // assume
        expect(attributes.id).to.equal('ATTR_1');

        // when
        attributes.set('id', undefined);

        // then
        expect(attributes).not.to.have.property('id');
      });

      it('should unset property (ns)', function() {

        // given
        var attributes = model.create('props:Attributes', {
          'props:integerValue': -1000
        });

        // assume
        expect(attributes.integerValue).to.equal(-1000);

        // when
        attributes.set('props:integerValue', undefined);

        // then
        expect(attributes).not.to.have.keys('integerValue', 'props:integerValue');
      });

      it('should unset extension property', function() {

        // given
        var attributes = model.create('props:Attributes', {
          'foobar': 42
        });

        // assume
        expect(attributes.$attrs.foobar).to.equal(42);

        // when
        attributes.set('foobar', undefined);

        // then
        expect(attributes.$attrs).not.to.have.keys('foobar');
      });

      it('should unset extension property (ns)', function() {

        // given
        var attributes = model.create('props:Attributes', {
          'foo:bar': 42
        });

        // assume
        expect(attributes.$attrs['foo:bar']).to.equal(42);

        // when
        attributes.set('foo:bar', undefined);

        // then
        expect(attributes.$attrs).not.to.have.keys('foo:bar');
      });

    });

  });

  describe('should redefine property', function() {

    it('descriptor', function() {

      // given

      // when
      var BaseWithId = model.getType('props:BaseWithId');
      var BaseWithNumericId = model.getType('props:BaseWithNumericId');

      var baseDescriptor = BaseWithId.$descriptor;
      var redefinedDescriptor = BaseWithNumericId.$descriptor;

      var originalIdProperty = baseDescriptor.propertiesByName.id;

      var refinedIdProperty = redefinedDescriptor.propertiesByName.id;
      var numericIdProperty = redefinedDescriptor.propertiesByName.idNumeric;

      // then
      expect(refinedIdProperty).not.to.jsonEqual(originalIdProperty);

      expect(refinedIdProperty).to.exist;
      expect(refinedIdProperty).to.eql(numericIdProperty);
    });

    describe('instance', function() {

      it('init in constructor', function() {

        // given
        var BaseWithNumericId = model.getType('props:BaseWithNumericId');

        // when
        var instance = new BaseWithNumericId({ 'id': 1000 });

        // then
        expect(instance.idNumeric).to.equal(1000);
      });

      it('access via original name', function() {

        // given
        var BaseWithNumericId = model.getType('props:BaseWithNumericId');

        // when
        var instance = new BaseWithNumericId({ 'id': 1000 });

        // then
        expect(instance.get('props:id')).to.equal(1000);
      });

      it('should return $attrs property on non-metamodel defined property access', function() {

        // given
        var BaseWithNumericId = model.getType('props:BaseWithNumericId');

        // when
        var instance = new BaseWithNumericId({ 'id': 1000 });

        instance.$attrs.unknown = 'UNKNOWN';

        // then
        expect(instance.get('unknown')).to.eql('UNKNOWN');
      });

      it('access via original name', function() {

        // given
        var BaseWithNumericId = model.getType('props:BaseWithNumericId');

        // when
        var instance = new BaseWithNumericId({ 'id': 1000 });

        // then
        expect(instance.get('props:idNumeric')).to.equal(1000);
      });

    });

  });

});
<commit_msg>chore(test): add testCase for inheritance of properties<commit_after>import expect from '../expect';

import {
  createModelBuilder
} from '../helper';

describe('properties', function() {

  var createModel = createModelBuilder('test/fixtures/model/');
  var model = createModel([ 'properties', 'properties-extended' ]);

  describe('descriptor', function() {

    it('should provide id property', function() {

      // when
      var Complex = model.getType('props:Complex');

      var descriptor = model.getElementDescriptor(Complex);
      var idProperty = descriptor.propertiesByName.id;

      // then
      expect(idProperty).to.exist;
      expect(idProperty.isId).to.be.true;

      expect(descriptor.idProperty).to.eql(idProperty);
    });

    it('should provide body property', function() {

      // when
      var SimpleBody = model.getType('props:SimpleBody');

      var descriptor = model.getElementDescriptor(SimpleBody);
      var bodyProperty = descriptor.propertiesByName.body;

      // then
      expect(bodyProperty).to.exist;
      expect(bodyProperty.isBody).to.be.true;

      expect(descriptor.bodyProperty).to.eql(bodyProperty);
    });

    it('should NOT provide default id', function() {

      // when
      var SimpleBody = model.getType('props:SimpleBody');

      var descriptor = model.getElementDescriptor(SimpleBody);
      var idProperty = descriptor.propertiesByName.id;

      // then
      expect(idProperty).not.to.exist;
    });

    it('should inherit properties', function() {

      // when
      var ExtRoot = model.getType('ext:Root');

      var descriptor = model.getElementDescriptor(ExtRoot);
      var elementsProperty = descriptor.propertiesByName.elements;
      var inheritedAnyProperty = descriptor.propertiesByName.any;

      // then
      expect(ExtRoot).to.exist;
      expect(elementsProperty).to.exist;
      expect(inheritedAnyProperty).to.exist;
    });

  });

  describe('instance', function() {

    it('should set simple properties in constructor', function() {

      // when
      var attributes = model.create('props:Attributes', {
        id: 'ATTR_1',
        booleanValue: false,
        integerValue: -1000
      });

      // then
      // expect constructor to have set values
      expect(attributes.id).to.equal('ATTR_1');
      expect(attributes.booleanValue).to.equal(false);
      expect(attributes.integerValue).to.equal(-1000);
    });

    it('should set collection properties in constructor (referencing)', function() {

      // given
      var reference1 = model.create('props:ComplexCount');
      var reference2 = model.create('props:ComplexNesting');

      // when
      var referencingCollection = model.create('props:ReferencingCollection', {
        references: [ reference1, reference2 ]
      });

      // then
      expect(referencingCollection.references).to.jsonEqual([ reference1, reference2 ]);

      // TODO: validate not parent -> child relationship
    });

    it('should set collection properties in constructor (containment)', function() {

      // given
      var child1 = model.create('props:ComplexCount');
      var child2 = model.create('props:ComplexNesting');

      // when
      var containedCollection = model.create('props:ContainedCollection', {
        children: [ child1, child2 ]
      });

      // then
      expect(containedCollection.children).to.jsonEqual([ child1, child2 ]);

      // TODO: establish parent relationship
    });

    it('should provide default values', function() {

      // given
      var Attributes = model.getType('props:Attributes');

      // when
      var instance = new Attributes();

      // then
      expect(instance.defaultBooleanValue).to.equal(true);
    });

    it('should provide inherited default values', function() {

      // given
      var SubAttributes = model.getType('props:SubAttributes');

      // when
      var instance = new SubAttributes();

      // then
      expect(instance.defaultBooleanValue).to.equal(true);
    });

    it.skip('should set collection properties in constructor');

    it('should lazy init collection properties', function() {

      // given
      var Root = model.getType('props:Root');
      var instance = new Root();

      // assume
      expect(instance.any).not.to.exist;

      // when
      var any = instance.get('props:any');

      // then
      expect(any).to.eql([]);
      expect(instance.any).to.equal(any);
    });

    describe('set', function() {

      it('should set property', function() {

        // given
        var instance = model.create('props:Attributes');

        // when
        instance.set('id', 'ATTR_1');

        // then
        expect(instance.id).to.equal('ATTR_1');
      });

      it('should set property (ns)', function() {

        // given
        var instance = model.create('props:Attributes');

        // when
        instance.set('props:booleanValue', true);
        instance.set('props:integerValue', -1000);

        // then
        expect(instance.booleanValue).to.equal(true);
        expect(instance.integerValue).to.equal(-1000);
      });

      it('should set extension property', function() {

        // given
        var instance = model.create('props:Attributes');

        // when
        instance.set('foo', 'bar');

        // then
        expect(instance.$attrs).to.have.property('foo', 'bar');
        expect(instance).not.to.have.keys('foo');
      });

      it('should set extension property (ns)', function() {

        // given
        var instance = model.create('props:Attributes');

        // when
        instance.set('namespace:foo', 'bar');

        // then
        expect(instance.$attrs).to.have.property('namespace:foo', 'bar');
        expect(instance).not.to.have.keys('foo', 'namespace:foo');
      });

    });

    describe('update', function() {

      it('should update property', function() {

        // given
        var attributes = model.create('props:Attributes', { id: 'ATTR_1' });

        // when
        attributes.set('id', 'ATTR_23');

        // then
        expect(attributes.id).to.equal('ATTR_23');
      });

      it('should update property (ns)', function() {

        // given
        var attributes = model.create('props:Attributes', { 'props:integerValue': -1000 });

        // when
        attributes.set('props:integerValue', 1024);

        // then
        expect(attributes.integerValue).to.equal(1024);
      });

      it('should update extension property', function() {

        // given
        var attributes = model.create('props:Attributes', { 'foo': 'bar' });

        // when
        attributes.set('foo', 'baz');

        // then
        expect(attributes.$attrs.foo).to.equal('baz');
      });

      it('should update extension property (ns)', function() {

        // given
        var attributes = model.create('props:Attributes', { 'foo:bar': 'baz' });

        // when
        attributes.set('foo:bar', 'qux');

        // then
        expect(attributes.$attrs).to.have.property('foo:bar', 'qux');
      });

    });

    describe('unset', function() {

      it('should unset property', function() {

        // given
        var attributes = model.create('props:Attributes', { id: 'ATTR_1' });

        // assume
        expect(attributes.id).to.equal('ATTR_1');

        // when
        attributes.set('id', undefined);

        // then
        expect(attributes).not.to.have.property('id');
      });

      it('should unset property (ns)', function() {

        // given
        var attributes = model.create('props:Attributes', {
          'props:integerValue': -1000
        });

        // assume
        expect(attributes.integerValue).to.equal(-1000);

        // when
        attributes.set('props:integerValue', undefined);

        // then
        expect(attributes).not.to.have.keys('integerValue', 'props:integerValue');
      });

      it('should unset extension property', function() {

        // given
        var attributes = model.create('props:Attributes', {
          'foobar': 42
        });

        // assume
        expect(attributes.$attrs.foobar).to.equal(42);

        // when
        attributes.set('foobar', undefined);

        // then
        expect(attributes.$attrs).not.to.have.keys('foobar');
      });

      it('should unset extension property (ns)', function() {

        // given
        var attributes = model.create('props:Attributes', {
          'foo:bar': 42
        });

        // assume
        expect(attributes.$attrs['foo:bar']).to.equal(42);

        // when
        attributes.set('foo:bar', undefined);

        // then
        expect(attributes.$attrs).not.to.have.keys('foo:bar');
      });

    });

  });

  describe('should redefine property', function() {

    it('descriptor', function() {

      // given

      // when
      var BaseWithId = model.getType('props:BaseWithId');
      var BaseWithNumericId = model.getType('props:BaseWithNumericId');

      var baseDescriptor = BaseWithId.$descriptor;
      var redefinedDescriptor = BaseWithNumericId.$descriptor;

      var originalIdProperty = baseDescriptor.propertiesByName.id;

      var refinedIdProperty = redefinedDescriptor.propertiesByName.id;
      var numericIdProperty = redefinedDescriptor.propertiesByName.idNumeric;

      // then
      expect(refinedIdProperty).not.to.jsonEqual(originalIdProperty);

      expect(refinedIdProperty).to.exist;
      expect(refinedIdProperty).to.eql(numericIdProperty);
    });

    describe('instance', function() {

      it('init in constructor', function() {

        // given
        var BaseWithNumericId = model.getType('props:BaseWithNumericId');

        // when
        var instance = new BaseWithNumericId({ 'id': 1000 });

        // then
        expect(instance.idNumeric).to.equal(1000);
      });

      it('access via original name', function() {

        // given
        var BaseWithNumericId = model.getType('props:BaseWithNumericId');

        // when
        var instance = new BaseWithNumericId({ 'id': 1000 });

        // then
        expect(instance.get('props:id')).to.equal(1000);
      });

      it('should return $attrs property on non-metamodel defined property access', function() {

        // given
        var BaseWithNumericId = model.getType('props:BaseWithNumericId');

        // when
        var instance = new BaseWithNumericId({ 'id': 1000 });

        instance.$attrs.unknown = 'UNKNOWN';

        // then
        expect(instance.get('unknown')).to.eql('UNKNOWN');
      });

      it('access via original name', function() {

        // given
        var BaseWithNumericId = model.getType('props:BaseWithNumericId');

        // when
        var instance = new BaseWithNumericId({ 'id': 1000 });

        // then
        expect(instance.get('props:idNumeric')).to.equal(1000);
      });

    });

  });

});
<|endoftext|>


<commit_before>/**
 * import(s)
 */

var validates = require('../../lib/validates')
var required = validates.required
var pattern = validates.pattern
var minLength = validates.minLength
var maxLength = validates.maxLength
var min = validates.min
var max = validates.max

describe('validates', function () {
  describe('required', function () {
    describe('string', function () {
      describe('not empty', function () {
        it('should be true', function () {
          expect(required('hello')).to.be(true)
        })
      })

      describe('empty', function () {
        it('should be false', function () {
          expect(required('')).to.be(false)
        })
      })
    })

    describe('boolean', function () {
      describe('true', function () {
        it('should be true', function () {
          expect(required(true)).to.be(true)
        })
      })

      describe('false', function () {
        it('should be false', function () {
          expect(required(false)).to.be(false)
        })
      })
    })

    describe('numeric', function () {
      describe('integer', function () {
        it('should be true', function () {
          expect(required(11)).to.be(true)
        })
      })

      describe('float', function () {
        it('should be true', function () {
          expect(required(0.11)).to.be(true)
        })
      })
    })

    describe('object', function () {
      it('should be true', function () {
        expect(required({ foo: 'bar' })).to.be(true)
      })
    })

    describe('array', function () {
      it('should be true', function () {
        expect(required([1, 'foo'])).to.be(true)
      })
    })

    describe('function', function () {
      it('should be true', function () {
        expect(required(function () {})).to.be(true)
      })
    })

    describe('undefined', function () {
      it('should be false', function () {
        expect(required(undefined)).to.be(false)
      })
    })

    describe('null', function () {
      it('should be false', function () {
        expect(required(null)).to.be(false)
      })
    })
  })

  describe('pattern', function () {
    describe('basic regex', function () {
      describe('valid', function () {
        it('should be true', function () {
          expect(pattern('foo', '/^[0-9a-zA-Z]+$/')).to.be(true)
        })
      })

      describe('invalid', function () {
        it('should be false', function () {
          expect(pattern('', '/^[0-9a-zA-Z]+$/')).to.be(false)
        })
      })
    })

    describe('flag regex', function () {
      describe('valid', function () {
        it('should be true', function () {
          expect(pattern('HELLO', '/hello/i')).to.be(true)
        })
      })

      describe('invalid', function () {
        it('should be false', function () {
          expect(pattern('foo', '/hello/i')).to.be(false)
        })
      })
    })
  })

  describe('minLength', function () {
    describe('boundary', function () {
      describe('length - 1', function () {
        it('should be false', function () {
          expect(minLength('aaa', '4')).to.be(false)
        })
      })

      describe('just length', function () {
        it('should be true', function () {
          expect(minLength('aaaa', '4')).to.be(true)
        })
      })

      describe('length + 1', function () {
        it('should be true', function () {
          expect(minLength('aaaaa', '4')).to.be(true)
        })
      })
    })

    describe('not string', function () {
      it('should be false', function () {
        expect(minLength(111, '4')).to.be(false)
      })
    })
  })

  describe('maxLength', function () {
    describe('boundary', function () {
      describe('length - 1', function () {
        it('should be true', function () {
          expect(maxLength('aaa', '4')).to.be(true)
        })
      })

      describe('just length', function () {
        it('should be true', function () {
          expect(maxLength('aaaa', '4')).to.be(true)
        })
      })

      describe('length + 1', function () {
        it('should be false', function () {
          expect(maxLength('aaaaa', '4')).to.be(false)
        })
      })
    })

    describe('not string', function () {
      it('should be false', function () {
        expect(maxLength({}, '4')).to.be(false)
      })
    })
  })

  describe('min', function () {
    describe('boundary', function () {
      describe('value - 1', function () {
        it('should be false', function () {
          expect(min('3', '4')).to.be(false)
        })
      })

      describe('just value', function () {
        it('should be true', function () {
          expect(min('4', '4')).to.be(true)
        })
      })

      describe('value + 1', function () {
        it('should be true', function () {
          expect(min('5', '4')).to.be(true)
        })
      })
    })

    describe('not number', function () {
      it('should be false', function () {
        expect(min(function () {}, '4')).to.be(false)
      })
    })
  })

  describe('max', function () {
    describe('boundary', function () {
      describe('value - 1', function () {
        it('should be true', function () {
          expect(max('7', '8')).to.be(true)
        })
      })

      describe('just value', function () {
        it('should be true', function () {
          expect(max('8', '8')).to.be(true)
        })
      })

      describe('value + 1', function () {
        it('should be false', function () {
          expect(max('9', '8')).to.be(false)
        })
      })
    })

    describe('not number', function () {
      it('should be false', function () {
        expect(max([1, 2], '4')).to.be(false)
      })
    })
  })
})
<commit_msg>Update comment<commit_after>/**
 * Import(s)
 */

var validates = require('../../lib/validates')
var required = validates.required
var pattern = validates.pattern
var minLength = validates.minLength
var maxLength = validates.maxLength
var min = validates.min
var max = validates.max

describe('validates', function () {
  describe('required', function () {
    describe('string', function () {
      describe('not empty', function () {
        it('should be true', function () {
          expect(required('hello')).to.be(true)
        })
      })

      describe('empty', function () {
        it('should be false', function () {
          expect(required('')).to.be(false)
        })
      })
    })

    describe('boolean', function () {
      describe('true', function () {
        it('should be true', function () {
          expect(required(true)).to.be(true)
        })
      })

      describe('false', function () {
        it('should be false', function () {
          expect(required(false)).to.be(false)
        })
      })
    })

    describe('numeric', function () {
      describe('integer', function () {
        it('should be true', function () {
          expect(required(11)).to.be(true)
        })
      })

      describe('float', function () {
        it('should be true', function () {
          expect(required(0.11)).to.be(true)
        })
      })
    })

    describe('object', function () {
      it('should be true', function () {
        expect(required({ foo: 'bar' })).to.be(true)
      })
    })

    describe('array', function () {
      it('should be true', function () {
        expect(required([1, 'foo'])).to.be(true)
      })
    })

    describe('function', function () {
      it('should be true', function () {
        expect(required(function () {})).to.be(true)
      })
    })

    describe('undefined', function () {
      it('should be false', function () {
        expect(required(undefined)).to.be(false)
      })
    })

    describe('null', function () {
      it('should be false', function () {
        expect(required(null)).to.be(false)
      })
    })
  })

  describe('pattern', function () {
    describe('basic regex', function () {
      describe('valid', function () {
        it('should be true', function () {
          expect(pattern('foo', '/^[0-9a-zA-Z]+$/')).to.be(true)
        })
      })

      describe('invalid', function () {
        it('should be false', function () {
          expect(pattern('', '/^[0-9a-zA-Z]+$/')).to.be(false)
        })
      })
    })

    describe('flag regex', function () {
      describe('valid', function () {
        it('should be true', function () {
          expect(pattern('HELLO', '/hello/i')).to.be(true)
        })
      })

      describe('invalid', function () {
        it('should be false', function () {
          expect(pattern('foo', '/hello/i')).to.be(false)
        })
      })
    })
  })

  describe('minLength', function () {
    describe('boundary', function () {
      describe('length - 1', function () {
        it('should be false', function () {
          expect(minLength('aaa', '4')).to.be(false)
        })
      })

      describe('just length', function () {
        it('should be true', function () {
          expect(minLength('aaaa', '4')).to.be(true)
        })
      })

      describe('length + 1', function () {
        it('should be true', function () {
          expect(minLength('aaaaa', '4')).to.be(true)
        })
      })
    })

    describe('not string', function () {
      it('should be false', function () {
        expect(minLength(111, '4')).to.be(false)
      })
    })
  })

  describe('maxLength', function () {
    describe('boundary', function () {
      describe('length - 1', function () {
        it('should be true', function () {
          expect(maxLength('aaa', '4')).to.be(true)
        })
      })

      describe('just length', function () {
        it('should be true', function () {
          expect(maxLength('aaaa', '4')).to.be(true)
        })
      })

      describe('length + 1', function () {
        it('should be false', function () {
          expect(maxLength('aaaaa', '4')).to.be(false)
        })
      })
    })

    describe('not string', function () {
      it('should be false', function () {
        expect(maxLength({}, '4')).to.be(false)
      })
    })
  })

  describe('min', function () {
    describe('boundary', function () {
      describe('value - 1', function () {
        it('should be false', function () {
          expect(min('3', '4')).to.be(false)
        })
      })

      describe('just value', function () {
        it('should be true', function () {
          expect(min('4', '4')).to.be(true)
        })
      })

      describe('value + 1', function () {
        it('should be true', function () {
          expect(min('5', '4')).to.be(true)
        })
      })
    })

    describe('not number', function () {
      it('should be false', function () {
        expect(min(function () {}, '4')).to.be(false)
      })
    })
  })

  describe('max', function () {
    describe('boundary', function () {
      describe('value - 1', function () {
        it('should be true', function () {
          expect(max('7', '8')).to.be(true)
        })
      })

      describe('just value', function () {
        it('should be true', function () {
          expect(max('8', '8')).to.be(true)
        })
      })

      describe('value + 1', function () {
        it('should be false', function () {
          expect(max('9', '8')).to.be(false)
        })
      })
    })

    describe('not number', function () {
      it('should be false', function () {
        expect(max([1, 2], '4')).to.be(false)
      })
    })
  })
})
<|endoftext|>


<commit_before>var http = require('http');
var fs = require("fs");

var assert = require("assert");
var sizeOf = require('image-size');

var screenshot = require('../');

describe('screenshot', function() {

    var server = http.createServer(function(req, res) {
        res.end('test');
    });

    before(function(done) {
        server.listen(9000);
        server.on('listening', done);
    });

    after(function(done) {
        server.close();
        done();
    });

    describe('render', function() {
        it('should render test image', function(done) {
            screenshot('http://localhost:9000', 'localhost.png').done(function() {
                var dimensions = sizeOf('localhost.png');
                assert.equal(dimensions.width, 1280, 'default width is incorrect');
                fs.unlinkSync('localhost.png');
                done();
            });
        });

        it('should render image in custom size', function(done) {
            screenshot(
                'http://localhost:9000',
                'localhost.png', {
                    width: 800,
                    height: 600
                }
            ).done(function() {
                var dimensions = sizeOf('localhost.png');

                assert.equal(dimensions.width, 800, 'width is incorrect');

                // The content of test page is so small, so viewport
                // is larger than content. If content were larger,
                // screenshot's height could be bigger than viewport's width
                assert.equal(dimensions.height, 600, 'height is incorrect');

                fs.unlinkSync('localhost.png');
                done();
            });
        });

        it('should fail', function(done) {
            screenshot(
                'http://failure',
                'localhost.png', {
                    width: 800,
                    height: 600
                }
            ).fail(function(err) {
                done();
            });
        });
    });
});
<commit_msg>Increase timeout for tests to prevent travis fails<commit_after>var http = require('http');
var fs = require("fs");

var assert = require("assert");
var sizeOf = require('image-size');

var screenshot = require('../');

describe('screenshot', function() {

    var server = http.createServer(function(req, res) {
        res.end('test');
    });

    before(function(done) {
        server.listen(9000);
        server.on('listening', done);
    });

    after(function(done) {
        server.close();
        done();
    });

    describe('render', function() {
        this.timeout(5000);

        it('should render test image', function(done) {
            screenshot('http://localhost:9000', 'localhost.png').done(function() {
                var dimensions = sizeOf('localhost.png');
                assert.equal(dimensions.width, 1280, 'default width is incorrect');
                fs.unlinkSync('localhost.png');
                done();
            });
        });

        it('should render image in custom size', function(done) {
            screenshot(
                'http://localhost:9000',
                'localhost.png', {
                    width: 800,
                    height: 600
                }
            ).done(function() {
                var dimensions = sizeOf('localhost.png');

                assert.equal(dimensions.width, 800, 'width is incorrect');

                // The content of test page is so small, so viewport
                // is larger than content. If content were larger,
                // screenshot's height could be bigger than viewport's width
                assert.equal(dimensions.height, 600, 'height is incorrect');

                fs.unlinkSync('localhost.png');
                done();
            });
        });

        it('should fail', function(done) {
            screenshot(
                'http://failure',
                'localhost.png', {
                    width: 800,
                    height: 600
                }
            ).fail(function(err) {
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {
  browsers,
  commentFlow,
  disableExperimentalPlugins,
  disableSourceMaps,
  jsx,
  minify,
  node,
  platforms,
  react,
  removeFlow,
  typeScript,
  watchBuild,
} from '../flags'
import {CONFIGS_DIR, setTargetDir} from '../paths'
import {getSettings} from '../settings'
import {join} from 'path'
import {exitOnError, runCommandSync} from '../system'
import {exitOnPackageNotFound} from '../util'

const PRESET_LOCATION = join(CONFIGS_DIR, 'babel-preset', 'index.js')
const BASIC_ARGS = [
  '"src"',
  '-d "build"',
  '--ignore "**/__tests__"',
  `--presets="${PRESET_LOCATION}"`,
]

function builder(yargs) {
  browsers(yargs)
  commentFlow(yargs)
  disableExperimentalPlugins(yargs)
  disableSourceMaps(yargs)
  jsx(yargs)
  minify(yargs)
  node(yargs)
  platforms(yargs)
  react(yargs)
  removeFlow(yargs)
  typeScript(yargs)
  watchBuild(yargs)
}

function handler(args) {
  setTargetDir(args.dir)
  exitOnPackageNotFound()

  exitOnError(runCommandSync('rimraf', {args: ['"build"']}))

  let {bundle} = getSettings()
  if (bundle)
    runWebpack(args)
  else
    runBabel(args)
}

function runBabel(args) {
  let {disableSourceMaps, watch} = args
  let babelArgs = [...BASIC_ARGS]

  if (!disableSourceMaps)
    babelArgs.push('--source-maps')

  if (watch)
    babelArgs.push('--watch')

  exitOnError(runCommandSync('babel', {
    args: babelArgs,
    env: args
  }))
}

function runWebpack(args) {
  exitOnError(runCommandSync('webpack', {env: args}))
}

export default {
  command: 'build [dir]',
  description: 'Build using Webpack.',
  builder,
  handler,
}
<commit_msg>Run webpack only on build<commit_after>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {
  browsers,
  commentFlow,
  disableExperimentalPlugins,
  disableSourceMaps,
  jsx,
  minify,
  node,
  platforms,
  react,
  removeFlow,
  typeScript,
  watchBuild,
} from '../flags'
import {CONFIGS_DIR, setTargetDir} from '../paths'
import {getSettings} from '../settings'
import {join} from 'path'
import {exitOnError, runCommandSync} from '../system'
import {exitOnPackageNotFound} from '../util'

const WEBPACK_CONFIG_PATH = join(CONFIGS_DIR, 'webpack')

function builder(yargs) {
  browsers(yargs)
  commentFlow(yargs)
  disableExperimentalPlugins(yargs)
  disableSourceMaps(yargs)
  jsx(yargs)
  minify(yargs)
  node(yargs)
  platforms(yargs)
  react(yargs)
  removeFlow(yargs)
  typeScript(yargs)
  watchBuild(yargs)
}

function handler(args) {
  setTargetDir(args.dir)
  exitOnPackageNotFound()

  exitOnError(runCommandSync('rimraf', {args: ['"build"']}))
  exitOnError(runCommandSync('webpack', {
    args: [`--config "${WEBPACK_CONFIG_PATH}"`],
    env: args,
  }))
}

export default {
  command: 'build [dir]',
  description: 'Build using Webpack.',
  builder,
  handler,
}
<|endoftext|>


<commit_before>import glob from 'glob';
import { CLIEngine } from 'eslint';
import LintRunner from '../LintRunner';
import { flatten } from '../util';

const ROOT_DIR = process.cwd();
const eslint = new CLIEngine({ cwd: ROOT_DIR });

export const check = (options) => {
  const {
    workers,
    paths,
    json
  } = options;

  const lintRunner = new LintRunner(workers);

  const filePaths = flatten(paths.map(globPath => glob.sync(globPath)));

  lintRunner.run({ cwd: ROOT_DIR }, filePaths)
    .then((results) => {
      const records = results.records.filter((record) => {
        return record.warningCount > 0 || record.errorCount > 0;
      });

      if (json) {
        console.log(JSON.stringify(records));
      } else {
        const formatter = eslint.getFormatter();
        console.log(formatter(records));
      }
      process.exit(results && results.errorCount > 0 ? 1 : 0);
    });
};
<commit_msg>Filter out ignored filepaths in check command (#47)<commit_after>import glob from 'glob';
import path from 'path';
import { CLIEngine } from 'eslint';
import LintRunner from '../LintRunner';
import { flatten } from '../util';

const ROOT_DIR = process.cwd();
const eslint = new CLIEngine({ cwd: ROOT_DIR });

export const check = (options) => {
  const {
    workers,
    paths,
    json
  } = options;

  const lintRunner = new LintRunner(workers);

  const filePaths = flatten(paths.map(globPath => glob.sync(globPath)));
  // filter out the files that we tell eslint to ignore
  const nonIgnoredFilePaths = filePaths.filter((filePath) => {
    return !(eslint.isPathIgnored(path.join(ROOT_DIR, filePath)) || filePath.indexOf('eslint') !== -1);
  });

  lintRunner.run({ cwd: ROOT_DIR }, nonIgnoredFilePaths)
    .then((results) => {
      const records = results.records.filter((record) => {
        return record.warningCount > 0 || record.errorCount > 0;
      });

      if (json) {
        console.log(JSON.stringify(records));
      } else {
        const formatter = eslint.getFormatter();
        console.log(formatter(records));
      }
      process.exit(results && results.errorCount > 0 ? 1 : 0);
    });
};
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import Comment from './comment.js'
import LoadingContainer, {PresentState, EmptyState} from 'snax/lib/containers/loading'

class Comments extends React.Component {

  static propTypes = {
    records: React.PropTypes.array,
    empty: React.PropTypes.string.isRequired
  }

  static defaultProps = {
    empty: "No records found."
  }

  render() {
    return (
      <LoadingContainer content={this.props.records} useLoader>
        <EmptyState>

{this.props.empty}

        </EmptyState>
        <PresentState>

            { this.props.records.map((record, index) => {
              return <Comment {...record} key={`event_${index}`} />
            })}

        </PresentState>
      </LoadingContainer>
    )
  }

}

export default Comments
<commit_msg>fix css<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import Comment from './comment.js'
import LoadingContainer, {PresentState, EmptyState} from 'snax/lib/containers/loading'

class Comments extends React.Component {

  static propTypes = {
    records: React.PropTypes.array,
    empty: React.PropTypes.string.isRequired
  }

  static defaultProps = {
    empty: "No records found."
  }

  render() {
    return (
      <LoadingContainer content={this.props.records} useLoader>
        <EmptyState>

{this.props.empty}

        </EmptyState>
        <PresentState>

            { this.props.records.map((record, index) => {
              return <Comment {...record} key={`event_${index}`} />
            })}

        </PresentState>
      </LoadingContainer>
    )
  }

}

export default Comments
<|endoftext|>


<commit_before>function addChromeListener() {
  chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
    if (req.tickets) {
      sendResponse(findOpenTickets());
    }
  });
}

function addFirefoxListener() {
  self.port.on("get-tickets", function getTickets() {
    self.port.emit("tickets", findOpenTickets());
  });
}

function handleSafariMessage(msgEvent) {
  if (window.top === window) {
    if (msgEvent.name == "get-tickets") {
      setTimeout(function() {
        safari.self.tab.dispatchMessage("tickets", findOpenTickets());
      }, 10);
    }
  }
}

function addSafariListener() {
  safari.self.addEventListener("message", handleSafariMessage, false);
}

function pivotalStories(stories, collapsed) {
  storyTitles = []
  stories.each(function () {
    var story = $(this);
    var title = (collapsed ? story.find('.story_name').text() : story.find('.editor.name').val());
    var id = /story_(\d+)/.exec(story.attr('class'))[1];
    classes = story.attr('class').split(" ");
    if (classes.indexOf("bug") > 0) {
      type = "bug"
    } else if (classes.indexOf("chore") > 0) {
      type = "chore"
    } else if (classes.indexOf("feature") > 0) {
      type = "feature"
    } else if (classes.indexOf("release") > 0) {
      type = "release"
    }
    storyTitles.push({id: id, title: title, type: type})
  });
  return storyTitles;
}

var findOpenTickets = function() {
  if ($(".gh-header-number").length > 0) {
    // Github
    var title = $(".js-issue-title").text();
    var id = $(".gh-header-number").text().substr(1);
    var type = "feature";
    if ($(".sidebar-labels .label[title='bug']").length > 0) {
      type = "bug"
    }
    return [{type: type, title: title, id: id}];
  } else if ((story = $(".ghx-fieldname-issuekey a")).length > 0) {
    // Jira sidebar
    var title = $("[data-field-id='summary']").text();
    var id = story.text();
    return [{id: id, title: title}];
  } else if ((story = $(".aui-page-header-inner .aui-page-header-main")).length > 0) {
    // Jira ticket page
    var title = $("#summary-val", story).text();
    var id = $(".issue-link", story).text();
    return [{id: id, title: title}];
  } else if ($('div.story .selector.selected').length > 0) {
    // Pivotal Tracker selected stories
    var stories = $('div.story .selector.selected').closest('.story');
    return pivotalStories(stories, true);
  } else if ($('div.story .details').length > 0) {
    // Pivotal Tracker opened stories
    var stories = $('div.story .details').closest('.story');
    return pivotalStories(stories, false);
  } else if ($("#tracker .story .name textarea").length > 0) {
    // Pivotal Tracker one story in separate tab
    var id = $("#tracker aside input.id").val();
    var title = $("#tracker .story .name textarea").text();
    var type = $("#tracker aside .story_type .selection").text();
    return [{id: id, title: title, type: type}]
  } else {
    return null;
  }
}

if (bowser.chrome) {
  if (window == top) {
    addChromeListener();
  }
} else if (bowser.firefox) {
  addFirefoxListener();
} else if (bowser.safari) {
  addSafariListener();
}

<commit_msg>Update content.js (#8)<commit_after>function addChromeListener() {
  chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
    if (req.tickets) {
      sendResponse(findOpenTickets());
    }
  });
}

function addFirefoxListener() {
  self.port.on("get-tickets", function getTickets() {
    self.port.emit("tickets", findOpenTickets());
  });
}

function handleSafariMessage(msgEvent) {
  if (window.top === window) {
    if (msgEvent.name == "get-tickets") {
      setTimeout(function() {
        safari.self.tab.dispatchMessage("tickets", findOpenTickets());
      }, 10);
    }
  }
}

function addSafariListener() {
  safari.self.addEventListener("message", handleSafariMessage, false);
}

function pivotalStories(stories, collapsed) {
  var storyTitles = [];
  stories.each(function () {
    var story = $(this);
    var title = (collapsed ? story.find('.story_name').text() : story.find('.editor.name').val());
    var id = /story_(\d+)/.exec(story.attr('class'))[1];
    classes = story.attr('class').split(" ");
    if (classes.indexOf("bug") > 0) {
      type = "bug"
    } else if (classes.indexOf("chore") > 0) {
      type = "chore"
    } else if (classes.indexOf("feature") > 0) {
      type = "feature"
    } else if (classes.indexOf("release") > 0) {
      type = "release"
    }
    storyTitles.push({id: id, title: title, type: type})
  });
  return storyTitles;
}

var findOpenTickets = function() {
  if ($(".gh-header-number").length > 0) {
    // Github
    var title = $(".js-issue-title").text();
    var id = $(".gh-header-number").text().substr(1);
    var type = "feature";
    if ($(".sidebar-labels .label[title='bug']").length > 0) {
      type = "bug"
    }
    return [{type: type, title: title, id: id}];
  } else if ((story = $(".ghx-fieldname-issuekey a")).length > 0) {
    // Jira sidebar
    var title = $("[data-field-id='summary']").text();
    var id = story.text();
    return [{id: id, title: title}];
  } else if ((story = $(".aui-page-header-inner .aui-page-header-main")).length > 0) {
    // Jira ticket page
    var title = $("#summary-val", story).text();
    var id = $(".issue-link", story).text();
    return [{id: id, title: title}];
  } else if ($('div.story .selector.selected').length > 0) {
    // Pivotal Tracker selected stories
    var stories = $('div.story .selector.selected').closest('.story');
    return pivotalStories(stories, true);
  } else if ($('div.story .details').length > 0) {
    // Pivotal Tracker opened stories
    var stories = $('div.story .details').closest('.story');
    return pivotalStories(stories, false);
  } else if ($("#tracker .story .name textarea").length > 0) {
    // Pivotal Tracker one story in separate tab
    var id = $("#tracker aside input.id").val();
    var title = $("#tracker .story .name textarea").text();
    var type = $("#tracker aside .story_type .selection").text();
    return [{id: id, title: title, type: type}]
  } else {
    return null;
  }
}

if (bowser.chrome) {
  if (window == top) {
    addChromeListener();
  }
} else if (bowser.firefox) {
  addFirefoxListener();
} else if (bowser.safari) {
  addSafariListener();
}

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import CubeContainer from './CubeContainer'

class App extends Component {
  render() {
    return (

          <CubeContainer/>

    );
  }
}

export default App;
<commit_msg>Update App.js<commit_after>import React, { Component } from 'react';
import CubeContainer from './CubeContainer';

class App extends Component {

    constructor(props){
        super(props);
        this.rangeChange=this.rangeChange.bind(this);
        this.state={orientation:[0,0,0]};
    }

    rangeChange(eve) {
        this.setState({orientation:[0,eve.target.value,0]})
    }

    render() {
        return (

                <input onChange={this.rangeChange} type="range" min="0" max="360" style={{'margin-bottom':'100px'}}/>
                <CubeContainer orientation={this.state.orientation}/>

        );
    }
}

export default App;
<|endoftext|>


<commit_before>import React from "react";
import connectToStores from "alt/utils/connectToStores";
import GwasActions from "../actions/GwasActions";
import GwasStore from "../stores/GwasStore";
import {Input, Button, Table, Alert, Grid, Row, Col} from "react-bootstrap";
import {LinkContainer} from "react-router-bootstrap";
import {Link, History} from "react-router";

const ExternalLink = (props => {
    if (props.children) {
        return {props.children};
    }
    else {
        return ;
    }
});

class App extends React.Component {

    constructor(props) {
        super(props);
        this.onSearch = this.onSearch.bind(this);
        this.onClear = this.onClear.bind(this);
    }

    static getStores(props) {
        return [GwasStore];
    }

    static getPropsFromStores(props) {
        return {
            results: GwasStore.getResults(),
            traits: GwasStore.getTraits(),
            different: GwasStore.getDifferent(),
            total: GwasStore.getTotal()
        };
    }

    componentDidUpdate(prevProps) {
        let oldQ = prevProps.params.q;
        let newQ = this.props.params.q;
        if (newQ !== oldQ) {
            GwasActions.search(this.props.params.q);
        }
    }

    onLinkClick(value, e) {
        GwasActions.search(value);
    }

    onSearch(e) {
        e.preventDefault();
        this.props.history.pushState(null, `/search/${this.refs.query.getValue()}`)
        GwasActions.search(this.refs.query.getValue());
    }

    onClear(e) {
        this.props.history.pushState(null, `/search/`)
        GwasActions.search('');
    }

    rowclass(p) {
        if (p > 0.00000005) {
            return "uninteresting";
        }
    }
    exp(number) {
        if (number && !isNaN(number)) {
            return number.toExponential();
        }
    }
    getYear(datestring) {
        return datestring.split("-").pop();
    }
    renderResults() {
        if (!this.props.params.q) {
            return (
                <Grid>
                    <Row>
                        <Col xs={12}>

                            Use the search field or select from the traits below if you want to see some results

                            {this.props.traits.map(trait =>

                                                       <Link to={`/search/${trait.get("_id")}`}>{trait.get("_id")}</Link> <ExternalLink href={trait.get("uri")} />

                                                   )}

                        </Col>
                    </Row>
                </Grid>
            );
        }
        else if (this.props.params.q && this.props.params.q.length < 3) {
            return <Alert style={{width: "600px", margin: "0 auto"}} bsStyle="danger">We need at least three characters, or we will crash your browser</Alert>;
        }
        else {
            let exportButton = <Button href={`/search/${this.props.params.q}.csv`} style={{float: "right", marginTop: -37, marginRight: 5}}>Download</Button>;
            return (

                    {exportButton}

                                SNP
                                MAF
                                P
                                Position
                                Mapped gene
                                Mapped trait
                                OR or Beta
                                Year
                                First author
                                Pubmed

                            {this.props.results.map(result =>

                                        <Link to={`/search/${result.get("SNP_ID_CURRENT")}`}>
                                            {result.get("SNPS")}
                                        </Link>

                                    {result.get("hunt")}

                                        {this.exp(result.get("P-VALUE")) || "0.0" }

                                        {result.get("P-VALUE (TEXT)")}

                                        <Link to={`/search/${result.get("REGION")}`}>
                                            {result.get("REGION")}
                                        </Link>

                                        <Link to={result.get("CHR_ID") ? `/search/chr${result.get("CHR_ID")}:${result.get("CHR_POS")}` : ""}>
                                            {result.get("CHR_ID") ? `chr${result.get("CHR_ID")}:${result.get("CHR_POS")}` : ""}
                                        </Link>

                                        {result.get("CONTEXT")}

                                        <Link to={`/search/${result.get("MAPPED_GENE")}`}>
                                            {result.get("MAPPED_GENE")}
                                        </Link> <ExternalLink href={`http://www.genecards.org/cgi-bin/carddisp.pl?gene=${result.get("MAPPED_GENE")}`} />

                                    {result.get("MAPPED_TRAIT").split(", ").map(trait =>

                                            <Link to={`/search/${trait}`}>
                                                {trait}
                                            </Link>

                                    )}

{result.get("OR or BETA")}

{result.get("95% CI (TEXT)")}

{this.getYear(result.get("DATE"))}

{result.get("DATE ADDED TO CATALOG")}

                                    <Link to={`/search/${result.get("FIRST AUTHOR")}`}>
                                        {result.get("FIRST AUTHOR")}
                                    </Link>

                                    <Link to={`/search/${result.get("PUBMEDID")}`}>
                                        {result.get("PUBMEDID")}
                                    </Link> <ExternalLink href={`http://www.ncbi.nlm.nih.gov/pubmed/${result.get("PUBMEDID")}`} />

{result.get("JOURNAL")}

                            )}

            );
        }
    }

    render() {
        //console.log("render", this.props.params.q);
        let button =
<Button type="submit" bsStyle="primary">Search</Button><Button type="reset" bsStyle="link">Clear</Button>
;
        let resultheader =
{this.props.different} unique RS numbers in {this.props.total} results for P < 5x10-8
;
        let examples =
Examples: <Link to="/search/diabetes">diabetes</Link>, <Link to="/search/rs3820706">rs3820706</Link>, <Link to="/search/Chung S">Chung S</Link>, <Link to="/search/2q23.3">2q23.3</Link>, <Link to="/search/CACNB4">CACNB4</Link>
;
        return (

                <form onSubmit={this.onSearch} onReset={this.onClear} style={{width: "600px", margin: "0 auto", backgroundColor: "white"}}>

Search HUNT fast-track GWAS catalog

                    <Input
                        type="text"
                        ref="query"
                        placeholder={this.props.params.q || "Search"}
                        help={examples}
                        buttonAfter={button}
                    />
                </form>
                {resultheader}
                {this.renderResults()}

                <Grid>
                    <Row>
                        <Col xs={12}>

                            The usual warnings about providing the service AS-IS applies.

                            <ExternalLink href="http://www.ntnu.no/ism/epicenter/home">Human genetic epidemiology group (HGE)</ExternalLink>, <ExternalLink href="http://www.ntnu.edu/ism">Department of public health and general practice (ISM)</ExternalLink>, <ExternalLink href="http://www.ntnu.edu/">Norwegian university of science and technology (NTNU)</ExternalLink>
                        </Col>
                    </Row>
                </Grid>

        );
    }
}

export default connectToStores(App);
<commit_msg>Link to data download at EBI.<commit_after>import React from "react";
import connectToStores from "alt/utils/connectToStores";
import GwasActions from "../actions/GwasActions";
import GwasStore from "../stores/GwasStore";
import {Input, Button, Table, Alert, Grid, Row, Col} from "react-bootstrap";
import {LinkContainer} from "react-router-bootstrap";
import {Link, History} from "react-router";

const ExternalLink = (props => {
    if (props.children) {
        return {props.children};
    }
    else {
        return ;
    }
});

class App extends React.Component {

    constructor(props) {
        super(props);
        this.onSearch = this.onSearch.bind(this);
        this.onClear = this.onClear.bind(this);
    }

    static getStores(props) {
        return [GwasStore];
    }

    static getPropsFromStores(props) {
        return {
            results: GwasStore.getResults(),
            traits: GwasStore.getTraits(),
            different: GwasStore.getDifferent(),
            total: GwasStore.getTotal()
        };
    }

    componentDidUpdate(prevProps) {
        let oldQ = prevProps.params.q;
        let newQ = this.props.params.q;
        if (newQ !== oldQ) {
            GwasActions.search(this.props.params.q);
        }
    }

    onLinkClick(value, e) {
        GwasActions.search(value);
    }

    onSearch(e) {
        e.preventDefault();
        this.props.history.pushState(null, `/search/${this.refs.query.getValue()}`)
        GwasActions.search(this.refs.query.getValue());
    }

    onClear(e) {
        this.props.history.pushState(null, `/search/`)
        GwasActions.search('');
    }

    rowclass(p) {
        if (p > 0.00000005) {
            return "uninteresting";
        }
    }
    exp(number) {
        if (number && !isNaN(number)) {
            return number.toExponential();
        }
    }
    getYear(datestring) {
        return datestring.split("-").pop();
    }
    renderResults() {
        if (!this.props.params.q) {
            return (
                <Grid>
                    <Row>
                        <Col xs={12}>

                            Use the search field or select from the traits below if you want to see some results

                            {this.props.traits.map(trait =>

                                                       <Link to={`/search/${trait.get("_id")}`}>{trait.get("_id")}</Link> <ExternalLink href={trait.get("uri")} />

                                                   )}

                        </Col>
                    </Row>
                </Grid>
            );
        }
        else if (this.props.params.q && this.props.params.q.length < 3) {
            return <Alert style={{width: "600px", margin: "0 auto"}} bsStyle="danger">We need at least three characters, or we will crash your browser</Alert>;
        }
        else {
            let exportButton = <Button href={`/search/${this.props.params.q}.csv`} style={{float: "right", marginTop: -37, marginRight: 5}}>Download</Button>;
            return (

                    {exportButton}

                                SNP
                                MAF
                                P
                                Position
                                Mapped gene
                                Mapped trait
                                OR or Beta
                                Year
                                First author
                                Pubmed

                            {this.props.results.map(result =>

                                        <Link to={`/search/${result.get("SNP_ID_CURRENT")}`}>
                                            {result.get("SNPS")}
                                        </Link>

                                    {result.get("hunt")}

                                        {this.exp(result.get("P-VALUE")) || "0.0" }

                                        {result.get("P-VALUE (TEXT)")}

                                        <Link to={`/search/${result.get("REGION")}`}>
                                            {result.get("REGION")}
                                        </Link>

                                        <Link to={result.get("CHR_ID") ? `/search/chr${result.get("CHR_ID")}:${result.get("CHR_POS")}` : ""}>
                                            {result.get("CHR_ID") ? `chr${result.get("CHR_ID")}:${result.get("CHR_POS")}` : ""}
                                        </Link>

                                        {result.get("CONTEXT")}

                                        <Link to={`/search/${result.get("MAPPED_GENE")}`}>
                                            {result.get("MAPPED_GENE")}
                                        </Link> <ExternalLink href={`http://www.genecards.org/cgi-bin/carddisp.pl?gene=${result.get("MAPPED_GENE")}`} />

                                    {result.get("MAPPED_TRAIT").split(", ").map(trait =>

                                            <Link to={`/search/${trait}`}>
                                                {trait}
                                            </Link>

                                    )}

{result.get("OR or BETA")}

{result.get("95% CI (TEXT)")}

{this.getYear(result.get("DATE"))}

{result.get("DATE ADDED TO CATALOG")}

                                    <Link to={`/search/${result.get("FIRST AUTHOR")}`}>
                                        {result.get("FIRST AUTHOR")}
                                    </Link>

                                    <Link to={`/search/${result.get("PUBMEDID")}`}>
                                        {result.get("PUBMEDID")}
                                    </Link> <ExternalLink href={`http://www.ncbi.nlm.nih.gov/pubmed/${result.get("PUBMEDID")}`} />

{result.get("JOURNAL")}

                            )}

            );
        }
    }

    render() {
        //console.log("render", this.props.params.q);
        let button =
<Button type="submit" bsStyle="primary">Search</Button><Button type="reset" bsStyle="link">Clear</Button>
;
        let resultheader =
{this.props.different} unique RS numbers in {this.props.total} results for P < 5x10-8
;
        let examples =
Examples: <Link to="/search/diabetes">diabetes</Link>, <Link to="/search/rs3820706">rs3820706</Link>, <Link to="/search/Chung S">Chung S</Link>, <Link to="/search/2q23.3">2q23.3</Link>, <Link to="/search/CACNB4">CACNB4</Link>
;
        return (

                <form onSubmit={this.onSearch} onReset={this.onClear} style={{width: "600px", margin: "0 auto", backgroundColor: "white"}}>

Search HUNT fast-track GWAS catalog

                    <Input
                        type="text"
                        ref="query"
                        placeholder={this.props.params.q || "Search"}
                        help={examples}
                        buttonAfter={button}
                    />
                </form>
                {resultheader}
                {this.renderResults()}

                <Grid>
                    <Row>
                        <Col xs={12}>

                            The usual warnings about providing the service AS-IS applies.

                            GWAS data from <ExternalLink href="https://www.ebi.ac.uk/gwas/docs/downloads">NHGRI-EBI</ExternalLink>

                            <ExternalLink href="http://www.ntnu.no/ism/epicenter/home">Human genetic epidemiology group (HGE)</ExternalLink>, <ExternalLink href="http://www.ntnu.edu/ism">Department of public health and general practice (ISM)</ExternalLink>, <ExternalLink href="http://www.ntnu.edu/">Norwegian university of science and technology (NTNU)</ExternalLink>
                        </Col>
                    </Row>
                </Grid>

        );
    }
}

export default connectToStores(App);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { GoogleMapLoader, GoogleMap } from 'react-google-maps'

class Map extends Component {

  render(){
    const mapContainer =

    return(

      <GoogleMapLoader
        containerElement={ mapContainer }
        googleMapElement={
          <GoogleMap

            defaultZoom={15}
            defaultCenter={this.props.center}
            options={{streetViewControl: false, mapTypeControl: false}}>

          </GoogleMap>
        }
      />

Estou montando o mapa

    );
  }
}
export default Map<commit_msg>Add map component<commit_after>import React, { Component } from 'react';
import { GoogleMapLoader, GoogleMap, Marker } from 'react-google-maps'

class Map extends Component {

  render(){
    const { lat, lng } = this.props;
    return(

        <GoogleMapLoader
          containerElement={
 }
          googleMapElement={
              <GoogleMap defaultZoom={15} defaultCenter={{ lat, lng }} >
                 <Marker position={{ lat, lng }} />
              </GoogleMap>
            }
        />

Estou montando o mapa

    );
  }
}
export default Map<|endoftext|>


<commit_before>/*global describe, it*/
describe('unexpected', function () {
    describe('ok/truthy/falsy assertion', function () {
        it('assert that the value is truthy or not', function () {
            expect(1, 'to be ok');
            expect(true, 'to be ok');
            expect(true, 'to not be falsy');
            expect({}, 'to be truthy');
            expect(0, 'to not be ok');
            expect(0, 'to be falsy');
            expect(null, 'to be falsy');
            expect(undefined, 'to be falsy');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be ok');
            }, 'to throw exception', 'expected 0 to be ok');
        });

        it('throws with message when the assertion fails', function () {
            expect(function () {
                expect(4 < 4, 'to be ok', '4 < 4');
            }, "to throw exception", "expected false to be ok '4 < 4'");
        });
    });

    describe('be assertion', function () {
        it('assert === equality', function () {
            var obj = {};
            expect(obj, 'to be', obj);
            expect(obj, 'to not be', {});
            expect(1, 'to be', 1);
            expect(NaN, 'to not be', NaN);
            expect(1, 'to not be', true);
            expect('1', 'to not be', 1);
            expect(null, 'to not be', undefined);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect('foo', 'to be', 'bar');
            }, 'to throw exception', "expected 'foo' to be 'bar'");
        });
    });

    describe('a/an assertion', function () {
        it('asserts typeof with support for array type and instanceof', function () {
            expect(5, 'to be a', 'number');
            expect([], 'to be an', 'array');
            expect([], 'to be an', 'object');
            expect([], 'to be an', Array);
            expect(null, 'to not be an', 'object');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(5, 'to be a', Array);
            }, 'to throw exception', 'expected 5 to be a [Function: Array]');
        });
    });

    describe('equal assertion', function () {
        it('asserts loose equality that works with objects', function () {
            expect({ a: 'b' }, 'to equal', { a: 'b' });
            expect(1, 'to equal', '1');
            expect(null, 'to not equal', '1');
            var now = new Date();
            expect(now, 'to equal', now);
            expect(now, 'to equal', new Date(now.getTime()));
            expect({ now: now }, 'to equal', { now: now });
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect({ a: 'b' }, 'to not equal', { a: 'b' });
            }, 'to throw exception', "expected { a: 'b' } to not equal { a: 'b' }");
        });
    });

    describe('exception assertion', function () {
        it('fails if no exception is thrown', function () {
            expect(function () {
                expect(function () {
                    // Don't throw
                }, 'to throw exception');
            }, 'to throw exception', 'expected [Function] to throw exception');
        });

        it('fails if the argument is not a function', function () {
            expect(function () {
                expect(1, 'to throw exception');
            }, 'to throw exception', "Assertion 'to throw exception' only supports functions");
        });

        it('given a function the function is called with the exception', function () {
            expect(function () {
                throw new SyntaxError();
            }, 'to throw exception', function (e) {
                expect(e, 'to be a', SyntaxError);
            });
        });

        it('matches the message against the given regular expression', function () {
            expect(function () {
                throw new Error('matches the exception message');
            }, 'to throw exception', /matches the exception message/);
            expect(function () {
                throw new Error('Other error');
            }, 'to not throw exception', /matches the exception message/);
        });

        it('exactly matches the message against the given string', function () {
            expect(function () {
                throw new Error('matches the exception message');
            }, 'to throw exception', 'matches the exception message');
            expect(function () {
                throw new Error('matches the exception message');
            }, 'to not throw exception', 'the exception message');
        });
    });

    describe('match assertion', function () {
        it('tests that the subject matches the given regular expression', function () {
            expect('test', 'to match', /.*st/);
            expect('test', 'to not match', /foo/);
            expect(null, 'to not match', /foo/);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect('test', 'to match', /foo/);
            }, 'to throw exception', "expected 'test' to match /foo/");
        });
    });

    describe('contain assertion', function () {
        it('asserts indexOf for an array or string', function () {
            expect([1, 2], 'to contain', 1);
            expect('hello world', 'to contain', 'world');
            expect(null, 'to not contain', 'world');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect('hello world', 'to contain', 'foo');
            }, 'to throw exception', "expected 'hello world' to contain 'foo'");
        });
    });

    describe('length assertion', function () {
        it('asserts array .length', function () {
            expect([], 'to have length', 0);
            expect([1,2,3], 'to have length', 3);
            expect([1,2,3], 'to not have length', 4);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(null, 'to have length', 4);
            }, 'to throw exception', "expected null to have length 4");

            expect(function () {
                expect({ length: 'foo' }, 'to have length', 4);
            }, 'to throw exception', "expected { length: 'foo' } to have length 4");
        });
    });

    describe('property assertion', function () {
        it('asserts presence of an own property (and value optionally)', function () {
            expect([1, 2], 'to have property', 'length');
            expect([1, 2], 'to have property', 'length', 2);
            expect({a: 'b'}, 'to have property', 'a');
            expect({a: 'b'}, 'to have property', 'a', 'b');
            expect({a: 'b'}, 'to have property', 'toString');
            expect({a: 'b'}, 'to have own property', 'a');
            expect(Object.create({a: 'b'}), 'to not have own property', 'a');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect({a: 'b'}, 'to have property', 'b');
            }, 'to throw exception', "expected { a: 'b' } to have property 'b'");

            expect(function () {
                expect(null, 'to have property', 'b');
            }, 'to throw exception', "expected null to have property 'b'");
        });
    });

    describe('empty assertion', function () {
        it('asserts presence of an own property (and value optionally)', function () {
            expect([], 'to be empty');
            expect('', 'to be empty');
            expect({}, 'to be empty');
            expect({ length: 0, duck: 'typing' }, 'to be empty');
            expect({ my: 'object' }, 'to not be empty');
            expect([1,2,3], 'to not be empty');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect([1,2,3], 'to be empty');
            }, 'to throw exception', "expected [ 1, 2, 3 ] to be empty");

            expect(function () {
                expect(null, 'to be empty');
            }, 'to throw exception', "Assertion 'to be empty' only supports strings, arrays and objects");
        });
    });

    describe('key assertion', function () {
        it('asserts the presence of a key', function () {
            expect(null, 'to not have key', 'a');
            expect({ a: 'b' }, 'to have key', 'a');
            expect({ a: 'b' }, 'to not have key', 'b');
            expect({ a: 'b', c: 'd' }, 'to not only have key', 'a');
            expect({ a: 'b', c: 'd' }, 'to only have keys', 'a', 'c');
            expect({ a: 'b', c: 'd' }, 'to only have keys', ['a', 'c']);
            expect({ a: 'b', c: 'd', e: 'f' }, 'to not only have keys', ['a', 'c']);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect({ a: 'b', b: 'c' }, 'to not have key', 'b');
            }, 'to throw exception', "expected { a: 'b', b: 'c' } to not have key 'b'");
        });
    });

    describe('within assertion', function () {
        it('asserts a number within a range', function () {
            expect(0, 'to be within', 0, 4);
            expect(1, 'to be within', 0, 4);
            expect(4, 'to be within', 0, 4);
            expect(-1, 'to not be within', 0, 4);
            expect(5, 'to not be within', 0, 4);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(4, 'to not be within', 0, 4);
            }, 'to throw exception', "expected 4 to not be within '0..4'");
            expect(function () {
                expect(null, 'to not be within', 0, 4);
            }, 'to throw exception', "expected null to not be within '0..4'");
        });
    });

    describe('less than assertion', function () {
        it('asserts <', function () {
            expect(0, 'to be less than', 4);
            expect(0, 'to be below', 1);
            expect(3, 'to be <', 4);
            expect(3, '<', 4);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be less than', 0);
            }, 'to throw exception', "expected 0 to be less than 0");
        });
    });

    describe('less than or equals assertion', function () {
        it('asserts <=', function () {
            expect(0, 'to be less than or equals to', 4);
            expect(4, 'to be <=', 4);
            expect(3, '<=', 4);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be less than or equals to', -1);
            }, 'to throw exception', "expected 0 to be less than or equals to -1");
        });
    });

    describe('greater than assertion', function () {
        it('assert >', function () {
            expect(3, 'to be greater than', 2);
            expect(1, 'to be above', 0);
            expect(4, 'to be >', 3);
            expect(4, '>', 3);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be greater than', 0);
            }, 'to throw exception', "expected 0 to be greater than 0");
        });
    });

    describe('greater than or equals assertion', function () {
        it('assert >=', function () {
            expect(3, 'to be greater than or equals to', 2);
            expect(3, 'to be >=', 3);
            expect(3, '>=', 3);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(-1, 'to be greater than or equals to', 0);
            }, 'to throw exception', "expected -1 to be greater than or equals to 0");
        });
    });

    describe('positive assertion', function () {
        it('assert that a number is positive', function () {
            expect(3, 'to be positive');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be positive');
            }, 'to throw exception', "expected 0 to be positive");
        });
    });

    describe('negative assertion', function () {
        it('assert that a number is negative', function () {
            expect(-1, 'to be negative');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be negative');
            }, 'to throw exception', "expected 0 to be negative");
        });
    });

    describe('fail assertion', function () {
        it('throws an error', function () {
            expect(function () {
                expect.fail();
            }, 'to throw exception', "explicit failure");
        });

        it('throws an error with a given message', function () {
            expect(function () {
                expect.fail('fail with error message');
            }, 'to throw exception', "fail with error message");
        });

        it('supports placeholders', function () {
            expect(function () {
                expect.fail('{0} was expected to be {1}', 0, 'zero');
            }, 'to throw exception', "0 was expected to be 'zero'");

            expect(function () {
                expect.fail('{0} was expected to be {1}', 0);
            }, 'to throw exception', "0 was expected to be {1}");
        });

        it('throws if the assertion does not exists', function () {
            expect(function () {
                expect(1, "foo bar", 2);
            }, 'to throw exception', 'Unknown assertion "foo bar"');
        });
    });

});
<commit_msg>Getting rid of Object.create<commit_after>/*global describe, it, expect*/

// use this instead of Object.create in order to make the tests run in
// es5 compatible browsers
function create(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

describe('unexpected', function () {
    describe('ok/truthy/falsy assertion', function () {
        it('assert that the value is truthy or not', function () {
            expect(1, 'to be ok');
            expect(true, 'to be ok');
            expect(true, 'to not be falsy');
            expect({}, 'to be truthy');
            expect(0, 'to not be ok');
            expect(0, 'to be falsy');
            expect(null, 'to be falsy');
            expect(undefined, 'to be falsy');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be ok');
            }, 'to throw exception', 'expected 0 to be ok');
        });

        it('throws with message when the assertion fails', function () {
            expect(function () {
                expect(4 < 4, 'to be ok', '4 < 4');
            }, "to throw exception", "expected false to be ok '4 < 4'");
        });
    });

    describe('be assertion', function () {
        it('assert === equality', function () {
            var obj = {};
            expect(obj, 'to be', obj);
            expect(obj, 'to not be', {});
            expect(1, 'to be', 1);
            expect(NaN, 'to not be', NaN);
            expect(1, 'to not be', true);
            expect('1', 'to not be', 1);
            expect(null, 'to not be', undefined);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect('foo', 'to be', 'bar');
            }, 'to throw exception', "expected 'foo' to be 'bar'");
        });
    });

    describe('a/an assertion', function () {
        it('asserts typeof with support for array type and instanceof', function () {
            expect(5, 'to be a', 'number');
            expect([], 'to be an', 'array');
            expect([], 'to be an', 'object');
            expect([], 'to be an', Array);
            expect(null, 'to not be an', 'object');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(5, 'to be a', Array);
            }, 'to throw exception', 'expected 5 to be a [Function: Array]');
        });
    });

    describe('equal assertion', function () {
        it('asserts loose equality that works with objects', function () {
            expect({ a: 'b' }, 'to equal', { a: 'b' });
            expect(1, 'to equal', '1');
            expect(null, 'to not equal', '1');
            var now = new Date();
            expect(now, 'to equal', now);
            expect(now, 'to equal', new Date(now.getTime()));
            expect({ now: now }, 'to equal', { now: now });
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect({ a: 'b' }, 'to not equal', { a: 'b' });
            }, 'to throw exception', "expected { a: 'b' } to not equal { a: 'b' }");
        });
    });

    describe('exception assertion', function () {
        it('fails if no exception is thrown', function () {
            expect(function () {
                expect(function () {
                    // Don't throw
                }, 'to throw exception');
            }, 'to throw exception', 'expected [Function] to throw exception');
        });

        it('fails if the argument is not a function', function () {
            expect(function () {
                expect(1, 'to throw exception');
            }, 'to throw exception', "Assertion 'to throw exception' only supports functions");
        });

        it('given a function the function is called with the exception', function () {
            expect(function () {
                throw new SyntaxError();
            }, 'to throw exception', function (e) {
                expect(e, 'to be a', SyntaxError);
            });
        });

        it('matches the message against the given regular expression', function () {
            expect(function () {
                throw new Error('matches the exception message');
            }, 'to throw exception', /matches the exception message/);
            expect(function () {
                throw new Error('Other error');
            }, 'to not throw exception', /matches the exception message/);
        });

        it('exactly matches the message against the given string', function () {
            expect(function () {
                throw new Error('matches the exception message');
            }, 'to throw exception', 'matches the exception message');
            expect(function () {
                throw new Error('matches the exception message');
            }, 'to not throw exception', 'the exception message');
        });
    });

    describe('match assertion', function () {
        it('tests that the subject matches the given regular expression', function () {
            expect('test', 'to match', /.*st/);
            expect('test', 'to not match', /foo/);
            expect(null, 'to not match', /foo/);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect('test', 'to match', /foo/);
            }, 'to throw exception', "expected 'test' to match /foo/");
        });
    });

    describe('contain assertion', function () {
        it('asserts indexOf for an array or string', function () {
            expect([1, 2], 'to contain', 1);
            expect('hello world', 'to contain', 'world');
            expect(null, 'to not contain', 'world');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect('hello world', 'to contain', 'foo');
            }, 'to throw exception', "expected 'hello world' to contain 'foo'");
        });
    });

    describe('length assertion', function () {
        it('asserts array .length', function () {
            expect([], 'to have length', 0);
            expect([1,2,3], 'to have length', 3);
            expect([1,2,3], 'to not have length', 4);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(null, 'to have length', 4);
            }, 'to throw exception', "expected null to have length 4");

            expect(function () {
                expect({ length: 'foo' }, 'to have length', 4);
            }, 'to throw exception', "expected { length: 'foo' } to have length 4");
        });
    });

    describe('property assertion', function () {
        it('asserts presence of an own property (and value optionally)', function () {
            expect([1, 2], 'to have property', 'length');
            expect([1, 2], 'to have property', 'length', 2);
            expect({a: 'b'}, 'to have property', 'a');
            expect({a: 'b'}, 'to have property', 'a', 'b');
            expect({a: 'b'}, 'to have property', 'toString');
            expect({a: 'b'}, 'to have own property', 'a');
            expect(create({a: 'b'}), 'to not have own property', 'a');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect({a: 'b'}, 'to have property', 'b');
            }, 'to throw exception', "expected { a: 'b' } to have property 'b'");

            expect(function () {
                expect(null, 'to have property', 'b');
            }, 'to throw exception', "expected null to have property 'b'");
        });
    });

    describe('empty assertion', function () {
        it('asserts presence of an own property (and value optionally)', function () {
            expect([], 'to be empty');
            expect('', 'to be empty');
            expect({}, 'to be empty');
            expect({ length: 0, duck: 'typing' }, 'to be empty');
            expect({ my: 'object' }, 'to not be empty');
            expect([1,2,3], 'to not be empty');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect([1,2,3], 'to be empty');
            }, 'to throw exception', "expected [ 1, 2, 3 ] to be empty");

            expect(function () {
                expect(null, 'to be empty');
            }, 'to throw exception', "Assertion 'to be empty' only supports strings, arrays and objects");
        });
    });

    describe('key assertion', function () {
        it('asserts the presence of a key', function () {
            expect(null, 'to not have key', 'a');
            expect({ a: 'b' }, 'to have key', 'a');
            expect({ a: 'b' }, 'to not have key', 'b');
            expect({ a: 'b', c: 'd' }, 'to not only have key', 'a');
            expect({ a: 'b', c: 'd' }, 'to only have keys', 'a', 'c');
            expect({ a: 'b', c: 'd' }, 'to only have keys', ['a', 'c']);
            expect({ a: 'b', c: 'd', e: 'f' }, 'to not only have keys', ['a', 'c']);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect({ a: 'b', b: 'c' }, 'to not have key', 'b');
            }, 'to throw exception', "expected { a: 'b', b: 'c' } to not have key 'b'");
        });
    });

    describe('within assertion', function () {
        it('asserts a number within a range', function () {
            expect(0, 'to be within', 0, 4);
            expect(1, 'to be within', 0, 4);
            expect(4, 'to be within', 0, 4);
            expect(-1, 'to not be within', 0, 4);
            expect(5, 'to not be within', 0, 4);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(4, 'to not be within', 0, 4);
            }, 'to throw exception', "expected 4 to not be within '0..4'");
            expect(function () {
                expect(null, 'to not be within', 0, 4);
            }, 'to throw exception', "expected null to not be within '0..4'");
        });
    });

    describe('less than assertion', function () {
        it('asserts <', function () {
            expect(0, 'to be less than', 4);
            expect(0, 'to be below', 1);
            expect(3, 'to be <', 4);
            expect(3, '<', 4);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be less than', 0);
            }, 'to throw exception', "expected 0 to be less than 0");
        });
    });

    describe('less than or equals assertion', function () {
        it('asserts <=', function () {
            expect(0, 'to be less than or equals to', 4);
            expect(4, 'to be <=', 4);
            expect(3, '<=', 4);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be less than or equals to', -1);
            }, 'to throw exception', "expected 0 to be less than or equals to -1");
        });
    });

    describe('greater than assertion', function () {
        it('assert >', function () {
            expect(3, 'to be greater than', 2);
            expect(1, 'to be above', 0);
            expect(4, 'to be >', 3);
            expect(4, '>', 3);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be greater than', 0);
            }, 'to throw exception', "expected 0 to be greater than 0");
        });
    });

    describe('greater than or equals assertion', function () {
        it('assert >=', function () {
            expect(3, 'to be greater than or equals to', 2);
            expect(3, 'to be >=', 3);
            expect(3, '>=', 3);
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(-1, 'to be greater than or equals to', 0);
            }, 'to throw exception', "expected -1 to be greater than or equals to 0");
        });
    });

    describe('positive assertion', function () {
        it('assert that a number is positive', function () {
            expect(3, 'to be positive');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be positive');
            }, 'to throw exception', "expected 0 to be positive");
        });
    });

    describe('negative assertion', function () {
        it('assert that a number is negative', function () {
            expect(-1, 'to be negative');
        });

        it('throws when the assertion fails', function () {
            expect(function () {
                expect(0, 'to be negative');
            }, 'to throw exception', "expected 0 to be negative");
        });
    });

    describe('fail assertion', function () {
        it('throws an error', function () {
            expect(function () {
                expect.fail();
            }, 'to throw exception', "explicit failure");
        });

        it('throws an error with a given message', function () {
            expect(function () {
                expect.fail('fail with error message');
            }, 'to throw exception', "fail with error message");
        });

        it('supports placeholders', function () {
            expect(function () {
                expect.fail('{0} was expected to be {1}', 0, 'zero');
            }, 'to throw exception', "0 was expected to be 'zero'");

            expect(function () {
                expect.fail('{0} was expected to be {1}', 0);
            }, 'to throw exception', "0 was expected to be {1}");
        });

        it('throws if the assertion does not exists', function () {
            expect(function () {
                expect(1, "foo bar", 2);
            }, 'to throw exception', 'Unknown assertion "foo bar"');
        });
    });

});
<|endoftext|>