<commit_before>
var expect = require('chai').expect,
  minimodel = require('../lib');

describe('set/get/cast', function() {
  var Post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      id: String,
      title: {
        type: String
      },
      nested: {
        type: {
          type: String
        },
        hello: String
      },
      nested2: {
        me: String,
        hello: String
      },
      asField: minimodel.Types.String
    });
  });

  it('should set/get a property from constructor', function() {
    var post = new Post({id: "blah"});
    expect(post.get('id')).to.be.equal('blah');
  });

  it('should set a property', function() {
    var post = new Post();
    post.set('id', "blah");
    expect(post.get('id')).to.be.equal('blah');
  });

  it('should cast a value to its actual type (generic test)', function() {
    var post = new Post({id: {}});
    expect(post.get('id')).to.be.equal('[object Object]');
  });

  it('should support nested properties', function() {
    var post = new Post({id: "blah", nested2: {me: "test", hello: "world"}});
    expect(post.get('nested2.me')).to.be.equal('test');
    expect(post.get('nested2.hello')).to.be.equal('world');
  });

  it('should support nested "type" property', function() {
    var post = new Post({id: "blah", nested: {type: "test", hello: "world"}});
    expect(post.get('nested.type')).to.be.equal('test');
    expect(post.get('nested.hello')).to.be.equal('world');
  });

  it('should retrieve entire nested objects', function() {
    var post = new Post({nested: {type: "test"}});
    expect(post.get('nested')).to.have.property('type', 'test');
  });

  it('should not set properties not in schema', function() {
    var post = new Post({id: "blah", type: "test"});
    expect(post.get('type')).to.not.exist;
  });

  it('should support Model/Fields as types', function() {
    var post = new Post({asField: 1});
    expect(post.get('asField')).to.be.equal('1');
  });
});

describe('handling wrong descriptors', function() {
  it('should throw exception for empty object', function() {
    expect(function() {
      minimodel.Model.extend({
        id: {}
      });
    }).to.throw(/Invalid field/);
  });

  it('should throw exception for undefined', function() {
    expect(function() {
      minimodel.Model.extend({
        id: undefined
      });
    }).to.throw(/Invalid field/);
  });

  it('should throw exception for undefined type', function() {
    expect(function() {
      minimodel.Model.extend({
        id: {
          type: undefined
        }
      });
    }).to.throw(/Invalid field/);
  });

  it('should throw exception for nested empty types', function() {
    expect(function() {
      minimodel.Model.extend({
        id: {
          type: {
            type: {
              type: {}
            }
          }
        }
      });
    }).to.throw(/Invalid field/);
  });
});

describe('field getters/setters', function() {

  it('should use the field getter to retrieve field value', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        get: function() {
          return this.getRaw() + "!"
        }
      }
    });

    var model = new TestModel();
    model.set('id', "ok");
    expect(model.get('id')).to.be.equal('ok!');
  });

  it('should use the field setter to set field value', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        set: function(val) {
          return this.setRaw(val + "!");
        }
      }
    });

    var model = new TestModel();
    model.set('id', "ok");
    expect(model.get('id')).to.be.equal('ok!');
  });
});

describe('Virtuals', function() {
  it('should not have default getters and setters', function() {
    var TestModel = minimodel.Model.extend({
      field: {
        type: minimodel.Types.Virtual
      }
    });

    var model = new TestModel();
    model.set('field', "ok");
    expect(model.get('field')).to.not.exist;
  });

  it('getters/setters should be able to access main model', function() {
    var TestModel = minimodel.Model.extend({
      full: {
        type: minimodel.Types.Virtual,
        get: function() {
          return this.model.get('name') + " " + this.model.get('surname');
        }
      },
      nested: {
        prop: {
          type: minimodel.Types.Virtual,
          get: function() {
            return this.model.get('name') + " " + this.model.get('surname');
          }
        }
      },
      name: String,
      surname: String
    });

    var model = new TestModel({name: "John", surname: "Doe"});
    expect(model.get('full')).to.be.equal('John Doe');
    expect(model.get('nested.prop')).to.be.equal('John Doe');
  });

  it('should not be exported', function() {
    var TestModel = minimodel.Model.extend({
      field: {
        type: minimodel.Types.Virtual,
        get: function() {
          return "ok";
        }
      }
    });

    var model = new TestModel();
    expect(model.toObject()).to.be.empty;
  });
});

describe('access using properties', function() {
  var Post, post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      title: {
        type: String
      },
      nested: {
        type: {
          type: String
        }
      },
    });
    post = new Post({title: "blah", nested: {type: "test"}});
  });

  it('should get the value using property accessor', function() {
    expect(post.title).to.be.equal('blah');
  });

  it('should set the value using property accessor', function() {
    post.title = 'blah+';
    expect(post.title).to.be.equal('blah+');
  });

  it('should get the value of nested fields using property accessor', function() {
    expect(post.nested.type).to.be.equal('test');
  });

  it('should set the value of nested fields using property accessor', function() {
    post.nested.type = 'test+';
    expect(post.nested.type).to.be.equal('test+');
  });

  it('should set entire nested objects', function() {
    post.nested = {type: 'test+'};
    expect(post.nested.type).to.be.equal('test+');
  });
});

describe('defaults', function() {
  var Post, post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      title: {
        type: String
      },
      nested: {
        type: {
          type: String,
          default: "ahahah"
        }
      },
      aField: {
        type: String,
        default: "mmm"
      },
      anotherField: {
        type: String,
        default: "mmm"
      }
    });
    post = new Post({title: "blah", anotherField: "wha"});
  });

  it('should set default value if not specified in constructor', function() {
    expect(post.aField).to.be.equal('mmm');
    expect(post.nested.type).to.be.equal('ahahah');
  });

  it('should not set default value if it is specified in constructor', function() {
    expect(post.title).to.be.equal('blah');
    expect(post.anotherField).to.be.equal('wha');
  });
});

describe('Date field', function() {
  var Post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      date: Date
    });
  });

  it('should set date from string', function() {
    var post = new Post({date: "1382354005"});
    expect(post.date).to.be.instanceof(Date);
    expect(post.date.toString()).to.be.equal("Fri Jan 16 1970 23:59:14 GMT+0000 (GMT)");
  });

  it('should set date from number', function() {
    var post = new Post({date: 1382354005});
    expect(post.date).to.be.instanceof(Date);
    expect(post.date.toString()).to.be.equal("Fri Jan 16 1970 23:59:14 GMT+0000 (GMT)");
  });
});

describe('Number field', function() {
  var Post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      nr: Number
    });
  });

  it('should set number from string', function() {
    var post = new Post({nr: "7"});
    expect(typeof post.nr === 'number');
    expect(post.nr).to.be.equal(7);
  });

  it('should set number from number', function() {
    var post = new Post({nr: 7});
    expect(typeof post.nr === 'number');
    expect(post.nr).to.be.equal(7);
  });
});

describe('Validators', function() {
  it('should not validate if empty value and required is set', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        required: true
      }
    });

    var model = new TestModel({});
    expect(model.id).to.not.exist;
    expect(model.validate()).to.be.instanceof(minimodel.Errors.ModelValidationError);
    expect(model.validate()).to.have.deep.property("errors.id.type", "required");
  });

  it('should not validate if empty string and required is set', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        required: true
      }
    });

    var model = new TestModel({id: ""});
    expect(model.validate()).to.have.deep.property("errors.id.type", "required");
  });

  it('should not validate if date is not valid date', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: Date
      }
    });

    var model = new TestModel({id: "asdqweasd"});
    expect(model.validate()).to.have.deep.property("errors.id.type", "wrong_type");
  });

  it('should not validate if custom validation fail', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        validate: function() {
          if(this.value.length < 2) {
            return new Error("Custom validation failed");
          }
        }
      }
    });

    var model = new TestModel({id: "a"});
    expect(model.validate()).to.have.deep.property("errors.id");
  });
});

<commit_msg>Fix tests<commit_after>
var expect = require('chai').expect,
  minimodel = require('../lib');

describe('set/get/cast', function() {
  var Post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      id: String,
      title: {
        type: String
      },
      nested: {
        type: {
          type: String
        },
        hello: String
      },
      nested2: {
        me: String,
        hello: String
      },
      asField: minimodel.Types.String
    });
  });

  it('should set/get a property from constructor', function() {
    var post = new Post({id: "blah"});
    expect(post.get('id')).to.be.equal('blah');
  });

  it('should set a property', function() {
    var post = new Post();
    post.set('id', "blah");
    expect(post.get('id')).to.be.equal('blah');
  });

  it('should cast a value to its actual type (generic test)', function() {
    var post = new Post({id: {}});
    expect(post.get('id')).to.be.equal('[object Object]');
  });

  it('should support nested properties', function() {
    var post = new Post({id: "blah", nested2: {me: "test", hello: "world"}});
    expect(post.get('nested2.me')).to.be.equal('test');
    expect(post.get('nested2.hello')).to.be.equal('world');
  });

  it('should support nested "type" property', function() {
    var post = new Post({id: "blah", nested: {type: "test", hello: "world"}});
    expect(post.get('nested.type')).to.be.equal('test');
    expect(post.get('nested.hello')).to.be.equal('world');
  });

  it('should retrieve entire nested objects', function() {
    var post = new Post({nested: {type: "test"}});
    expect(post.get('nested')).to.have.property('type', 'test');
  });

  it('should not set properties not in schema', function() {
    var post = new Post({id: "blah", type: "test"});
    expect(post.get('type')).to.not.exist;
  });

  it('should support Model/Fields as types', function() {
    var post = new Post({asField: 1});
    expect(post.get('asField')).to.be.equal('1');
  });
});

describe('handling wrong descriptors', function() {
  it('should throw exception for empty object', function() {
    expect(function() {
      minimodel.Model.extend({
        id: {}
      });
    }).to.throw(/Invalid field/);
  });

  it('should throw exception for undefined', function() {
    expect(function() {
      minimodel.Model.extend({
        id: undefined
      });
    }).to.throw(/Invalid field/);
  });

  it('should throw exception for undefined type', function() {
    expect(function() {
      minimodel.Model.extend({
        id: {
          type: undefined
        }
      });
    }).to.throw(/Invalid field/);
  });

  it('should throw exception for nested empty types', function() {
    expect(function() {
      minimodel.Model.extend({
        id: {
          type: {
            type: {
              type: {}
            }
          }
        }
      });
    }).to.throw(/Invalid field/);
  });
});

describe('field getters/setters', function() {

  it('should use the field getter to retrieve field value', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        get: function() {
          return this.getRaw() + "!"
        }
      }
    });

    var model = new TestModel();
    model.set('id', "ok");
    expect(model.get('id')).to.be.equal('ok!');
  });

  it('should use the field setter to set field value', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        set: function(val) {
          return this.setRaw(val + "!");
        }
      }
    });

    var model = new TestModel();
    model.set('id', "ok");
    expect(model.get('id')).to.be.equal('ok!');
  });
});

describe('Virtuals', function() {
  it('should not have default getters and setters', function() {
    var TestModel = minimodel.Model.extend({
      field: {
        type: minimodel.Types.Virtual
      }
    });

    var model = new TestModel();
    model.set('field', "ok");
    expect(model.get('field')).to.not.exist;
  });

  it('getters/setters should be able to access main model', function() {
    var TestModel = minimodel.Model.extend({
      full: {
        type: minimodel.Types.Virtual,
        get: function() {
          return this.model.get('name') + " " + this.model.get('surname');
        }
      },
      nested: {
        prop: {
          type: minimodel.Types.Virtual,
          get: function() {
            return this.model.get('name') + " " + this.model.get('surname');
          }
        }
      },
      name: String,
      surname: String
    });

    var model = new TestModel({name: "John", surname: "Doe"});
    expect(model.get('full')).to.be.equal('John Doe');
    expect(model.get('nested.prop')).to.be.equal('John Doe');
  });

  it('should not be exported', function() {
    var TestModel = minimodel.Model.extend({
      field: {
        type: minimodel.Types.Virtual,
        get: function() {
          return "ok";
        }
      }
    });

    var model = new TestModel();
    expect(model.toObject()).to.be.empty;
  });
});

describe('access using properties', function() {
  var Post, post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      title: {
        type: String
      },
      nested: {
        type: {
          type: String
        }
      },
    });
    post = new Post({title: "blah", nested: {type: "test"}});
  });

  it('should get the value using property accessor', function() {
    expect(post.title).to.be.equal('blah');
  });

  it('should set the value using property accessor', function() {
    post.title = 'blah+';
    expect(post.title).to.be.equal('blah+');
  });

  it('should get the value of nested fields using property accessor', function() {
    expect(post.nested.type).to.be.equal('test');
  });

  it('should set the value of nested fields using property accessor', function() {
    post.nested.type = 'test+';
    expect(post.nested.type).to.be.equal('test+');
  });

  it('should set entire nested objects', function() {
    post.nested = {type: 'test+'};
    expect(post.nested.type).to.be.equal('test+');
  });
});

describe('defaults', function() {
  var Post, post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      title: {
        type: String
      },
      nested: {
        type: {
          type: String,
          default: "ahahah"
        }
      },
      aField: {
        type: String,
        default: "mmm"
      },
      anotherField: {
        type: String,
        default: "mmm"
      }
    });
    post = new Post({title: "blah", anotherField: "wha"});
  });

  it('should set default value if not specified in constructor', function() {
    expect(post.aField).to.be.equal('mmm');
    expect(post.nested.type).to.be.equal('ahahah');
  });

  it('should not set default value if it is specified in constructor', function() {
    expect(post.title).to.be.equal('blah');
    expect(post.anotherField).to.be.equal('wha');
  });
});

describe('Date field', function() {
  var Post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      date: Date
    });
  });

  it('should set date from string', function() {
    var post = new Post({date: "1382354005"});
    expect(post.date).to.be.instanceof(Date);
    expect(post.date.toString()).to.contain("Fri Jan 16 1970 23:59:14 GMT+0000");
  });

  it('should set date from number', function() {
    var post = new Post({date: 1382354005});
    expect(post.date).to.be.instanceof(Date);
    expect(post.date.toString()).to.contain("Fri Jan 16 1970 23:59:14 GMT+0000");
  });
});

describe('Number field', function() {
  var Post;

  beforeEach(function() {
    Post = minimodel.Model.extend({
      nr: Number
    });
  });

  it('should set number from string', function() {
    var post = new Post({nr: "7"});
    expect(typeof post.nr === 'number');
    expect(post.nr).to.be.equal(7);
  });

  it('should set number from number', function() {
    var post = new Post({nr: 7});
    expect(typeof post.nr === 'number');
    expect(post.nr).to.be.equal(7);
  });
});

describe('Validators', function() {
  it('should not validate if empty value and required is set', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        required: true
      }
    });

    var model = new TestModel({});
    expect(model.id).to.not.exist;
    expect(model.validate()).to.be.instanceof(minimodel.Errors.ModelValidationError);
    expect(model.validate()).to.have.deep.property("errors.id.type", "required");
  });

  it('should not validate if empty string and required is set', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        required: true
      }
    });

    var model = new TestModel({id: ""});
    expect(model.validate()).to.have.deep.property("errors.id.type", "required");
  });

  it('should not validate if date is not valid date', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: Date
      }
    });

    var model = new TestModel({id: "asdqweasd"});
    expect(model.validate()).to.have.deep.property("errors.id.type", "wrong_type");
  });

  it('should not validate if custom validation fail', function() {
    var TestModel = minimodel.Model.extend({
      id: {
        type: String,
        validate: function() {
          if(this.value.length < 2) {
            return new Error("Custom validation failed");
          }
        }
      }
    });

    var model = new TestModel({id: "a"});
    expect(model.validate()).to.have.deep.property("errors.id");
  });
});

<|endoftext|>


<commit_before>var expect = chai.expect

var prefix = 'WebkitAppearance' in document.documentElement.style ? '-webkit-' : ''
var testZooming = new Zooming()
var defaultOpts = Object.assign({}, testZooming.config())
var els = document.querySelectorAll(defaultOpts.defaultZoomable)
var el = els[0]
var i = els.length

describe('API', function() {

  describe('listen()', function() {
    it('should set cursor style to zoom-in', function() {
      while (i--) {
        var el = els[i]
        expect(el.style.cursor).to.equal(prefix + 'zoom-in')
      }
    })
  })

  describe('config()', function() {
    var opts = {
      defaultZoomable: 'img[data-action="open"]',
      enableGrab: false,
      preloadImage: false,
      transitionDuration: 0.2,
      transitionTimingFunction: 'ease',
      bgColor: '#000',
      bgOpacity: 0.8,
      scaleBase: 0.8,
      scaleExtra: 0.3,
      scrollThreshold: 50,
      onOpen: function() { return 'onOpen' },
      onClose: function() { return 'onClose' },
      onRelease: function() { return 'onRelease' },
      onBeforeOpen: function() { return 'onBeforeOpen' },
      onBeforeClose: function() { return 'onBeforeClose' },
      onBeforeGrab: function() { return 'onBeforeGrab' },
      onBeforeMove: function() { return 'onBeforeMove' },
      onBeforeRelease: function() { return 'onBeforeRelease' }
    }

    before(function() {
      testZooming.config(opts)
    })

    it('should update options correctly', function() {
      expect(testZooming.config()).to.deep.equal(opts)
    })

    after(function() {
      testZooming.config(defaultOpts)
    })
  })

  describe('config() new instance', function() {
    var testZooming2 = new Zooming({})

    testZooming2.config({
      defaultZoomable: 'img[data-action="zoom2"]',
      scrollThreshold: 250
    })

    it('should update options correctly', function() {
      expect(testZooming2.config().defaultZoomable).to.equal('img[data-action="zoom2"]')
      expect(testZooming2.config().scrollThreshold).to.equal(250)
      expect(testZooming2.config().enableGrab).to.equal(true)
    })
  })

  describe('open()', function() {
    it('should open up the image', function(done) {
      testZooming.open(el, function(target) {
        expect(target.style.position).to.equal('relative')
        expect(target.style.zIndex).to.equal('999')
        expect(target.style.cursor).to.equal(prefix + (defaultOpts.enableGrab ? 'grab': 'zoom-out'))
        expect(target.style.transition).to.not.be.empty
        expect(target.style.transform).to.not.be.empty
        done()
      })
    })

    it('should insert the overlay', function() {
      var style = testZooming.overlay.style
      expect(style.zIndex).to.equal('998')
      expect(style.backgroundColor).to.equal(defaultOpts.bgColor)
      expect(style.position).to.equal('fixed')
      expect(style.top).to.equal('0px')
      expect(style.left).to.equal('0px')
      expect(style.right).to.equal('0px')
      expect(style.bottom).to.equal('0px')
      expect(style.opacity).to.equal(defaultOpts.bgOpacity.toString())
      expect(style.transition).to.not.be.empty
    })
  })

  describe('grab()', function() {
    var x = window.innerWidth / 2
    var y = window.innerHeight / 2

    it('should grab the image', function(done) {
      testZooming.grab(x, y, defaultOpts.scaleExtra, function(target) {
        expect(target.style.cursor).to.equal('move')
        expect(target.style.transition).to.not.be.empty
        expect(target.style.transform).to.not.be.empty
        done()
      })
    })
  })

  describe('release()', function() {
    it('should release the image', function(done) {
      testZooming.release(function(target) {
        expect(target.style.position).to.equal('relative')
        expect(target.style.zIndex).to.equal('999')
        expect(target.style.cursor).to.equal(prefix + (defaultOpts.enableGrab ? 'grab': 'zoom-out'))
        expect(target.style.transition).to.not.be.empty
        expect(target.style.transform).to.not.be.empty
        done()
      })
    })
  })

  describe('close()', function() {
    it('should close out the image', function(done) {
      testZooming.close(function(target) {
        expect(target.style.position).to.be.empty
        expect(target.style.zIndex).to.be.empty
        expect(target.style.cursor).to.equal(prefix + 'zoom-in')
        expect(target.style.transition).to.be.empty
        expect(target.style.transform).to.be.empty
        done()
      })
    })

    it('should remove the overlay', function() {
      expect(el.parentNode.lastElementChild.tagName).to.equal('IMG')
    })
  })
})
<commit_msg>test refactor<commit_after>var expect = chai.expect
var prefix = 'WebkitAppearance' in document.documentElement.style ? '-webkit-' : ''

describe('API', function() {

  var testZooming = new Zooming()
  var defaultOpts = Object.assign({}, testZooming.config())
  var els = document.querySelectorAll(defaultOpts.defaultZoomable)
  var el = els[0]

  describe('listen()', function() {
    it('should set cursor style to zoom-in', function() {
      expect(el.style.cursor).to.equal(prefix + 'zoom-in')
    })
  })

  describe('config()', function() {
    var opts = {
      defaultZoomable: 'img[data-action="open"]',
      enableGrab: false,
      preloadImage: false,
      transitionDuration: 0.2,
      transitionTimingFunction: 'ease',
      bgColor: '#000',
      bgOpacity: 0.8,
      scaleBase: 0.8,
      scaleExtra: 0.3,
      scrollThreshold: 50,
      onOpen: function() { return 'onOpen' },
      onClose: function() { return 'onClose' },
      onRelease: function() { return 'onRelease' },
      onBeforeOpen: function() { return 'onBeforeOpen' },
      onBeforeClose: function() { return 'onBeforeClose' },
      onBeforeGrab: function() { return 'onBeforeGrab' },
      onBeforeMove: function() { return 'onBeforeMove' },
      onBeforeRelease: function() { return 'onBeforeRelease' }
    }

    before(function() {
      testZooming.config(opts)
    })

    it('should update options correctly', function() {
      expect(testZooming.config()).to.deep.equal(opts)
    })

    after(function() {
      testZooming.config(defaultOpts)
    })
  })

  describe('config() new instance', function() {
    var testZooming2 = new Zooming({})
    var defaultZoomable = 'img[data-action="zoom2"]'
    var scrollThreshold = 250
    var newOptions = {
      defaultZoomable: defaultZoomable,
      scrollThreshold: scrollThreshold
    }

    testZooming2.config(newOptions)

    it('should update options correctly', function() {
      var resultOptions = testZooming2.config()

      for (let key in resultOptions) {
        if (key in newOptions) {
          expect(resultOptions[key]).to.equal(newOptions[key])
        } else {
          expect(resultOptions[key]).to.equal(defaultOpts[key])
        }
      }
    })
  })

  describe('open()', function() {
    it('should open up the image', function(done) {
      testZooming.open(el, function(target) {
        expect(target.style.position).to.equal('relative')
        expect(target.style.zIndex).to.equal('999')
        expect(target.style.cursor).to.equal(prefix + (defaultOpts.enableGrab ? 'grab': 'zoom-out'))
        expect(target.style.transition).to.not.be.empty
        expect(target.style.transform).to.not.be.empty
        done()
      })
    })

    it('should insert the overlay', function() {
      var overlay = el.parentNode.lastElementChild
      expect(overlay.tagName).to.equal('DIV')
      var style = overlay.style
      expect(style.zIndex).to.equal('998')
      expect(style.backgroundColor).to.equal(defaultOpts.bgColor)
      expect(style.position).to.equal('fixed')
      expect(style.top).to.equal('0px')
      expect(style.left).to.equal('0px')
      expect(style.right).to.equal('0px')
      expect(style.bottom).to.equal('0px')
      expect(style.opacity).to.equal(defaultOpts.bgOpacity.toString())
      expect(style.transition).to.not.be.empty
    })
  })

  describe('grab()', function() {
    var x = window.innerWidth / 2
    var y = window.innerHeight / 2

    it('should grab the image', function(done) {
      testZooming.grab(x, y, defaultOpts.scaleExtra, function(target) {
        expect(target.style.cursor).to.equal('move')
        expect(target.style.transition).to.not.be.empty
        expect(target.style.transform).to.not.be.empty
        done()
      })
    })
  })

  describe('release()', function() {
    it('should release the image', function(done) {
      testZooming.release(function(target) {
        expect(target.style.position).to.equal('relative')
        expect(target.style.zIndex).to.equal('999')
        expect(target.style.cursor).to.equal(prefix + (defaultOpts.enableGrab ? 'grab': 'zoom-out'))
        expect(target.style.transition).to.not.be.empty
        expect(target.style.transform).to.not.be.empty
        done()
      })
    })
  })

  describe('close()', function() {
    it('should close out the image', function(done) {
      testZooming.close(function(target) {
        expect(target.style.position).to.be.empty
        expect(target.style.zIndex).to.be.empty
        expect(target.style.cursor).to.equal(prefix + 'zoom-in')
        expect(target.style.transition).to.be.empty
        expect(target.style.transform).to.be.empty
        done()
      })
    })

    it('should remove the overlay', function() {
      expect(el.parentNode.lastElementChild.tagName).to.equal('IMG')
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

const	assert	= require('assert'),
	async	= require('async'),
	log	= require('winston'),
	fs	= require('fs');

let	confFile,
	altConfFile;

// Set up winston
log.remove(log.transports.Console);

before(function(done) {
	// Set configure file
	if (process.argv[3] === undefined)
		confFile = __dirname + '/../config/amqp_test.json';
	else
		confFile = process.argv[3].split('=')[1];

	log.verbose('Autobahn config file: "' + confFile + '"');

	fs.stat(confFile, function(err) {
		altConfFile = __dirname + '/../config/' + confFile;

		if (err) {
			log.info('Failed to find config file "' + confFile + '", retrying with "' + altConfFile + '"');

			fs.stat(altConfFile, function(err) {

				if (err) assert( ! err, 'fs.stat failed: ' + err.message);
				else if ( ! err) confFile	= altConfFile;

				done();
			});
		} else {
			done();
		}
	});
});

describe('Send, Recieve, Publish and Subscribe', function() {

	it('Test Connection', function(done) {
		const	Intercom	= require(__dirname + '/../index.js').Intercom,
			intercom	= new Intercom(require(confFile).default);

		intercom.ready(done);
	});

	// We do this to ensure intercom is just called once per session.
	it('Test parallel connection', function(done) {
		const	Intercom	= require(__dirname + '/../index.js').Intercom,
			intercom	= new Intercom(require(confFile).default);

		intercom.ready(done);
	});

	it('Send & Consume without publishing', function(done) {
		const	Intercom	= require(__dirname + '/../index.js').Intercom,
			intercom	= new Intercom(require(confFile).default);

		intercom.consume({que: 'testQue1', ack: true}, function(msg) {
			assert.deepEqual(msg.content.toString(), 'Hello World');
			done();
		}, function(err, result) {
			if (err) throw err;

			assert(result.consumerTag !== undefined);

			const	message	= 'Hello World',
				Intercom	= require(__dirname + '/../index.js').Intercom,
				intercom	= new Intercom(require(confFile).default);

			intercom.send({que: 'testQue1', publish: false}, message);
		});
	});

	it('Send & publish', function(done) {
		const	tasks = [];

		tasks.push(function(cb) {
			const	Intercom	= require(__dirname + '/../index.js').Intercom,
				intercom	= new Intercom(require(confFile).default);

			intercom.subscribe({exchange: 'testExchange1', ack: true}, function(msg) {
				assert.deepEqual(msg.content.toString(), 'Hello World');
				cb();
			}, function(err, result) {
				if (err) throw err;

				assert(result.consumerTag !== undefined);

				const	Intercom	= require(__dirname + '/../index.js').Intercom,
					intercom	= new Intercom(require(confFile).default),
					message	= 'Hello World';

				intercom.send({que: 'testQue2', exchange: 'testExchange1'}, message);
			});
		});

		tasks.push(function(cb) {
			const	Intercom	= require(__dirname + '/../index.js').Intercom,
				intercom	= new Intercom(require(confFile).default);

			intercom.consume({que: 'testQue2', ack: true}, function(msg) {
				assert.deepEqual(msg.content.toString(), 'Hello World');
				cb();
			}, function(err, result) {
				if (err) throw err;
				assert(result.consumerTag !== undefined);
			});
		});

		async.series(tasks, function(err) {
			assert( ! err);
			done();
		});
	});

	it('Subscribe & Publish', function(done) {
		const	Intercom	= require(__dirname + '/../index.js').Intercom,
			intercom	= new Intercom(require(confFile).default);

		intercom.subscribe({exchange: 'testExchange2', ack: true}, function(msg) {
			assert.deepEqual(msg.content.toString(), 'Hello World');
			done();
		}, function(err, result) {
			if (err) throw err;

			assert(result.consumerTag !== undefined);

			const	Intercom	= require(__dirname + '/../index.js').Intercom,
				intercom	= new Intercom(require(confFile).default);

			intercom.publish({exchange: 'testExchange2'}, 'Hello World');
		});
	});

});
<commit_msg>Did some comments in test.js<commit_after>'use strict';

const	assert	= require('assert'),
	async	= require('async'),
	log	= require('winston'),
	fs	= require('fs');

let	confFile,
	altConfFile;

// Set up winston
log.remove(log.transports.Console);

before(function(done) {
	// Set configure file
	if (process.argv[3] === undefined)
		confFile = __dirname + '/../config/amqp_test.json';
	else
		confFile = process.argv[3].split('=')[1];

	log.verbose('Autobahn config file: "' + confFile + '"');

	fs.stat(confFile, function(err) {
		altConfFile = __dirname + '/../config/' + confFile;

		if (err) {
			log.info('Failed to find config file "' + confFile + '", retrying with "' + altConfFile + '"');

			fs.stat(altConfFile, function(err) {

				if (err) assert( ! err, 'fs.stat failed: ' + err.message);
				else if ( ! err) confFile	= altConfFile;

				done();
			});
		} else {
			done();
		}
	});
});

describe('Send, Recieve, Publish and Subscribe', function() {

	it('Test Connection', function(done) {
		const	Intercom	= require(__dirname + '/../index.js').Intercom,
			intercom	= new Intercom(require(confFile).default);

		intercom.ready(done);
	});

	// We do this to ensure intercom is just called once per session.
	it('Test parallel connection', function(done) {
		const	Intercom	= require(__dirname + '/../index.js').Intercom,
			intercom	= new Intercom(require(confFile).default);

		intercom.ready(done);
	});

	it('Send & Consume without publishing', function(done) {
		const	Intercom	= require(__dirname + '/../index.js').Intercom,
			intercom	= new Intercom(require(confFile).default);

		// Consume as opposed to subscribe.
		intercom.consume({que: 'testQue1', ack: true}, function(msg) {
			assert.deepEqual(msg.content.toString(), 'Hello World');
			done();
		}, function(err, result) {
			if (err) throw err;

			assert(result.consumerTag !== undefined);

			// Instantiate a new intercom connection and sends a message.
			const	message	= 'Hello World',
				Intercom	= require(__dirname + '/../index.js').Intercom,
				intercom	= new Intercom(require(confFile).default);

			intercom.send({que: 'testQue1', publish: false}, message);
		});
	});

	it('Send & publish', function(done) {
		const	tasks = [];

		// Subscribe on testExchange1, send and publish message.
		tasks.push(function(cb) {
			const	Intercom	= require(__dirname + '/../index.js').Intercom,
				intercom	= new Intercom(require(confFile).default);

			intercom.subscribe({exchange: 'testExchange1', ack: true}, function(msg) {
				assert.deepEqual(msg.content.toString(), 'Hello World');
				cb();
			}, function(err, result) {
				if (err) throw err;

				assert(result.consumerTag !== undefined);

				const	Intercom	= require(__dirname + '/../index.js').Intercom,
					intercom	= new Intercom(require(confFile).default),
					message	= 'Hello World';

				intercom.send({que: 'testQue2', exchange: 'testExchange1'}, message);
			});
		});

		// Consume messages on testQue2.
		tasks.push(function(cb) {
			const	Intercom	= require(__dirname + '/../index.js').Intercom,
				intercom	= new Intercom(require(confFile).default);

			intercom.consume({que: 'testQue2', ack: true}, function(msg) {
				assert.deepEqual(msg.content.toString(), 'Hello World');
				cb();
			}, function(err, result) {
				if (err) throw err;
				assert(result.consumerTag !== undefined);
			});
		});

		async.series(tasks, function(err) {
			if (err) throw err;
			done();
		});
	});

	it('Subscribe & Publish', function(done) {
		const	Intercom	= require(__dirname + '/../index.js').Intercom,
			intercom	= new Intercom(require(confFile).default);

		intercom.subscribe({exchange: 'testExchange2', ack: true}, function(msg) {
			assert.deepEqual(msg.content.toString(), 'Hello World');
			done();
		}, function(err, result) {
			if (err) throw err;

			assert(result.consumerTag !== undefined);

			const	Intercom	= require(__dirname + '/../index.js').Intercom,
				intercom	= new Intercom(require(confFile).default);

			intercom.publish({exchange: 'testExchange2'}, 'Hello World');
		});
	});

});
<|endoftext|>


<commit_before>(function (rquery) {
  // Module systems magic dance.
  if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
    // NodeJS
    module.exports = rquery;
  } else if (typeof define === "function" && define.amd) {
    // AMD
    define(['react', 'lodash'], function (React, _) {
      return rquery(_, React);
    });
  } else {
    // Other environment (usually <script> tag): assume React is already loaded.
    window.$R = rquery(window._, React);
  }
}(function (_, React) {
  'use strict';

  var TestUtils = React.addons.TestUtils;

  function isArray (arr) {
    return Object.prototype.toString.call(arr) === '[object Array]';
  }

  function getDescendents (components, includeSelf) {
    return _(components)
      .map(function (component) {
        var components = TestUtils.findAllInRenderedTree(component, function () {
          return true;
        });

        if (!includeSelf) {
          components.shift();
        }

        return components;
      })
      .flatten()
      .uniq()
      .value();
  }

  function includeCompositeComponents (component) {
    if (component._renderedComponent) {
      return [component, component._renderedComponent];
    }

    return [component];
  }

  var STEP_DEFINITIONS = [
    // scope modifiers
    {
      matcher: /^\s*>\s*/,
      runStep: function (context, match) {
        var newScope = _(context.currentScope)
            .map(function (component) {
              var depth = component._reactInternalInstance._rootNodeID.split('.').length;

              return TestUtils.findAllInRenderedTree(component, function (descendent) {
                var descendentDepth = descendent._reactInternalInstance._rootNodeID.split('.').length;
                return depth + 1 === descendentDepth;
              });
            })
            .compact()
            .flatten()
            .map(includeCompositeComponents)
            .flatten()
            .value();

        context.setScope(newScope);
      }
    },
    {
      matcher: /^,\s*/,
      runStep: function (context, match) {
        context.saveResults();
        context.resetScope();
      }
    },
    {
      matcher: /^\s+/,
      runStep: function (context, match) {
        var newScope = getDescendents(context.currentScope, false);
        context.setScope(newScope);
      }
    },

    // selectors
    {
      matcher: /^([A-Z]\w*)/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          if (TestUtils.isCompositeComponent(component)) {
            return component._reactInternalInstance
                && component._reactInternalInstance._currentElement
                && component._reactInternalInstance._currentElement.type
                && component._reactInternalInstance._currentElement.type.displayName === match[1];
          }

          return false;
        });
      }
    },
    {
      matcher: /^([a-z]\w*)/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          if (TestUtils.isDOMComponent(component)) {
            return component.getDOMNode().tagName === match[1].toUpperCase();
          }

          return false;
        });
      }
    },
    {
      matcher: /^\.([^\s:]+)/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          if (TestUtils.isDOMComponent(component)
              && component.props.className) {
            var classes = component.props.className.split(' ');
            return classes.indexOf(match[1]) !== -1;
          }

          return false;
        });
      }
    },
    {
      matcher: /^\[([^\s~|^$*=]+)(?:([~|^$*]?=)"((?:\\"|.)*)")?\]/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          var propName = match[1] === 'class' ? 'className' : match[1],
              hasProp = TestUtils.isDOMComponent(component)
                        && propName in component.props;

          if (match[2]) {
            var value = match[3].replace('\\"', '"'),
                prop = String(component.props[propName]);

            switch (match[2]) {
              case '=':
                return prop === value;

              case '~=':
                return prop.split(/\s+/).indexOf(value) !== -1;

              case '|=':
                return prop === value || prop.indexOf(value + '-') === 0;

              case '^=':
                return prop.indexOf(value) === 0;

              case '$=':
                return prop.indexOf(value) === prop.length - value.length;

              case '*=':
                return prop.indexOf(value) !== -1;

              default:
                throw new Error('Unknown attribute operator: ' + operator);
                break;
            }
          }

          return hasProp;
        });
      }
    },
    {
      matcher: /^:contains\(((?:\\\)|.)*)\)/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          return $R(component).text().indexOf(match[1]) !== -1;
        });
      }
    }
  ];

  function isEmptyString (str) {
    return /^\s*$/.test(str);
  }

  function parseNextStep (selector) {
    var match, step;

    for (var i = 0; i < STEP_DEFINITIONS.length; i++) {
      step = STEP_DEFINITIONS[i];
      match = selector.match(step.matcher);
      if (match) {
        return {
          match: match,
          step: step
        };
      }
    }
  }

  function buildSteps (selector) {
    var step,
        steps = [];

    while (!isEmptyString(selector)) {
      step = parseNextStep(selector);

      if (step) {
        steps.push(step);
        selector = selector.substr(step.match[0].length);
      } else {
        throw new Error('Failed to parse selector at: ' + selector);
      }
    }

    return steps;
  }

  function Context (rootComponents) {
    this.rootComponents = rootComponents;
    this.results = [];
    this.defaultScope = getDescendents(rootComponents, true);
    this.resetScope();
  }

  Context.prototype.setScope = function (scope) {
    this.currentScope = _(scope)
      .map(includeCompositeComponents)
      .flatten()
      .value();
  };

  Context.prototype.resetScope = function () {
    this.setScope(this.defaultScope);
  };

  Context.prototype.filterScope = function (predicate) {
    this.currentScope = this.currentScope.filter(predicate);
  };

  Context.prototype.saveResults = function () {
    this.results = _.union(this.results, this.currentScope);
  };

  function rquery (components) {
    if (!isArray(components)) {
      if (components) {
        components = [components];
      } else {
        components = [];
      }
    }

    this.components = components;
    this.length = components.length;

    for (var i = 0; i < components.length; i++) {
      this[i] = components[i];
    }
  }

  rquery.prototype.find = function (selector) {
    var steps = buildSteps(selector),
        context = new Context(this.components);

    steps.forEach(function (step) {
      step.step.runStep(context, step.match);
    });

    context.saveResults();

    return new rquery(context.results);
  };

  rquery.prototype.findComponent = function (type) {
    return this._generate(function (component) {
      return TestUtils.isCompositeComponentWithType(component, type);
    });
  };

  rquery.prototype.get = function (index) {
    return this.components[index];
  };

  rquery.prototype.at = function (index) {
    return new rquery(this.components[index]);
  };

  rquery.prototype._generate = function (predicate) {
    var matches = [].concat.apply([], this.components.map(function (component) {
      return TestUtils.findAllInRenderedTree(component, predicate);
    }));

    return new rquery(matches);
  };

  rquery.prototype.simulateEvent = function (eventName, eventData) {
    for (var i = 0; i < this.components.length; i++) {
      TestUtils.Simulate[eventName](this.components[i].getDOMNode(), eventData);
    }

    return this;
  };

  rquery.prototype.text = function () {
    return _.map(this.components, function(component) {
      return component.getDOMNode().innerText || component.getDOMNode().textContent;
    }).join('');
  };

  var EVENT_NAMES = [
    // clipboard events
    'copy', 'cut', 'paste',
    // keyboard events
    'keyDown', 'keyPress', 'keyUp',
    // focus events
    'focus', 'blur',
    // form events
    'change', 'input', 'submit',
    // mouse events
    'click', 'mouseDown', 'mouseEnter', 'mouseLeave', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp',
    'doubleClick', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop',
    // touch events
    'touchCancel', 'touchEnd', 'touchMove', 'touchStart',
    // UI events
    'scroll',
    // wheel events
    'wheel'
  ];

  EVENT_NAMES.forEach(function (eventName) {
    rquery.prototype[eventName] = function (eventData) {
      return this.simulateEvent(eventName, eventData);
    };

    var name = 'ensure' + eventName[0].toUpperCase() + eventName.substr(1);
    rquery.prototype[name] = function (eventData) {
      if (this.length !== 1) {
        throw new Error('Called ' + name + ', but current context has ' + this.length + ' components. ' + name + ' only works when 1 component is present.');
      }

      return this.simulateEvent(eventName, eventData);
    };
  });

  var $R = function (components, selector) {
    var $r = new rquery(components);

    if (selector) {
      return $r.find(selector);
    }

    return $r;
  };

  $R.isRQuery = function (obj) {
    return obj instanceof rquery;
  };

  return $R;
}));
<commit_msg>Add `.val` helper<commit_after>(function (rquery) {
  // Module systems magic dance.
  if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
    // NodeJS
    module.exports = rquery;
  } else if (typeof define === "function" && define.amd) {
    // AMD
    define(['react', 'lodash'], function (React, _) {
      return rquery(_, React);
    });
  } else {
    // Other environment (usually <script> tag): assume React is already loaded.
    window.$R = rquery(window._, React);
  }
}(function (_, React) {
  'use strict';

  var TestUtils = React.addons.TestUtils;

  function isArray (arr) {
    return Object.prototype.toString.call(arr) === '[object Array]';
  }

  function getDescendents (components, includeSelf) {
    return _(components)
      .map(function (component) {
        var components = TestUtils.findAllInRenderedTree(component, function () {
          return true;
        });

        if (!includeSelf) {
          components.shift();
        }

        return components;
      })
      .flatten()
      .uniq()
      .value();
  }

  function includeCompositeComponents (component) {
    if (component._renderedComponent) {
      return [component, component._renderedComponent];
    }

    return [component];
  }

  var STEP_DEFINITIONS = [
    // scope modifiers
    {
      matcher: /^\s*>\s*/,
      runStep: function (context, match) {
        var newScope = _(context.currentScope)
            .map(function (component) {
              var depth = component._reactInternalInstance._rootNodeID.split('.').length;

              return TestUtils.findAllInRenderedTree(component, function (descendent) {
                var descendentDepth = descendent._reactInternalInstance._rootNodeID.split('.').length;
                return depth + 1 === descendentDepth;
              });
            })
            .compact()
            .flatten()
            .map(includeCompositeComponents)
            .flatten()
            .value();

        context.setScope(newScope);
      }
    },
    {
      matcher: /^,\s*/,
      runStep: function (context, match) {
        context.saveResults();
        context.resetScope();
      }
    },
    {
      matcher: /^\s+/,
      runStep: function (context, match) {
        var newScope = getDescendents(context.currentScope, false);
        context.setScope(newScope);
      }
    },

    // selectors
    {
      matcher: /^([A-Z]\w*)/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          if (TestUtils.isCompositeComponent(component)) {
            return component._reactInternalInstance
                && component._reactInternalInstance._currentElement
                && component._reactInternalInstance._currentElement.type
                && component._reactInternalInstance._currentElement.type.displayName === match[1];
          }

          return false;
        });
      }
    },
    {
      matcher: /^([a-z]\w*)/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          if (TestUtils.isDOMComponent(component)) {
            return component.getDOMNode().tagName === match[1].toUpperCase();
          }

          return false;
        });
      }
    },
    {
      matcher: /^\.([^\s:]+)/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          if (TestUtils.isDOMComponent(component)
              && component.props.className) {
            var classes = component.props.className.split(' ');
            return classes.indexOf(match[1]) !== -1;
          }

          return false;
        });
      }
    },
    {
      matcher: /^\[([^\s~|^$*=]+)(?:([~|^$*]?=)"((?:\\"|.)*)")?\]/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          var propName = match[1] === 'class' ? 'className' : match[1],
              hasProp = TestUtils.isDOMComponent(component)
                        && propName in component.props;

          if (match[2]) {
            var value = match[3].replace('\\"', '"'),
                prop = String(component.props[propName]);

            switch (match[2]) {
              case '=':
                return prop === value;

              case '~=':
                return prop.split(/\s+/).indexOf(value) !== -1;

              case '|=':
                return prop === value || prop.indexOf(value + '-') === 0;

              case '^=':
                return prop.indexOf(value) === 0;

              case '$=':
                return prop.indexOf(value) === prop.length - value.length;

              case '*=':
                return prop.indexOf(value) !== -1;

              default:
                throw new Error('Unknown attribute operator: ' + operator);
                break;
            }
          }

          return hasProp;
        });
      }
    },
    {
      matcher: /^:contains\(((?:\\\)|.)*)\)/,
      runStep: function (context, match) {
        context.filterScope(function (component) {
          return $R(component).text().indexOf(match[1]) !== -1;
        });
      }
    }
  ];

  function isEmptyString (str) {
    return /^\s*$/.test(str);
  }

  function parseNextStep (selector) {
    var match, step;

    for (var i = 0; i < STEP_DEFINITIONS.length; i++) {
      step = STEP_DEFINITIONS[i];
      match = selector.match(step.matcher);
      if (match) {
        return {
          match: match,
          step: step
        };
      }
    }
  }

  function buildSteps (selector) {
    var step,
        steps = [];

    while (!isEmptyString(selector)) {
      step = parseNextStep(selector);

      if (step) {
        steps.push(step);
        selector = selector.substr(step.match[0].length);
      } else {
        throw new Error('Failed to parse selector at: ' + selector);
      }
    }

    return steps;
  }

  function Context (rootComponents) {
    this.rootComponents = rootComponents;
    this.results = [];
    this.defaultScope = getDescendents(rootComponents, true);
    this.resetScope();
  }

  Context.prototype.setScope = function (scope) {
    this.currentScope = _(scope)
      .map(includeCompositeComponents)
      .flatten()
      .value();
  };

  Context.prototype.resetScope = function () {
    this.setScope(this.defaultScope);
  };

  Context.prototype.filterScope = function (predicate) {
    this.currentScope = this.currentScope.filter(predicate);
  };

  Context.prototype.saveResults = function () {
    this.results = _.union(this.results, this.currentScope);
  };

  function rquery (components) {
    if (!isArray(components)) {
      if (components) {
        components = [components];
      } else {
        components = [];
      }
    }

    this.components = components;
    this.length = components.length;

    for (var i = 0; i < components.length; i++) {
      this[i] = components[i];
    }
  }

  rquery.prototype.find = function (selector) {
    var steps = buildSteps(selector),
        context = new Context(this.components);

    steps.forEach(function (step) {
      step.step.runStep(context, step.match);
    });

    context.saveResults();

    return new rquery(context.results);
  };

  rquery.prototype.findComponent = function (type) {
    return this._generate(function (component) {
      return TestUtils.isCompositeComponentWithType(component, type);
    });
  };

  rquery.prototype.get = function (index) {
    return this.components[index];
  };

  rquery.prototype.at = function (index) {
    return new rquery(this.components[index]);
  };

  rquery.prototype._generate = function (predicate) {
    var matches = [].concat.apply([], this.components.map(function (component) {
      return TestUtils.findAllInRenderedTree(component, predicate);
    }));

    return new rquery(matches);
  };

  rquery.prototype.simulateEvent = function (eventName, eventData) {
    for (var i = 0; i < this.components.length; i++) {
      TestUtils.Simulate[eventName](this.components[i].getDOMNode(), eventData);
    }

    return this;
  };

  rquery.prototype.text = function () {
    return _.map(this.components, function(component) {
      return component.getDOMNode().innerText || component.getDOMNode().textContent;
    }).join('');
  };

  rquery.prototype.val = function (value) {
    _.each(this.components, function(component) {
      var node = component.getDOMNode();

      if ('value' in node) {
        node.value = value;
        $R(component).change();
      }
    });

    return this;
  };

  var EVENT_NAMES = [
    // clipboard events
    'copy', 'cut', 'paste',
    // keyboard events
    'keyDown', 'keyPress', 'keyUp',
    // focus events
    'focus', 'blur',
    // form events
    'change', 'input', 'submit',
    // mouse events
    'click', 'mouseDown', 'mouseEnter', 'mouseLeave', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp',
    'doubleClick', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop',
    // touch events
    'touchCancel', 'touchEnd', 'touchMove', 'touchStart',
    // UI events
    'scroll',
    // wheel events
    'wheel'
  ];

  EVENT_NAMES.forEach(function (eventName) {
    rquery.prototype[eventName] = function (eventData) {
      return this.simulateEvent(eventName, eventData);
    };

    var name = 'ensure' + eventName[0].toUpperCase() + eventName.substr(1);
    rquery.prototype[name] = function (eventData) {
      if (this.length !== 1) {
        throw new Error('Called ' + name + ', but current context has ' + this.length + ' components. ' + name + ' only works when 1 component is present.');
      }

      return this.simulateEvent(eventName, eventData);
    };
  });

  var $R = function (components, selector) {
    var $r = new rquery(components);

    if (selector) {
      return $r.find(selector);
    }

    return $r;
  };

  $R.isRQuery = function (obj) {
    return obj instanceof rquery;
  };

  return $R;
}));
<|endoftext|>


<commit_before>'use strict';

var esprintf = require('../');
var assert = require('assert');

/* global describe, it */

describe('esprintf', function() {
	it('Does not delete dashes from the formatted string', function() {
		assert.equal(esprintf('%s', '-'), '-');
	});

	it('Correctly formats 3 string values of length 1', function() {
		assert.equal(esprintf('%s %s %s', 'a', 'b', 'c'), 'a b c');
	});

	it('Correctly formats 3 string values of length 1 with left justification and no min width', function() {
		assert.equal(esprintf('%-s %-s %-s', 'a', 'b', 'c'), 'a b c');
	});

	it('Correctly padds a format with 6 dynamic strings with dynamic length', function() {
		assert.equal(
			esprintf('%-*s %-*s %-*s %-*s %-*s', 'asda', 20, 'asdas', 21, 'asda', 22, 'asdasd', 23, 'asdasd', 24),
			'asda                 asdas                 asda                   asdasd                  asdasd                  '
		);
	});

	it('Correctly truncates the string length for a string with a dynamic width of 0', function() {
		assert.equal(esprintf('%*s', 'asda', 0), '');
	});
});
<commit_msg>Added more tests<commit_after>'use strict';

var esprintf = require('../');
var assert = require('assert');

/* global describe, it */

describe('esprintf', function() {
	describe('Testing string formatting', function() {
		it('Does not delete dashes from the formatted string', function() {
			assert.equal(esprintf('%s', '-'), '-');
		});

		it('Correctly formats 3 string values of length 1', function() {
			assert.equal(esprintf('%s %s %s', 'a', 'b', 'c'), 'a b c');
		});

		it('Correctly formats 3 string values of length 1 with left justification and no min width', function() {
			assert.equal(esprintf('%-s %-s %-s', 'a', 'b', 'c'), 'a b c');
		});

		it('Correctly padds a format with 6 dynamic strings with dynamic length', function() {
			assert.equal(
				esprintf('%-*s %-*s %-*s %-*s %-*s', 'asda', 20, 'asdas', 21, 'asda', 22, 'asdasd', 23, 'asdasd', 24),
				'asda                 asdas                 asda                   asdasd                  asdasd                  '
			);
		});

		it('Correctly truncates the string length for a string with a dynamic width of 0', function() {
			assert.equal(esprintf('%*s', 'asda', 0), '');
		});
	});

	describe('Testing integer formatting', function() {
		it('Correctly formats a single integer', function() {
			assert.equal(esprintf('%i', 123456), '123456');
		});

		it('Correctly formats a single integer with forced prefix', function() {
			assert.equal(esprintf('%+i', 123456), '+123456');
		});

		it('Correctly truncates a single integer with fixed length', function() {
			assert.equal(esprintf('%3i', 123456), '123');
		});

		it('Correctly padds a single integer with zeros', function() {
			assert.equal(esprintf('%07i', 123456), '0123456');
		});
	});

	describe('Testing float formatting', function() {
		it('Correctly formats a single float', function() {
			assert.equal(esprintf('%f', 123456.12345), '123456.12345');
		});

		it('Correctly formats a single float with forced prefix', function() {
			assert.equal(esprintf('%+f', 12346.123), '+12346.123');
		});

		it('Correctly truncates a single float with fixed length', function() {
			assert.equal(esprintf('%3f', 123456.123), '123');
		});

		it('Correctly padds a single float with zeros', function() {
			assert.equal(esprintf('%09f', 123456), '000123456');
		});

		it('Correctly padds a single float with zeros and a floating point length of 2', function() {
			assert.equal(esprintf('%010.2f', 123456.12), '0123456.12');
		});
	});
});
<|endoftext|>


<commit_before>const { describe, it } = require('mocha')
const Bot = require('..')

const peer = process.env.TEST_PEER_ID
const token = process.env.TEST_VK_TOKEN

describe('Bot', function () {
  const bot = new Bot({ token })

  const engbot = new Bot({ token, api: { lang: 'en' } })
  const rusbot = new Bot({ token, api: { lang: 'ru' } })

  const oldVersionBot = new Bot({ token, api: { v: 5.37 } })

  const pollingbot = new Bot({ token })
  pollingbot.start()

  describe('Events', function () {
    it('Emits "update" on recieved message', (done) => {
      pollingbot.once('update', () => done())
      setTimeout(function() {
        pollingbot.send('Test message', peer)
      }, 1000) // because sometimes it doesn't work ¯\_(ツ)_/¯
    })
  })

  describe('#send', function () {
    it('Sends message', function () {
      return bot.send('Test message 2', peer)
    })
  })

  describe('#api', function () {
    describe('Languages', function () {
      it('Gets response in Russian', function () {
        return rusbot.api('users.get', { user_ids: 1 })
          .then(res => res[0])
          .then(durov => {
            if (durov.first_name !== 'Павел') throw new Error()
          })
      })

      it('Gets response in English', function () {
        return engbot.api('users.get', { user_ids: 1 })
          .then(res => res[0])
          .then(durov => {
            if (durov.first_name !== 'Pavel') throw new Error()
          })
      })
    })

    it('Gets full response object if using `execute` method', function () {
      return bot.api('execute', {
        code: "return [API.messages.send(), API.messages.send()];"
      }).then(res => {
        if (!res.response) throw new Error('There is no response object')
        if (!res.execute_errors) throw new Error('There is no errors object')
      })
    })

    describe('Versions', function () {
      it('Gets error when using peer_id on version 5.37', function () {
        return oldVersionBot.api('messages.send', {
          peer_id: peer,
          message: '123'
        }).then(() => { throw new Error() }, () => true)
      })
    })
  })
})
<commit_msg>test message delay 1s -> 5s<commit_after>const { describe, it } = require('mocha')
const Bot = require('..')

const peer = process.env.TEST_PEER_ID
const token = process.env.TEST_VK_TOKEN

describe('Bot', function () {
  const bot = new Bot({ token })

  const engbot = new Bot({ token, api: { lang: 'en' } })
  const rusbot = new Bot({ token, api: { lang: 'ru' } })

  const oldVersionBot = new Bot({ token, api: { v: 5.37 } })

  const pollingbot = new Bot({ token })
  pollingbot.start()

  describe('Events', function () {
    it('Emits "update" on recieved message', (done) => {
      pollingbot.once('update', () => done())
      setTimeout(function() {
        pollingbot.send('Test message', peer)
      }, 5000) // because sometimes it doesn't work ¯\_(ツ)_/¯
    })
  })

  describe('#send', function () {
    it('Sends message', function () {
      return bot.send('Test message 2', peer)
    })
  })

  describe('#api', function () {
    describe('Languages', function () {
      it('Gets response in Russian', function () {
        return rusbot.api('users.get', { user_ids: 1 })
          .then(res => res[0])
          .then(durov => {
            if (durov.first_name !== 'Павел') throw new Error()
          })
      })

      it('Gets response in English', function () {
        return engbot.api('users.get', { user_ids: 1 })
          .then(res => res[0])
          .then(durov => {
            if (durov.first_name !== 'Pavel') throw new Error()
          })
      })
    })

    it('Gets full response object if using `execute` method', function () {
      return bot.api('execute', {
        code: "return [API.messages.send(), API.messages.send()];"
      }).then(res => {
        if (!res.response) throw new Error('There is no response object')
        if (!res.execute_errors) throw new Error('There is no errors object')
      })
    })

    describe('Versions', function () {
      it('Gets error when using peer_id on version 5.37', function () {
        return oldVersionBot.api('messages.send', {
          peer_id: peer,
          message: '123'
        }).then(() => { throw new Error() }, () => true)
      })
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');
const path = require('path');
const {parseString} = require('xml2js');
const fs = require('fs');

const icecatProduct = require('../lib/OpenCatalog/product');

describe('IcecatProduct - Found', function () {
    let icecatProductXML = fs.readFileSync(path.join(__dirname, 'fixtures/4948570114344.xml'), 'utf8');
    let icecatProductJSON = null;
    let testProduct = null;

    describe('Create Product', function () {
        it('should return IcecatProduct', function () {
            parseString(icecatProductXML, function (err, jsonData) {
                icecatProductJSON = jsonData;
            });

            const requestUrl = 'https://user:password@data.icecat.biz/response';
            testProduct = new icecatProduct(icecatProductJSON, icecatProductXML, requestUrl);
            assert.ok(testProduct instanceof icecatProduct);
            assert.ok(testProduct.requestUrl === requestUrl);
        });
    });

    describe('Get Product values', function () {
        it('should get Product returnCode Success', function () {
            assert.strictEqual(
                testProduct.getReturnCode(),
                testProduct.returnCode.SUCCESS
            );
        });

        it('should get Product Name', function () {
            assert.equal(
                testProduct.getName(),
                'X4071UHSU-B1'
            );
        });

        it('should get Product Url', function () {
            assert.equal(
                testProduct.getProductUrl(),
                'http://www.iiyama.com/gl_en/products/prolite-x4071uhsu-b1/'
            );
        });

        it('should get Product EAN', function () {
            assert.equal(
                testProduct.getEan(),
                '4948570114344'
            );
        });

        it('should get Icecat Product Id', function () {
            assert.equal(
                testProduct.getId(),
                '29900045'
            );
        });
    });
});

describe('IcecatProduct - Not Found', function () {
    let icecatProductXML = fs.readFileSync(path.join(__dirname, 'fixtures/12345.xml'), 'utf8');
    let icecatProductJSON = null;
    let testProduct = null;

    describe('Create Product', function () {
        it('should return IcecatProduct', function () {
            parseString(icecatProductXML, function (err, jsonData) {
                icecatProductJSON = jsonData;
            });

            const requestUrl = 'https://user:password@data.icecat.biz/response';
            testProduct = new icecatProduct(icecatProductJSON, icecatProductXML, requestUrl);
            assert.ok(testProduct instanceof icecatProduct);
            assert.ok(testProduct.requestUrl === requestUrl);
        });
    });

    describe('Get Product values', function () {
        it('should get Product returnCode Fail', function () {
            assert.strictEqual(
                testProduct.getReturnCode(),
                testProduct.returnCode.FAIL
            );
        });
    });
});<commit_msg>code review<commit_after>'use strict';

const assert = require('assert');
const path = require('path');
const {parseString} = require('xml2js');
const fs = require('fs');

const icecatProduct = require('../lib/OpenCatalog/product');

describe('IcecatProduct - Found', function () {
    let icecatProductXML = fs.readFileSync(path.join(__dirname, 'fixtures/4948570114344.xml'), 'utf8');
    let icecatProductJSON = null;
    let testProduct = null;

    describe('Create Product', function () {
        it('should return IcecatProduct', function () {
            parseString(icecatProductXML, function (err, jsonData) {
                icecatProductJSON = jsonData;
            });

            const requestUrl = 'https://user:password@data.icecat.biz/response';
            testProduct = new icecatProduct(icecatProductJSON, icecatProductXML, requestUrl);
            assert.ok(testProduct instanceof icecatProduct);
            assert.ok(testProduct.requestUrl === requestUrl);
        });
    });

    describe('Get Product values', function () {
        it('should get Product returnCode Success', function () {
            assert.strictEqual(
                testProduct.getReturnCode(),
                testProduct.returnCode.SUCCESS
            );
        });

        it('should get Product Name', function () {
            assert.equal(
                testProduct.getName(),
                'X4071UHSU-B1'
            );
        });

        it('should get Product Url', function () {
            assert.equal(
                testProduct.getProductUrl(),
                'http://www.iiyama.com/gl_en/products/prolite-x4071uhsu-b1/'
            );
        });

        it('should get Product EAN', function () {
            assert.equal(
                testProduct.getEan(),
                '4948570114344'
            );
        });

        it('should get Icecat Product Id', function () {
            assert.equal(
                testProduct.getID(),
                '29900045'
            );
        });
    });
});

describe('IcecatProduct - Not Found', function () {
    let icecatProductXML = fs.readFileSync(path.join(__dirname, 'fixtures/12345.xml'), 'utf8');
    let icecatProductJSON = null;
    let testProduct = null;

    describe('Create Product', function () {
        it('should return IcecatProduct', function () {
            parseString(icecatProductXML, function (err, jsonData) {
                icecatProductJSON = jsonData;
            });

            const requestUrl = 'https://user:password@data.icecat.biz/response';
            testProduct = new icecatProduct(icecatProductJSON, icecatProductXML, requestUrl);
            assert.ok(testProduct instanceof icecatProduct);
            assert.ok(testProduct.requestUrl === requestUrl);
        });
    });

    describe('Get Product values', function () {
        it('should get Product returnCode Fail', function () {
            assert.strictEqual(
                testProduct.getReturnCode(),
                testProduct.returnCode.FAIL
            );
        });
    });
});<|endoftext|>


<commit_before>const fs = require('fs');
const {promisify} = require('util');

const stat = promisify(fs.stat);

const checkCacheExpiry = (path, ttl) =>
    stat(path).then(stats => {

        if (new Date(stats.mtime).getTime() + ttl < Date.now()) {

            return Promise.reject(new Error('Cache has expired.'));

        }

        return stats;

    })
        .catch(() => Promise.reject(new Error('Cache is missing.')));

module.exports = checkCacheExpiry;
<commit_msg>Simplified catch calls.<commit_after>const fs = require('fs');
const {promisify} = require('util');

const stat = promisify(fs.stat);

const checkCacheExpiry = (path, ttl) =>
    stat(path).then(stats => {

        if (new Date(stats.mtime).getTime() + ttl < Date.now()) {

            return Promise.reject(new Error('Cache has expired.'));

        }

        return stats;

    });

module.exports = checkCacheExpiry;
<|endoftext|>


<commit_before>/**
 * End2End tests for browse table module
 */

describe('browse/table/filter', function() {

    beforeEach(function() {
        browser.get('/browse/table/filter');
    });

    it('should not render filter table without selection', function() {
        expect(element.all(by.css('[ng-view] .table.table-bordered.table-condensed.table-filter')).count()).toBe(0);
    });

    it('should render select for questionnaires selection', function() {
        expect(element.all(by.css('[ng-view] .select2-container')).count()).toBe(3);
    });

});

describe('browse/table/filter menu', function() {

    beforeEach(function() {
        // Always close menu if it was opened, by clicking anywhere
        element(by.css('footer')).click();
    });

    browser.get('/browse/table/filter?questionnaires=2&filters=3,75,27,9,10');

    it('should render filter table', function() {
        expect(element.all(by.css('[ng-view] .table.table-bordered.table-condensed.table-filter')).count()).toBe(1);
    });

    it('should have every single type of values', function() {
        expect(element.all(by.css('.input-group-btn .fa-question')).count()).toBe(1);
        expect(element.all(by.css('.input-group-btn .fa-gims-rule')).count()).toBe(1);
        expect(element.all(by.css('.input-group-btn .fa-angle-down')).count()).toBe(1);
        expect(element.all(by.css('.input-group-btn .fa-gims-child')).count()).toBe(1);
        expect(element.all(by.css('.input-group-btn .fa-gims-summand')).count()).toBe(1);
    });

    it('menu for question should be complete', function() {
        element(by.css('.input-group-btn .fa-question')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("Manually answered");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(3)')).getText()).toContain("Tap");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(4)')).getText()).toContain("0.243446");
    });

    it('menu for rule should be complete', function() {
        element(by.css('.input-group-btn .fa-gims-rule')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("Computed with rules");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(4)')).getText()).toContain("Rules used in 1st step of computation");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(5) ul li:nth-child(1)')).getText()).toContain("Total improved (CEN91 - Bangladesh, Urban)");
    });

    it('menu for nothing should be complete', function() {
        element(by.css('.input-group-btn .fa-angle-down')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("No value");
    });

    it('menu for children should be complete', function() {
        element(by.css('.input-group-btn .fa-gims-child')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("Computed with children");
    });

    it('menu for summands should be complete', function() {
        element(by.css('.input-group-btn .fa-gims-summand')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("Computed with summands");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(4)')).getText()).toContain("Summands used for computation");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(5)')).getText()).toContain("Protected ground water (all protected wells or springs)");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(6)')).getText()).toContain("Protected ground water (all protected wells or springs)");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(7)')).getText()).toContain("Protected ground water (all protected wells or springs)");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(8)')).getText()).toContain("Protected ground water (all protected wells or springs)");
    });
});
<commit_msg>Fix e2e tests #2761<commit_after>/**
 * End2End tests for browse table module
 */

describe('browse/table/filter', function() {

    beforeEach(function() {
        browser.get('/browse/table/filter');
    });

    it('should not render filter table without selection', function() {
        expect(element.all(by.css('[ng-view] .table.table-bordered.table-condensed.table-filter')).count()).toBe(0);
    });

    it('should render select for questionnaires selection', function() {
        expect(element.all(by.css('[ng-view] .select2-container')).count()).toBe(3);
    });

});

describe('browse/table/filter menu', function() {

    beforeEach(function() {
        // Always close menu if it was opened, by clicking anywhere
        element(by.css('footer')).click();
    });

    browser.get('/browse/table/filter?questionnaires=2&filters=3,75,27,9,10');

    it('should render filter table', function() {
        expect(element.all(by.css('[ng-view] .table-filter')).count()).toBe(1);
    });

    it('should have every single type of values', function() {
        expect(element.all(by.css('.input-group-btn .fa-question')).count()).toBe(1);
        expect(element.all(by.css('.input-group-btn .fa-gims-rule')).count()).toBe(1);
        expect(element.all(by.css('.input-group-btn .fa-angle-down')).count()).toBe(1);
        expect(element.all(by.css('.input-group-btn .fa-gims-child')).count()).toBe(1);
        expect(element.all(by.css('.input-group-btn .fa-gims-summand')).count()).toBe(1);
    });

    it('menu for question should be complete', function() {
        element(by.css('.input-group-btn .fa-question')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("Manually answered");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(3)')).getText()).toContain("Tap");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(4)')).getText()).toContain("0.243446");
    });

    it('menu for rule should be complete', function() {
        element(by.css('.input-group-btn .fa-gims-rule')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("Computed with rules");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(4)')).getText()).toContain("Rules used in 1st step of computation");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(5) ul li:nth-child(1)')).getText()).toContain("Total improved (CEN91 - Bangladesh, Urban)");
    });

    it('menu for nothing should be complete', function() {
        element(by.css('.input-group-btn .fa-angle-down')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("No value");
    });

    it('menu for children should be complete', function() {
        element(by.css('.input-group-btn .fa-gims-child')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("Computed with children");
    });

    it('menu for summands should be complete', function() {
        element(by.css('.input-group-btn .fa-gims-summand')).click();
        expect(element(by.css('.gims-dropdown-menu li:nth-child(2)')).getText()).toContain("Computed with summands");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(4)')).getText()).toContain("Summands used for computation");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(5)')).getText()).toContain("Protected ground water (all protected wells or springs)");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(6)')).getText()).toContain("Protected ground water (all protected wells or springs)");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(7)')).getText()).toContain("Protected ground water (all protected wells or springs)");
        expect(element(by.css('.gims-dropdown-menu li:nth-child(8)')).getText()).toContain("Protected ground water (all protected wells or springs)");
    });
});
<|endoftext|>