<commit_before>// ==UserScript==
// @name         einstein
// @namespace    https://github.com/reruin
// @version      0.1
// @license      MIT
// @description  einstein
// @author       reruin@gmail.com
// @grant        none
// @include      http://einstein.enoctus.co.uk/*
// @include      https://einstein.enoctus.co.uk/*
// @connect      *
// @run-at       document-start
// ==/UserScript==

(function(root){
  var nw = root.nw = {};
  var stack = [];
  var ArrayProto = Array.prototype, ObjProto = Object.prototype;
  var hasOwnProperty   = ObjProto.hasOwnProperty;

  var page  = {
    addStyle : function(css){
        var el = document.createElement("style");
        el.innerHTML = css;
        document.getElementsByTagName('head')[0].appendChild(el);
    },
    addScript : function(script , pos){
      var el = document.createElement("script");
      el.textContent = script;
      if(typeof pos == 'object'){
        pos.appendChild(el);
      }
      else if(pos == 'head'){
        document.getElementsByTagName('head')[0].appendChild(el);
      }else{
        document.getElementsByTagName('body')[0].appendChild(el);
      }
    },
    addScriptLink : function( data , pos){
      var el = document.createElement("script");
      for(var i in data){
        el.setAttribute(i , data[i]);
      }

      if(typeof pos == 'object'){
        pos.appendChild(el);
      }
      else if(pos == 'head'){
        document.getElementsByTagName('head')[0].appendChild(el);
      }else{
        document.getElementsByTagName('body')[0].appendChild(el);
      }
    },
    addHtml : function(dom){
      var el = document.createElement("dom");
      el.innerHTML = dom;
      document.getElementsByTagName('body')[0].appendChild(el);
    }
  };

  function $(e){
    return document.querySelector(e);
  }
  function $$(e){
    return document.querySelectorAll(e);
  }

  function noop(){

  }

  function has(obj, key) {
      return obj != null && hasOwnProperty.call(obj, key);
  }

  function key(obj){
      var k = [];
      for(var i in obj){
          if(has(obj , i)) k.push(i);
      }
      return k;
  }

  function isString(v){
    return typeof v === 'string';
  }

  function is(v , b){
    return ObjProto.toString.call(v) === "[object "+b+"]";
  }

  function isArray(v){
    return is(v , 'Array');
  }

  function isRegExp(v){
    return is(v , 'RegExp');
  }

  function isObject(v){
    return is(v , 'Object');
  }

  function isFunction(v){
    return is(v , 'Function');
  }

  function create(expr , handler){
    if(expr && handler){
      stack.push({rule:expr , post:handler});
    }
    else{
      stack.push(expr);
    }
  }

  function replace(str,obj , format){
      return str.replace(RegExp('(?:' + key(obj).join('|').replace(/([\:\'\)\(\{\}])/g,'\\$1') + ')','g') , function(match){
          return format ? format(obj[match]) : obj[match];
      });
  }

  function toArray(a){
    return Array.prototype.slice.call(a);
  }

  function formatLink(newurl , m){
    return newurl.replace(/\$(\d+)/g , function($0,$1){
      return m[$1];
    });
  }

  function hit(obj){
    var ret = [];
    for(var i in stack){
        var rule = stack[i].rule;
        if( isRegExp(rule) ){
          var m = obj.url.match(rule);
            // console.log(stack[i].post,m)
          if( m ){
            if(isString(stack[i].post)){
              ret.push({
                redirect : formatLink(stack[i].post , toArray(m))
              });
            }else{
              ret.push({
                pre : stack[i].pre || noop,
                post : stack[i].post || noop,
                args : toArray(m)
              });

            }
          }

        }
        else if(isObject(rule)){
          var flag = true;
          var m = null, ret_t = {};
          for(var key in rule){
            m = obj[key].match(rule[key]);
            if(!m){
              flag = false;
              break;
            }else{
              if(m.length>1){
                ret_t[key] = toArray(m);
              }
            }
          }
          if(flag){
            ret.push({
              pre : stack[i].pre || noop,
              post : stack[i].post || noop,
              args : ret_t
            });
          }
        }
        else if(isFunction(rule)){
          if( rule() ){
            ret.push({
              pre : stack[i].pre || noop,
              post : stack[i].post || noop,
              args : {}
            });
          }
        }
        else if(isArray(rule)){
          var flag = false;
          for (var j = rule.length - 1; j >= 0; j--) {
            if(obj.url.match(rule[j])){
              flag = true;
              break;
            }
          }
          if(flag){
            ret.push({
              pre : stack[i].pre || noop,
              post : stack[i].post || noop,
              args : {}
            });
          }
        }
    }
    return ret;
  }

  function init(){
    var loc = window.location;

    var obj = {
      url : loc.href,
      scheme: loc.protocol.slice(0, -1),
      host: loc.hostname,
      port: loc.port,
      path: loc.pathname,
      search: loc.search,
      hash: loc.hash
    };

    var handlers = hit(obj);
    if(handlers.length){
      handlers.forEach(function(handler){
        if(handler.redirect){
          open(handler.redirect);
        }
        else if(handler.pre) handler.pre(handler.args);
      });
    }

    document.addEventListener('DOMContentLoaded' , function(){
      if(handlers.length){
        handlers.forEach(function(handler){
          if(handler.post) {
            console.log(handler.post)
            handler.post(handler.args);
          }
        });
      }
    })
  }

  function monitor(tag , expr , callback){
    var d = tag.split(':');
    var evts = {
      'removed':'DOMNodeRemoved',
      'inserted':'DOMNodeInserted',
      'modified':'DOMSubtreeModified'
    };

    tag = d[0];

    var evt = evts[d[1] || 'modified'];

    var watch = d[2] === undefined ? false : true;

    if(isFunction(expr))  {
      callback = expr;
      expr =  null ;
    }

    var matchSpan = function(target , t){
      var k = document.createElement('div');
      k.appendChild(target.cloneNode(false));
      var ret = k.querySelector(t);
      k = null;
      return ret;
    }

    //return new promise(function(resolve, reject){
      var handler = function(event){
        var target = event.target;
        if(matchSpan(target , tag)){
          if(expr){
            var m = target.textContent.match(expr);
            if(m){
              if(callback) callback(m);
              if(!watch) document.removeEventListener(evt , handler);
            }
          }else{
            if(callback) callback(target);

            if(!watch) document.removeEventListener(evt , handler);
          }
        }
      };

      document.addEventListener(evt , handler);
    //});
  }

  function open(url){
    open_direct(url);
  }

  function open_direct(url){
    var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    link.href = url;
    link.click();
  }

  nw.c = create;
  nw.m = monitor;
  nw.o = open;

  nw.$ = $;
  nw.$$ = $$;
  nw.r = replace;

  nw.init = init;
  nw.noop = noop;

  nw.addStyle = page.addStyle;
  nw.addScript = page.addScript;
  nw.addScriptLink = page.addScriptLink;
}(this));

/**
 * einstein
 *
 */

//https://einstein.enoctus.co.uk/cart.php?a=add&pid=92&billingcycle=annually&promocode=JOIN15
nw.c({
  rule: /einstein\.enoctus\.co\.uk\/cart\.php\?a=add&pid=/,
  pre: function() {
    //超时
  },
  post: function() {
    var t = $('#order-boxes').html()
    if(t && t.indexOf('Out of Stock') >=0){
      setTimeout(function(){
        location.reload()
      },5*1000)
    }
  }
});

nw.c({
  rule: /einstein\.enoctus\.co\.uk\/cart\.php\?a=confproduct/,
  pre: function() {
    //超时

  },
  post: function() {

    setTimeout(function() {
      var host = $('#inputHostname');
      if(host.length){
        host.val('hk'+Date.now());
        $('#inputRootpw').val('changeme');
        $("#inputConfigOption1 option:last").attr("selected",true);

        $('#btnCompleteProductConfig').click();

      }else{
        console.log('no');
      }

    }, 200);

  }
});

nw.c({
  rule: /einstein\.enoctus\.co\.uk\/cart\.php\?a=view/,
  pre: function() {
    //超时
  },
  post: function() {

    var script = function(){
      var dig = (function($){
        var link = '/cart.php?a=add&pid=%id&billingcycle=annually', retry = 0;

        var services = [
          {title:'512M 月',url:'/cart.php?a=add&pid=92'},
          {title:'512M 年' , url:'/cart.php?a=add&pid=92&billingcycle=annually'},
          {title:'1G 月', url:'/cart.php?a=add&pid=93'},
          {title:'1G 年', url:'/cart.php?a=add&pid=93&billingcycle=annually'}
        ];

        var current
        function init(){
          var html = '';
          for(var i in services){
            html += '
<button id="__c_%id" onclick="window.dig(%id)" class="btn btn-success" id="checkout">%title</button>
'.replace(/%id/g,i).replace(/%title/g,services[i].title)
          }

          $('.top-nav').prepend(html);
        }

        function process(){
          current.prop('disabled',true).html('运行中('+ retry++ +')');

          $.get(link).then(function(resp){
            if(resp.indexOf('Out of Stock')>=0){
              setTimeout(process, 3000);
            }else{
              location.href = link;
            }
          },function(){
            setTimeout(process, 3000);
          });
        }

        function check(id){
          current = $('#__c_'+id);
          current.prop('disabled',true).html('运行中('+ retry++ +')');
          link = services[parseInt(id)].url;
          process();
        }

        init();

        return check;
      }(jQuery));

      window.dig = dig;
    }

    if($('.view-cart-empty').length){
      nw.addScript(';(' + script + '());', 'body');
    }else{
      setTimeout(function(){
        location.href = 'cart.php?a=checkout';
        // $('#checkout').click();
      },100);
    }

  }
});

nw.c({
  rule: /einstein\.enoctus\.co\.uk\/cart\.php\?a=checkout/,
  pre: function() {
    //超时
  },
  post: function() {
    setTimeout(function(){
      // $('#checkout').click();
      $("input[name='paymentmethod'][value='paypal']").attr("checked",'checked');
      $('.radio-inline').eq(1).click();
      $("#accepttos").attr("checked", true);
      $('#btnCompleteOrder').click();
      setTimeout(function(){
       // alert('快下单');
      },5000);
    },100);
  }
});

//==================================
nw.init();
<commit_msg>fix bugs<commit_after>// ==UserScript==
// @name         einstein
// @namespace    https://github.com/reruin
// @version      0.2
// @license      MIT
// @description  einstein
// @author       reruin@gmail.com
// @grant        none
// @include      http://einstein.enoctus.co.uk/*
// @include      https://einstein.enoctus.co.uk/*
// @connect      *
// @run-at       document-start
// ==/UserScript==

(function(root){
  var nw = root.nw = {};
  var stack = [];
  var ArrayProto = Array.prototype, ObjProto = Object.prototype;
  var hasOwnProperty   = ObjProto.hasOwnProperty;

  var page  = {
    addStyle : function(css){
        var el = document.createElement("style");
        el.innerHTML = css;
        document.getElementsByTagName('head')[0].appendChild(el);
    },
    addScript : function(script , pos){
      var el = document.createElement("script");
      el.textContent = script;
      if(typeof pos == 'object'){
        pos.appendChild(el);
      }
      else if(pos == 'head'){
        document.getElementsByTagName('head')[0].appendChild(el);
      }else{
        document.getElementsByTagName('body')[0].appendChild(el);
      }
    },
    addScriptLink : function( data , pos){
      var el = document.createElement("script");
      for(var i in data){
        el.setAttribute(i , data[i]);
      }

      if(typeof pos == 'object'){
        pos.appendChild(el);
      }
      else if(pos == 'head'){
        document.getElementsByTagName('head')[0].appendChild(el);
      }else{
        document.getElementsByTagName('body')[0].appendChild(el);
      }
    },
    addHtml : function(dom){
      var el = document.createElement("dom");
      el.innerHTML = dom;
      document.getElementsByTagName('body')[0].appendChild(el);
    }
  };

  function $(e){
    return document.querySelector(e);
  }
  function $$(e){
    return document.querySelectorAll(e);
  }

  function noop(){

  }

  function has(obj, key) {
      return obj != null && hasOwnProperty.call(obj, key);
  }

  function key(obj){
      var k = [];
      for(var i in obj){
          if(has(obj , i)) k.push(i);
      }
      return k;
  }

  function isString(v){
    return typeof v === 'string';
  }

  function is(v , b){
    return ObjProto.toString.call(v) === "[object "+b+"]";
  }

  function isArray(v){
    return is(v , 'Array');
  }

  function isRegExp(v){
    return is(v , 'RegExp');
  }

  function isObject(v){
    return is(v , 'Object');
  }

  function isFunction(v){
    return is(v , 'Function');
  }

  function create(expr , handler){
    if(expr && handler){
      stack.push({rule:expr , post:handler});
    }
    else{
      stack.push(expr);
    }
  }

  function replace(str,obj , format){
      return str.replace(RegExp('(?:' + key(obj).join('|').replace(/([\:\'\)\(\{\}])/g,'\\$1') + ')','g') , function(match){
          return format ? format(obj[match]) : obj[match];
      });
  }

  function toArray(a){
    return Array.prototype.slice.call(a);
  }

  function formatLink(newurl , m){
    return newurl.replace(/\$(\d+)/g , function($0,$1){
      return m[$1];
    });
  }

  function hit(obj){
    var ret = [];
    for(var i in stack){
        var rule = stack[i].rule;
        if( isRegExp(rule) ){
          var m = obj.url.match(rule);
            // console.log(stack[i].post,m)
          if( m ){
            if(isString(stack[i].post)){
              ret.push({
                redirect : formatLink(stack[i].post , toArray(m))
              });
            }else{
              ret.push({
                pre : stack[i].pre || noop,
                post : stack[i].post || noop,
                args : toArray(m)
              });

            }
          }

        }
        else if(isObject(rule)){
          var flag = true;
          var m = null, ret_t = {};
          for(var key in rule){
            m = obj[key].match(rule[key]);
            if(!m){
              flag = false;
              break;
            }else{
              if(m.length>1){
                ret_t[key] = toArray(m);
              }
            }
          }
          if(flag){
            ret.push({
              pre : stack[i].pre || noop,
              post : stack[i].post || noop,
              args : ret_t
            });
          }
        }
        else if(isFunction(rule)){
          if( rule() ){
            ret.push({
              pre : stack[i].pre || noop,
              post : stack[i].post || noop,
              args : {}
            });
          }
        }
        else if(isArray(rule)){
          var flag = false;
          for (var j = rule.length - 1; j >= 0; j--) {
            if(obj.url.match(rule[j])){
              flag = true;
              break;
            }
          }
          if(flag){
            ret.push({
              pre : stack[i].pre || noop,
              post : stack[i].post || noop,
              args : {}
            });
          }
        }
    }
    return ret;
  }

  function init(){
    var loc = window.location;

    var obj = {
      url : loc.href,
      scheme: loc.protocol.slice(0, -1),
      host: loc.hostname,
      port: loc.port,
      path: loc.pathname,
      search: loc.search,
      hash: loc.hash
    };

    var handlers = hit(obj);
    if(handlers.length){
      handlers.forEach(function(handler){
        if(handler.redirect){
          open(handler.redirect);
        }
        else if(handler.pre) handler.pre(handler.args);
      });
    }

    document.addEventListener('DOMContentLoaded' , function(){
      if(handlers.length){
        handlers.forEach(function(handler){
          if(handler.post) {
            console.log(handler.post)
            handler.post(handler.args);
          }
        });
      }
    })
  }

  function monitor(tag , expr , callback){
    var d = tag.split(':');
    var evts = {
      'removed':'DOMNodeRemoved',
      'inserted':'DOMNodeInserted',
      'modified':'DOMSubtreeModified'
    };

    tag = d[0];

    var evt = evts[d[1] || 'modified'];

    var watch = d[2] === undefined ? false : true;

    if(isFunction(expr))  {
      callback = expr;
      expr =  null ;
    }

    var matchSpan = function(target , t){
      var k = document.createElement('div');
      k.appendChild(target.cloneNode(false));
      var ret = k.querySelector(t);
      k = null;
      return ret;
    }

    //return new promise(function(resolve, reject){
      var handler = function(event){
        var target = event.target;
        if(matchSpan(target , tag)){
          if(expr){
            var m = target.textContent.match(expr);
            if(m){
              if(callback) callback(m);
              if(!watch) document.removeEventListener(evt , handler);
            }
          }else{
            if(callback) callback(target);

            if(!watch) document.removeEventListener(evt , handler);
          }
        }
      };

      document.addEventListener(evt , handler);
    //});
  }

  function open(url){
    open_direct(url);
  }

  function open_direct(url){
    var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    link.href = url;
    link.click();
  }

  nw.c = create;
  nw.m = monitor;
  nw.o = open;

  nw.$ = $;
  nw.$$ = $$;
  nw.r = replace;

  nw.init = init;
  nw.noop = noop;

  nw.addStyle = page.addStyle;
  nw.addScript = page.addScript;
  nw.addScriptLink = page.addScriptLink;
}(this));

/**
 * enoctus
 *
 */

//https://einstein.enoctus.co.uk/cart.php?a=add&pid=92&billingcycle=annually&promocode=JOIN15

nw.c({
  rule: /einstein\.enoctus\.co\.uk\/cart\.php\?a=confproduct/,
  pre: function() {},
  post: function() {

    setTimeout(function() {
      var host = $('#inputHostname');
      if(host.length){
        host.val('hk'+Date.now());
        $('#inputRootpw').val('changeme');
        $("#inputConfigOption1 option:last").attr("selected",true);

        $('#btnCompleteProductConfig').click();

      }else{
        console.log('no');
      }

    }, 200);

  }
});

nw.c({
  rule: /einstein\.enoctus\.co\.uk\/cart\.php\?a=view/,
  pre: function() {},
  post: function() {

    var script = function(){
      var dig = (function($){
        var link = '/cart.php?a=add&pid=%id&billingcycle=annually', retry = 0;

        var services = [
          {title:'512M 月',url:'/cart.php?a=add&pid=92'},
          {title:'512M 年' , url:'/cart.php?a=add&pid=92&billingcycle=annually'},
          {title:'1G 月', url:'/cart.php?a=add&pid=93'},
          {title:'1G 年', url:'/cart.php?a=add&pid=93&billingcycle=annually'}
        ];

        var current;
        var storage = window.localStorage;

        function init(){
          var html = '';
          for(var i in services){
            html += '
<button id="__c_%id" onclick="window.dig(%id)" class="btn btn-success" id="checkout">%title</button>
'.replace(/%id/g,i).replace(/%title/g,services[i].title)
          }

          $('.top-nav').prepend(html);

          if(location.search.indexOf('auto')>=0){
            var pid = storage['PID'];
            if(pid){
              check(parseInt(pid))
            }
          }
        }

        function process(){
          current.prop('disabled',true).html('运行中('+ retry++ +')');

          $.get(link).then(function(resp){
            if(resp.indexOf('Out of Stock')>=0){
              setTimeout(process, 3000);
            }else{
              location.href = link;
            }
          },function(){
            setTimeout(process, 3000);
          });
        }

        function check(id){
          current = $('#__c_'+id);
          storage['PID'] = id
          current.prop('disabled',true).html('运行中('+ retry++ +')');
          link = services[parseInt(id)].url;
          process();
        }

        init();

        return check;
      }(jQuery));

      window.dig = dig;
    }
    if($('.view-cart-empty').length){
      nw.addScript(';(' + script + '());', 'body');
    }else{
      setTimeout(function(){
        location.href = 'cart.php?a=checkout';
        // $('#checkout').click();
      },100);
    }

  }
});

nw.c({
  rule: /einstein\.enoctus\.co\.uk\/cart\.php\?a=checkout/,
  pre: function() {},
  post: function() {
    setTimeout(function(){
      // $('#checkout').click();
      $("input[name='paymentmethod'][value='paypal']").attr("checked",'checked');
      $('.radio-inline').eq(1).click();
      $("#accepttos").attr("checked", true);
      $('#btnCompleteOrder').click();

      // automatically removed from the cart
      setTimeout(function(){
        location.href = 'cart.php?a=view&auto=1';
      },20*1000);
    },100);
  }
});

//==================================
nw.init();
<|endoftext|>


<commit_before>// require mongoose
var mongoose = require('mongoose')
	, Schema = mongoose.Schema;

// new Schema
var UserSchema = Schema({
	username: {
		type: String,
		required: true,
		unique: true // make sure the username is not repeated again
	},
	password: {
		type: String,
		required: true
	}
});

// use the above schema to make the User model
var User = mongoose.model('User', UserSchema);

// export the model so the server can use it
module.exports = User;<commit_msg>adds coins property :heavy_dollar_sign:<commit_after>// require mongoose
var mongoose = require('mongoose')
	, Schema = mongoose.Schema;

// new Schema
var UserSchema = Schema({
	username: {
		type: String,
		required: true,
		unique: true // make sure the username is not repeated again
	},
	password: {
		type: String,
		required: true
	},
	coins: {
    pennies: { type: Number, default: 0 },
		nickels: { type: Number, default: 0 },
    dimes:  { type: Number, default: 0 },
		quarters: { type: Number, default: 0 }
  }
});

// use the above schema to make the User model
var User = mongoose.model('User', UserSchema);

// export the model so the server can use it
module.exports = User;
<|endoftext|>


<commit_before>import {
    ClVariable,
    CL,
    ClAbstractVariable,
    ClDummyVariable,
    ClEditConstraint,
    ClEditInfo,
    ClEditOrStayConstraint,
    ClLinearConstraint, ClLinearEquation, ClLinearExpression,
    ClLinearInequality, ClConstraint, ClPoint, ClSimplexSolver,
    ClSlackVariable, ClStayConstraint, ClStrength, ClObjectiveVariable,
    ExCLConstraintNotFound, ExCLError, ExCLNonlinearExpression, ExCLInternalError,
    ExCLNotEnoughStays, ExCLRequiredFailure, ExCLTooDifficult, Timer
}  from '../lib/dwarfcassowary/dwarfcassowary.js';
import * as Cassowary from '../lib/dwarfcassowary/dwarfcassowary.js';
Cassowary; // TODO: this keeps rollup from tree-shaking away our import reference to Cassowary
import trigger from 'aexpr-trigger';

describe('Cassowary', function() {
    beforeEach(() => Cassowary.ClSimplexSolver.resetInstance());

    it('two-way data binding', function() {
        let a = 2,
            constraintVarA = new Cassowary.ClVariable('a', a);

        expect(a).to.equal(constraintVarA._value);

        // Two-way data binding
        aexpr(() => a).onChange(val => constraintVarA.set_value(val));
        aexpr(() => constraintVarA.value()).onChange(val => a = val);

        expect(a).to.equal(constraintVarA._value);

        a = 10;

        expect(a).to.equal(10);
        expect(a).to.equal(constraintVarA._value);

        constraintVarA._value = 20;

        expect(a).to.equal(20);
        expect(a).to.equal(constraintVarA._value);
    });

    describe('system integration', function() {
        // understanding the library API
        it('manual usage of solver library', function() {
            let a = 2, b = 3, c = 5;

            let solver = Cassowary.ClSimplexSolver.getInstance();

            // a
            let constraintVarA = new Cassowary.ClVariable('a', a);

            // b
            let constraintVarB = new Cassowary.ClVariable('b', b);

            /*
             * Initial Constraint Solving
             */
            //always: 2 * a == b;
            let linearEquation = constraintVarA.times(2).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation);

            solver.solveConstraints();

            expect(constraintVarA.value()).not.to.equal(0);
            expect(constraintVarB.value()).not.to.equal(0);
            expect(2 * constraintVarA.value()).to.equal(constraintVarB.value());

            /*
             * Assignment to A
             */
            constraintVarA.set_value(10);
            constraintVarA.suggestValue(10);

            expect(constraintVarA.value()).to.equal(10);
            expect(constraintVarB.value()).not.to.equal(0);
            expect(2 * constraintVarA.value()).to.equal(constraintVarB.value());

            // c
            let constraintVarC = new Cassowary.ClVariable('c', c);

            /*
             * Second Constraint
             */
            let linearEquation2 = constraintVarA.plus(constraintVarC).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation2);
            solver.solveConstraints();

            expect(constraintVarA.value()).not.to.equal(0);
            expect(constraintVarB.value()).not.to.equal(0);
            expect(constraintVarC.value()).not.to.equal(0);
            expect(2 * constraintVarA.value()).to.equal(constraintVarB.value());
            expect(constraintVarA.value() + constraintVarC.value()).to.equal(constraintVarB.value());

            /*
             * Assignment to B
             */
            constraintVarB.set_value(3000);
            constraintVarB.suggestValue(3000);

            expect(constraintVarB.value()).to.equal(3000);
            expect(2 * constraintVarA.value()).to.equal(constraintVarB.value());
            expect(constraintVarA.value() + constraintVarC.value()).to.equal(constraintVarB.value());
        });

        // identify, what the source transformation should do
        it('mimicing rewriter', function() {
            let a = 2, b = 3, c = 5;

            let solver = Cassowary.ClSimplexSolver.getInstance();

            // a
            let constraintVarA = new Cassowary.ClVariable('a', a);
            solver._constraintVariablesByVariables.set('a', constraintVarA);
            aexpr(() => a).onChange(val => constraintVarA.set_value(val));
            aexpr(() => constraintVarA.value()).onChange(val => a = val);

            // b
            let constraintVarB = new Cassowary.ClVariable('b', b);
            solver._constraintVariablesByVariables.set('b', constraintVarB);
            aexpr(() => b).onChange(val => constraintVarB.set_value(val));
            aexpr(() => constraintVarB.value()).onChange(val => b = val);

            /*
             * Initial Constraint Solving
             */
            console.log('BEFORE INITIAL CONSTRAINT CONSTRUCTION',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b
            );
            //always: 2 * a == b;
            let linearEquation = constraintVarA.times(2).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation);

            trigger(aexpr(() => 2 * constraintVarA.value() == constraintVarB.value()))
                .onBecomeFalse(() => solver.solveConstraints());

            expect(a).not.to.equal(0);
            expect(b).not.to.equal(0);
            expect(2 * a).to.equal(b);

            console.log('AFTER INITIAL CONSTRAINT CONSTRUCTION',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b
            );

            /*
             * Assignment to A
             */
            console.log('ASSIGNMENT TO A',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b
            );
            a = 10;
            //constraintVarA.suggestValue(10);
            //solver.solveConstraints();

            expect(a).to.equal(10);
            expect(b).not.to.equal(0);
            expect(2 * a).to.equal(b);

            /*
             * Second Constraint
             */
            // c
            let constraintVarC = new Cassowary.ClVariable('c', c);
            solver._constraintVariablesByVariables.set('c', constraintVarC);
            aexpr(() => c).onChange(val => constraintVarC.set_value(val));
            aexpr(() => constraintVarC.value()).onChange(val => c = val);

            console.log('SECOND CONSTRAINT',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b,
                constraintVarC.toString(), c
            );
            let linearEquation2 = constraintVarA.plus(constraintVarC).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation2);
            trigger(aexpr(() => constraintVarA.value() + constraintVarC.value() == constraintVarB.value()))
                .onBecomeFalse(() => solver.solveConstraints());

            console.log('SECOND CONSTRAINT AFTER SOLVING',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b,
                constraintVarC.toString(), c
            );
            expect(a).not.to.equal(0);
            expect(b).not.to.equal(0);
            expect(c).not.to.equal(0);
            expect(2 * a).to.equal(b);
            expect(a + c).to.equal(b);

            /*
             * Assignment to B
             */
            b = 3000;
            //constraintVarB.suggestValue(3000);
            //solver.solveConstraints();

            console.log('ASSIGNMENT TO B',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b,
                constraintVarC.toString(), c
            );
            expect(b).to.equal(3000);
            expect(2 * a).to.equal(b);
            expect(a + c).to.equal(b);
        });

        // using the source transformation
        it('test applying rewriter', function() {
            let a = 2, b = 3, c = 5;

            always: 2 * a == b;

            expect(a).not.to.equal(0);
            expect(b).not.to.equal(0);
            expect(2 * a).to.equal(b);

            a = 10;

            expect(a).to.equal(10);
            expect(b).not.to.equal(0);
            expect(2 * a).to.equal(b);

            always: a + c == b;

            expect(a).not.to.equal(0);
            expect(b).not.to.equal(0);
            expect(c).not.to.equal(0);
            expect(2 * a).to.equal(b);
            expect(a + c).to.equal(b);

            b = 3000;

            expect(b).to.equal(3000);
            expect(2 * a).to.equal(b);
            expect(a + c).to.equal(b);
        });
    });

    ClVariable,
        CL,
        ClAbstractVariable,
        ClDummyVariable,
        ClEditConstraint,
        ClEditInfo,
        ClEditOrStayConstraint,
        ClLinearConstraint, ClLinearEquation, ClLinearExpression,
        ClLinearInequality, ClConstraint, ClPoint, ClSimplexSolver,
        ClSlackVariable, ClStayConstraint, ClStrength, ClObjectiveVariable,
        ExCLConstraintNotFound, ExCLError, ExCLNonlinearExpression, ExCLInternalError,
        ExCLNotEnoughStays, ExCLRequiredFailure, ExCLTooDifficult, Timer;

    // TODO: same variables in different scopes
    xit('involve multiple constraints', function() {
        let _scope = {};
        let a = 2, b = 3;

        //always: 2 * a == b;
        {
            let solver = Cassowary.ClSimplexSolver.getInstance();

            // a
            let constraintVarA = solver.getConstraintVariableFor(_scope, 'a', () => {
                let _constraintVar = new Cassowary.ClVariable('a', a);
                aexpr(() => a).onChange(val => _constraintVar.set_value(val));
                aexpr(() => _constraintVar.value()).onChange(val => a = val);
                return _constraintVar;
            });

            // global b
            let constraintVarB = solver.getConstraintVariableFor(_scope, 'b', () => {
                let _constraintVar = new Cassowary.ClVariable('b', b);
                aexpr(() => b).onChange(val => _constraintVar.set_value(val));
                aexpr(() => _constraintVar.value()).onChange(val => b = val);
                return _constraintVar;
            });

            console.log(
                a, constraintVarA.value(), constraintVarA._lastValue,
                b, constraintVarB.value(), constraintVarB._lastValue
            );

            let linearEquation = constraintVarA.times(2).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation);

            console.log(
                a, constraintVarA.value(), constraintVarA._lastValue,
                b, constraintVarB.value(), constraintVarB._lastValue
            );

            trigger(aexpr(() => 2 * constraintVarA.value() == constraintVarB.value()))
                .onBecomeFalse(() => {
                    if (!solver.__solving__) {
                        solver.__solving__ = true;
                        solver.addAssignmentConstraints();

                        try {
                            solver.solveConstraints();
                        } finally {
                            solver.__solving__ = false;
                            solver.removeAssignmentConstraints();
                        }
                    }
                });
            expect(2 * a).to.equal(b);

            console.log(
                a, constraintVarA.value(), constraintVarA._lastValue,
                b, constraintVarB.value(), constraintVarB._lastValue
            );
            a = 15;
            console.log(
                a, constraintVarA.value(), constraintVarA._lastValue,
                b, constraintVarB.value(), constraintVarB._lastValue
            );

            expect(a).to.equal(15);
            expect(2 * a).to.equal(b);
        }

        let getLocalB, getLocalC, setLocalC;
        {
            //always: a + __b__ == 2 * c
            let _scope2 = {};
            let b = 10, c = 20;
            getLocalB = () => b;
            getLocalC = () => c;
            setLocalC = val => c = val;
            {
                let solver = Cassowary.ClSimplexSolver.getInstance();

                // a
                let constraintVarA = solver.getConstraintVariableFor(_scope, 'a', () => {
                    let _constraintVar = new Cassowary.ClVariable('a', a);
                    aexpr(() => a).onChange(val => _constraintVar.set_value(val));
                    aexpr(() => _constraintVar.value()).onChange(val => a = val);
                    return _constraintVar;
                });

                // local b
                let constraintVarB = solver.getConstraintVariableFor(_scope2, 'b', () => {
                    let _constraintVar = new Cassowary.ClVariable('b', b);
                    aexpr(() => b).onChange(val => _constraintVar.set_value(val));
                    aexpr(() => _constraintVar.value()).onChange(val => b = val);
                    return _constraintVar;
                });

                // c
                let constraintVarC = solver.getConstraintVariableFor(_scope2, 'c', () => {
                    let _constraintVar = new Cassowary.ClVariable('c', c);
                    aexpr(() => c).onChange(val => _constraintVar.set_value(val));
                    aexpr(() => _constraintVar.value()).onChange(val => c = val);
                    return _constraintVar;
                });

                let linearEquation = constraintVarA.plus(constraintVarB).cnEquals(constraintVarC.times(2));
                solver.addConstraint(linearEquation);

                trigger(aexpr(() => constraintVarA.value() + constraintVarB.value() == 2 * constraintVarC.value()))
                    .onBecomeFalse(() => {
                        if (!solver.__solving__) {
                            solver.__solving__ = true;

                            try {
                                solver.solveConstraints();
                            } finally {
                                solver.__solving__ = false;
                            }
                        }
                    });
            }
        }

        //console.log(a, b, getLocalB(), getLocalC());
        expect(2 * a).to.equal(b);
        expect(a + getLocalB()).to.equal(2 * getLocalC());

        a = 10;

        //console.log(a, b, getLocalB(), getLocalC());
        expect(2 * a).to.equal(b);
        expect(a + getLocalB()).to.equal(2 * getLocalC());

        setLocalC(100);

        //console.log(a, b, getLocalB(), getLocalC());
        expect(2 * a).to.equal(b);
        expect(a + getLocalB()).to.equal(2 * getLocalC());
    });

    it('two constraints with assignment', function() {
        var a = 2, b = 3, c = 10;

        always: 2 * a + 3 * b == c;
        expect(2 * a + 3 * b).to.equal(c);

        always: 2 * a == b;
        expect(2 * a + 3 * b).to.equal(c);
        expect(2 * a).to.equal(b);

        c = 42;
        expect(2 * a + 3 * b).to.equal(c);
        expect(2 * a).to.equal(b);
    });

    it('rewrite test with assignment', function() {
        var a = 2, b = 3, c = 10;

        always: 2 * a + 3 * b == c;
        expect(2 * a + 3 * b).to.equal(c);

        c = 42;
        expect(2 * a + 3 * b).to.equal(c);
    });
});
<commit_msg>added expected results<commit_after>import {
    ClVariable,
    CL,
    ClAbstractVariable,
    ClDummyVariable,
    ClEditConstraint,
    ClEditInfo,
    ClEditOrStayConstraint,
    ClLinearConstraint, ClLinearEquation, ClLinearExpression,
    ClLinearInequality, ClConstraint, ClPoint, ClSimplexSolver,
    ClSlackVariable, ClStayConstraint, ClStrength, ClObjectiveVariable,
    ExCLConstraintNotFound, ExCLError, ExCLNonlinearExpression, ExCLInternalError,
    ExCLNotEnoughStays, ExCLRequiredFailure, ExCLTooDifficult, Timer
}  from '../lib/dwarfcassowary/dwarfcassowary.js';
import * as Cassowary from '../lib/dwarfcassowary/dwarfcassowary.js';
Cassowary; // TODO: this keeps rollup from tree-shaking away our import reference to Cassowary
import trigger from 'aexpr-trigger';

describe('Cassowary', function() {
    beforeEach(() => Cassowary.ClSimplexSolver.resetInstance());

    it('two-way data binding', function() {
        let a = 2,
            constraintVarA = new Cassowary.ClVariable('a', a);

        expect(a).to.equal(constraintVarA._value);

        // Two-way data binding
        aexpr(() => a).onChange(val => constraintVarA.set_value(val));
        aexpr(() => constraintVarA.value()).onChange(val => a = val);

        expect(a).to.equal(constraintVarA._value);

        a = 10;

        expect(a).to.equal(10);
        expect(a).to.equal(constraintVarA._value);

        constraintVarA._value = 20;

        expect(a).to.equal(20);
        expect(a).to.equal(constraintVarA._value);
    });

    describe('system integration', function() {
        // understanding the library API
        it('manual usage of solver library', function() {
            let a = 2, b = 3, c = 5;

            let solver = Cassowary.ClSimplexSolver.getInstance();

            // a
            let constraintVarA = new Cassowary.ClVariable('a', a);

            // b
            let constraintVarB = new Cassowary.ClVariable('b', b);

            /*
             * Initial Constraint Solving
             */
            //always: 2 * a == b;
            let linearEquation = constraintVarA.times(2).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation);

            solver.solveConstraints();

            expect(constraintVarA.value()).not.to.equal(0);
            expect(constraintVarB.value()).not.to.equal(0);
            expect(2 * constraintVarA.value()).to.equal(constraintVarB.value());

            /*
             * Assignment to A
             */
            constraintVarA.set_value(10);
            constraintVarA.suggestValue(10);

            expect(constraintVarA.value()).to.equal(10);
            expect(constraintVarB.value()).not.to.equal(0);
            expect(2 * constraintVarA.value()).to.equal(constraintVarB.value());

            // c
            let constraintVarC = new Cassowary.ClVariable('c', c);

            /*
             * Second Constraint
             */
            let linearEquation2 = constraintVarA.plus(constraintVarC).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation2);
            solver.solveConstraints();

            expect(constraintVarA.value()).not.to.equal(0);
            expect(constraintVarB.value()).not.to.equal(0);
            expect(constraintVarC.value()).not.to.equal(0);
            expect(2 * constraintVarA.value()).to.equal(constraintVarB.value());
            expect(constraintVarA.value() + constraintVarC.value()).to.equal(constraintVarB.value());

            /*
             * Assignment to B
             */
            constraintVarB.set_value(3000);
            constraintVarB.suggestValue(3000);

            expect(constraintVarB.value()).to.equal(3000);
            expect(2 * constraintVarA.value()).to.equal(constraintVarB.value());
            expect(constraintVarA.value() + constraintVarC.value()).to.equal(constraintVarB.value());
        });

        // identify, what the source transformation should do
        it('mimicing rewriter', function() {
            let a = 2, b = 3, c = 5;

            let solver = Cassowary.ClSimplexSolver.getInstance();

            // a
            let constraintVarA = new Cassowary.ClVariable('a', a);
            solver._constraintVariablesByVariables.set('a', constraintVarA);
            aexpr(() => a).onChange(val => constraintVarA.set_value(val));
            aexpr(() => constraintVarA.value()).onChange(val => a = val);

            // b
            let constraintVarB = new Cassowary.ClVariable('b', b);
            solver._constraintVariablesByVariables.set('b', constraintVarB);
            aexpr(() => b).onChange(val => constraintVarB.set_value(val));
            aexpr(() => constraintVarB.value()).onChange(val => b = val);

            /*
             * Initial Constraint Solving
             */
            console.log('BEFORE INITIAL CONSTRAINT CONSTRUCTION',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b
            );
            //always: 2 * a == b;
            let linearEquation = constraintVarA.times(2).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation);

            trigger(aexpr(() => 2 * constraintVarA.value() == constraintVarB.value()))
                .onBecomeFalse(() => solver.solveConstraints());

            expect(a).not.to.equal(0);
            expect(b).not.to.equal(0);
            expect(2 * a).to.equal(b);

            console.log('AFTER INITIAL CONSTRAINT CONSTRUCTION',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b
            );

            /*
             * Assignment to A
             */
            console.log('ASSIGNMENT TO A',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b
            );
            a = 10;
            //constraintVarA.suggestValue(10);
            //solver.solveConstraints();

            expect(a).to.equal(10);
            expect(b).not.to.equal(0);
            expect(2 * a).to.equal(b);

            /*
             * Second Constraint
             */
            // c
            let constraintVarC = new Cassowary.ClVariable('c', c);
            solver._constraintVariablesByVariables.set('c', constraintVarC);
            aexpr(() => c).onChange(val => constraintVarC.set_value(val));
            aexpr(() => constraintVarC.value()).onChange(val => c = val);

            console.log('SECOND CONSTRAINT',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b,
                constraintVarC.toString(), c
            );
            let linearEquation2 = constraintVarA.plus(constraintVarC).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation2);
            trigger(aexpr(() => constraintVarA.value() + constraintVarC.value() == constraintVarB.value()))
                .onBecomeFalse(() => solver.solveConstraints());

            console.log('SECOND CONSTRAINT AFTER SOLVING',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b,
                constraintVarC.toString(), c
            );
            expect(a).not.to.equal(0);
            expect(b).not.to.equal(0);
            expect(c).not.to.equal(0);
            expect(2 * a).to.equal(b);
            expect(a + c).to.equal(b);

            /*
             * Assignment to B
             */
            b = 3000;
            //constraintVarB.suggestValue(3000);
            //solver.solveConstraints();

            console.log('ASSIGNMENT TO B',
                constraintVarA.toString(), a,
                constraintVarB.toString(), b,
                constraintVarC.toString(), c
            );
            expect(b).to.equal(3000);
            expect(2 * a).to.equal(b);
            expect(a + c).to.equal(b);
        });

        // using the source transformation
        it('test applying rewriter', function() {
            let a = 2, b = 3, c = 5;

            always: 2 * a == b; // a = 1.5, b = 3

            expect(a).not.to.equal(0);
            expect(b).not.to.equal(0);
            expect(2 * a).to.equal(b);

            a = 10; // a = 10, b = 20

            expect(a).to.equal(10);
            expect(b).not.to.equal(0);
            expect(2 * a).to.equal(b);

            always: a + c == b; // a = 10, b = 20, c = 10

            expect(a).not.to.equal(0);
            expect(b).not.to.equal(0);
            expect(c).not.to.equal(0);
            expect(2 * a).to.equal(b);
            expect(a + c).to.equal(b);

            b = 3000; // a = 1500, b = 3000, c = 1500

            expect(b).to.equal(3000);
            expect(2 * a).to.equal(b);
            expect(a + c).to.equal(b);
        });
    });

    ClVariable,
        CL,
        ClAbstractVariable,
        ClDummyVariable,
        ClEditConstraint,
        ClEditInfo,
        ClEditOrStayConstraint,
        ClLinearConstraint, ClLinearEquation, ClLinearExpression,
        ClLinearInequality, ClConstraint, ClPoint, ClSimplexSolver,
        ClSlackVariable, ClStayConstraint, ClStrength, ClObjectiveVariable,
        ExCLConstraintNotFound, ExCLError, ExCLNonlinearExpression, ExCLInternalError,
        ExCLNotEnoughStays, ExCLRequiredFailure, ExCLTooDifficult, Timer;

    // TODO: same variables in different scopes
    xit('involve multiple constraints', function() {
        let _scope = {};
        let a = 2, b = 3;

        //always: 2 * a == b;
        {
            let solver = Cassowary.ClSimplexSolver.getInstance();

            // a
            let constraintVarA = solver.getConstraintVariableFor(_scope, 'a', () => {
                let _constraintVar = new Cassowary.ClVariable('a', a);
                aexpr(() => a).onChange(val => _constraintVar.set_value(val));
                aexpr(() => _constraintVar.value()).onChange(val => a = val);
                return _constraintVar;
            });

            // global b
            let constraintVarB = solver.getConstraintVariableFor(_scope, 'b', () => {
                let _constraintVar = new Cassowary.ClVariable('b', b);
                aexpr(() => b).onChange(val => _constraintVar.set_value(val));
                aexpr(() => _constraintVar.value()).onChange(val => b = val);
                return _constraintVar;
            });

            console.log(
                a, constraintVarA.value(), constraintVarA._lastValue,
                b, constraintVarB.value(), constraintVarB._lastValue
            );

            let linearEquation = constraintVarA.times(2).cnEquals(constraintVarB);
            solver.addConstraint(linearEquation);

            console.log(
                a, constraintVarA.value(), constraintVarA._lastValue,
                b, constraintVarB.value(), constraintVarB._lastValue
            );

            trigger(aexpr(() => 2 * constraintVarA.value() == constraintVarB.value()))
                .onBecomeFalse(() => {
                    if (!solver.__solving__) {
                        solver.__solving__ = true;
                        solver.addAssignmentConstraints();

                        try {
                            solver.solveConstraints();
                        } finally {
                            solver.__solving__ = false;
                            solver.removeAssignmentConstraints();
                        }
                    }
                });
            expect(2 * a).to.equal(b);

            console.log(
                a, constraintVarA.value(), constraintVarA._lastValue,
                b, constraintVarB.value(), constraintVarB._lastValue
            );
            a = 15;
            console.log(
                a, constraintVarA.value(), constraintVarA._lastValue,
                b, constraintVarB.value(), constraintVarB._lastValue
            );

            expect(a).to.equal(15);
            expect(2 * a).to.equal(b);
        }

        let getLocalB, getLocalC, setLocalC;
        {
            //always: a + __b__ == 2 * c
            let _scope2 = {};
            let b = 10, c = 20;
            getLocalB = () => b;
            getLocalC = () => c;
            setLocalC = val => c = val;
            {
                let solver = Cassowary.ClSimplexSolver.getInstance();

                // a
                let constraintVarA = solver.getConstraintVariableFor(_scope, 'a', () => {
                    let _constraintVar = new Cassowary.ClVariable('a', a);
                    aexpr(() => a).onChange(val => _constraintVar.set_value(val));
                    aexpr(() => _constraintVar.value()).onChange(val => a = val);
                    return _constraintVar;
                });

                // local b
                let constraintVarB = solver.getConstraintVariableFor(_scope2, 'b', () => {
                    let _constraintVar = new Cassowary.ClVariable('b', b);
                    aexpr(() => b).onChange(val => _constraintVar.set_value(val));
                    aexpr(() => _constraintVar.value()).onChange(val => b = val);
                    return _constraintVar;
                });

                // c
                let constraintVarC = solver.getConstraintVariableFor(_scope2, 'c', () => {
                    let _constraintVar = new Cassowary.ClVariable('c', c);
                    aexpr(() => c).onChange(val => _constraintVar.set_value(val));
                    aexpr(() => _constraintVar.value()).onChange(val => c = val);
                    return _constraintVar;
                });

                let linearEquation = constraintVarA.plus(constraintVarB).cnEquals(constraintVarC.times(2));
                solver.addConstraint(linearEquation);

                trigger(aexpr(() => constraintVarA.value() + constraintVarB.value() == 2 * constraintVarC.value()))
                    .onBecomeFalse(() => {
                        if (!solver.__solving__) {
                            solver.__solving__ = true;

                            try {
                                solver.solveConstraints();
                            } finally {
                                solver.__solving__ = false;
                            }
                        }
                    });
            }
        }

        //console.log(a, b, getLocalB(), getLocalC());
        expect(2 * a).to.equal(b);
        expect(a + getLocalB()).to.equal(2 * getLocalC());

        a = 10;

        //console.log(a, b, getLocalB(), getLocalC());
        expect(2 * a).to.equal(b);
        expect(a + getLocalB()).to.equal(2 * getLocalC());

        setLocalC(100);

        //console.log(a, b, getLocalB(), getLocalC());
        expect(2 * a).to.equal(b);
        expect(a + getLocalB()).to.equal(2 * getLocalC());
    });

    it('two constraints with assignment', function() {
        var a = 2, b = 3, c = 10;

        always: 2 * a + 3 * b == c;
        expect(2 * a + 3 * b).to.equal(c);

        always: 2 * a == b;
        expect(2 * a + 3 * b).to.equal(c);
        expect(2 * a).to.equal(b);

        c = 42;
        expect(2 * a + 3 * b).to.equal(c);
        expect(2 * a).to.equal(b);
    });

    it('rewrite test with assignment', function() {
        var a = 2, b = 3, c = 10;

        always: 2 * a + 3 * b == c;
        expect(2 * a + 3 * b).to.equal(c);

        c = 42;
        expect(2 * a + 3 * b).to.equal(c);
    });
});
<|endoftext|>


<commit_before>require('proof')(34, require('cadence/redux')(prove))

function prove (async, assert) {
    var Semblance = require('semblance'),
        UserAgent = require('../..'),
        Bouquet = require('../../net/bouquet'),
        Binder = require('../../net/binder'),
        http = require('http'),
        pems = require('../../http/pems')

    var pseudo = new Semblance,
        bouquet = new Bouquet,
        ua = new UserAgent,
        binder

    var server = http.createServer(pseudo.dispatch()), request
    async(function () {
        var ua = new UserAgent(false)
        async(function () {
            ua.fetch({
                url: 'http://127.0.0.1:9999/here',
            }, async())
        }, function (body, response) {
            assert(response.statusCode, 599, 'no logging refused status')
        })
    }, function () {
        server.listen(7779, '127.0.0.1', async())
    }, function () {
        ua.fetch({
            url: 'http://127.0.0.1:9999/here',
        }, async())
    }, function (body, response) {
        assert(response.statusCode, 599, 'refused status')
        assert(response.errno, 'ECONNREFUSED', 'refused errno')
        assert(body, { message: 'connect ECONNREFUSED', errno: 'ECONNREFUSED' }, 'refused body')
        ua.fetch({
            url: 'http://127.0.0.1:9999/here',
        }, async())
    }, function (body, response, buffer) {
        assert(response.statusCode, 599, 'unparsed refused status')
        assert(response.errno, 'ECONNREFUSED', 'unparsed refused errno')
        assert(buffer.toString(),
            JSON.stringify({ message: 'connect ECONNREFUSED', errno: 'ECONNREFUSED' }), 'unparsed refused body')
        ua.fetch({
            grant: 'cc',
            url: 'http://a:z@127.0.0.1:9999/here',
        }, async())
    }, function (body, response, buffer) {
        assert(response.statusCode, 599, 'unparsed refused cc status')
        assert(response.errno, 'ECONNREFUSED', 'unparsed refused cc errno')
        assert(buffer.toString(), JSON.stringify({
            message: 'connect ECONNREFUSED',
            errno: 'ECONNREFUSED'
        }), 'unparsed refused cc body')
        pseudo.push({ delay: 1000 })
        ua.fetch({
            url: 'http://127.0.0.1:7779/here',
            timeout: 250
        }, async())
    }, function (body, response) {
        assert(response.statusCode, 599, 'timeout status')
        assert(response.errno, 'ECONNRESET', 'timeout errno')
        assert(body, { message: 'socket hang up', errno: 'ECONNRESET' }, 'timeout body')
        pseudo.clear()
        ua.fetch({
            url: 'http://127.0.0.1:7779/here'
        }, {
            method: 'GET',
            url: '/there?1'
        }, async())
    }, function () {
        assert(pseudo.shift(), {
            method: 'GET',
            headers: {
                accept: 'application/json',
                host: '127.0.0.1:7779',
                connection: 'keep-alive'
            },
            url: '/there?1',
            body: {}
        }, 'get')
        pseudo.clear()
        ua.fetch([{
            url: 'http://127.0.0.1:7779/here'
        }, {
            method: 'GET',
            url: '/there?1'
        }], async())
    }, function () {
        assert(pseudo.shift(), {
            method: 'GET',
            headers: {
                accept: 'application/json',
                host: '127.0.0.1:7779',
                connection: 'keep-alive'
            },
            url: '/there?1',
            body: {}
        }, 'get array override')
        pseudo.push({ payload: {} })
        ua.fetch({
            url: 'http://127.0.0.1:7779/here'
        }, {
            method: 'GET',
            url: '/there'
        }, async())
    }, function (body, response, buffer) {
        assert(buffer.toString(), '{}\n', 'unparsed')
    }, function () {
        pseudo.clear()
        ua.fetch({
            url: 'http://127.0.0.1:7779/here'
        }, {
            url: '/there',
            payload: { a: 1 }
        }, {
            headers: {
                greeting: 'Hello, World!'
            }
        }, async())
    }, function () {
        assert(pseudo.shift(), {
            method: 'POST',
            headers: {
                'content-type': 'application/json',
                'content-length': '7',
                accept: 'application/json',
                host: '127.0.0.1:7779',
                greeting: 'Hello, World!',
                connection: 'keep-alive'
            },
            url: '/there',
            body: { a: 1 }
        }, 'post')
        pseudo.push({
            headers: {},
            payload: 'Hello, World!'
        })
        ua.fetch({
            url: 'http://127.0.0.1:7779/here'
        }, {
            method: 'GET',
            url: '/there'
        }, async())
    }, function () {
        assert(pseudo.shift().headers['content-type'] == null, 'null content-type')
        pseudo.push({
            statusCode: 200,
            headers: {
                'content-type': 'text/plain'
            },
            payload: 'Hello, World!'
        })
        ua.fetch({ url: 'http://127.0.0.1:7779' }, async())
    }, function (body, response) {
        assert(body.toString(), 'Hello, World!', 'text')
        assert(response.headers['content-type'], 'text/plain', 'text content-type')
        pseudo.push({
            statusCode: 200,
            headers: {
                'content-type': 'text/html'
            },
            payload: 'Hello, World!'
        })
        ua.fetch({ url: 'http://127.0.0.1:7779' }, async())
    }, function (body, response) {
        assert(body.toString(), 'Hello, World!', 'html')
        assert(response.headers['content-type'], 'text/html', 'html content-type')
        pseudo.push({
            statusCode: 200,
            headers: {
                'content-type': 'application/octet-stream'
            },
            payload: 'Hello, World!'
        })
        ua.fetch({ url: 'http://127.0.0.1:7779' }, async())
    }, function (body, response) {
        assert(body.toString(), 'Hello, World!', 'unknown')
        assert(response.headers['content-type'], 'application/octet-stream', 'unknown content-type')
        pseudo.push({ statusCode: 401 })
        ua.fetch({
            url: 'http://a:z@127.0.0.1:7779/here'
        }, {
            grant: 'cc',
            url: '/there',
        }, async())
    }, function (body, response) {
        assert(response.statusCode, 401, 'bad authentication')
        pseudo.clear()
        pseudo.push({
            payload: {
                token_type: 'Bearer',
                access_token: 'x'
            }
        })
        ua.fetch({
            url: 'http://a:z@127.0.0.1:7779/here'
        }, {
            grant: 'cc',
            url: '/there',
        }, async())
    }, function (body, response) {
        assert(response.statusCode, 200, 'good authentication')
        assert(pseudo.shift(), {
            method: 'POST',
            headers: {
                authorization: 'Basic YTp6',
                'content-type': 'application/json',
                accept: 'application/json',
                'content-length': '35',
                host: '127.0.0.1:7779',
                connection: 'keep-alive'
            },
            url: '/token',
            body: { grant_type: 'client_credentials' }
        }, 'token request')
        assert(pseudo.shift(), {
            method: 'GET',
            headers: {
                accept: 'application/json',
                authorization: 'Bearer x',
                host: '127.0.0.1:7779',
                connection: 'keep-alive'
            },
            url: '/there',
            body: {}
        }, 'request with token')
    }, function () {
        server.close(async())
    }, function () {
// SSL!
        binder = [
            { url: 'https://127.0.0.1:7779' }, pems
        ]
        server = require('https').createServer(pems, pseudo.dispatch())
        server.listen(7779, '127.0.0.1', async())
    }, function () {
        ua.fetch(binder, async())
    }, function (body, response) {
        assert(response.statusCode, 200, 'https code')
        assert(body, { message: 'Hello, World!' }, 'https body')
        pseudo.clear()
        ua.fetch({ url: 'https://www.google.com/' }, async())
    }, function (body, response) {
        assert(response.statusCode, 200, 'https fetch without pinned CA')
        ua.fetch(binder, { agent: false }, async())
    }, function () {
        assert(pseudo.shift().headers.connection, 'close', 'connection close')
    }, function () {
        server.close(async())
    }, function () {
        server = require('https').createServer({
            ca:                 pems.ca,
            key:                pems.key,
            cert:               pems.cert,
            requestCert:        true,
            rejectUnauthorized: true
        }, pseudo.dispatch())
        server.listen(7779, '127.0.0.1', async())
    }, function () {
        ua.fetch({
            url: 'https://127.0.0.1:7779',
            ca: pems.ca
        }, { agent: false }, async())
    }, function (body, response) {
        assert(response.statusCode, 599, 'TLS client authentication failed')
        ua.fetch(binder, pems, { agent: false }, async())
    }, function (body, response) {
        assert(response.statusCode, 200, 'TLS client authentication succeeded')
        server.close(async())
    })
}
<commit_msg>Invoke construction of certificates.<commit_after>require('../proof')(34, require('cadence/redux')(prove))

function prove (async, assert) {
    var Semblance = require('semblance'),
        UserAgent = require('../..'),
        Bouquet = require('../../net/bouquet'),
        Binder = require('../../net/binder'),
        http = require('http'),
        pems = require('../../http/pems')

    var pseudo = new Semblance,
        bouquet = new Bouquet,
        ua = new UserAgent,
        binder

    var server = http.createServer(pseudo.dispatch()), request
    async(function () {
        var ua = new UserAgent(false)
        async(function () {
            ua.fetch({
                url: 'http://127.0.0.1:9999/here',
            }, async())
        }, function (body, response) {
            assert(response.statusCode, 599, 'no logging refused status')
        })
    }, function () {
        server.listen(7779, '127.0.0.1', async())
    }, function () {
        ua.fetch({
            url: 'http://127.0.0.1:9999/here',
        }, async())
    }, function (body, response) {
        assert(response.statusCode, 599, 'refused status')
        assert(response.errno, 'ECONNREFUSED', 'refused errno')
        assert(body, { message: 'connect ECONNREFUSED', errno: 'ECONNREFUSED' }, 'refused body')
        ua.fetch({
            url: 'http://127.0.0.1:9999/here',
        }, async())
    }, function (body, response, buffer) {
        assert(response.statusCode, 599, 'unparsed refused status')
        assert(response.errno, 'ECONNREFUSED', 'unparsed refused errno')
        assert(buffer.toString(),
            JSON.stringify({ message: 'connect ECONNREFUSED', errno: 'ECONNREFUSED' }), 'unparsed refused body')
        ua.fetch({
            grant: 'cc',
            url: 'http://a:z@127.0.0.1:9999/here',
        }, async())
    }, function (body, response, buffer) {
        assert(response.statusCode, 599, 'unparsed refused cc status')
        assert(response.errno, 'ECONNREFUSED', 'unparsed refused cc errno')
        assert(buffer.toString(), JSON.stringify({
            message: 'connect ECONNREFUSED',
            errno: 'ECONNREFUSED'
        }), 'unparsed refused cc body')
        pseudo.push({ delay: 1000 })
        ua.fetch({
            url: 'http://127.0.0.1:7779/here',
            timeout: 250
        }, async())
    }, function (body, response) {
        assert(response.statusCode, 599, 'timeout status')
        assert(response.errno, 'ECONNRESET', 'timeout errno')
        assert(body, { message: 'socket hang up', errno: 'ECONNRESET' }, 'timeout body')
        pseudo.clear()
        ua.fetch({
            url: 'http://127.0.0.1:7779/here'
        }, {
            method: 'GET',
            url: '/there?1'
        }, async())
    }, function () {
        assert(pseudo.shift(), {
            method: 'GET',
            headers: {
                accept: 'application/json',
                host: '127.0.0.1:7779',
                connection: 'keep-alive'
            },
            url: '/there?1',
            body: {}
        }, 'get')
        pseudo.clear()
        ua.fetch([{
            url: 'http://127.0.0.1:7779/here'
        }, {
            method: 'GET',
            url: '/there?1'
        }], async())
    }, function () {
        assert(pseudo.shift(), {
            method: 'GET',
            headers: {
                accept: 'application/json',
                host: '127.0.0.1:7779',
                connection: 'keep-alive'
            },
            url: '/there?1',
            body: {}
        }, 'get array override')
        pseudo.push({ payload: {} })
        ua.fetch({
            url: 'http://127.0.0.1:7779/here'
        }, {
            method: 'GET',
            url: '/there'
        }, async())
    }, function (body, response, buffer) {
        assert(buffer.toString(), '{}\n', 'unparsed')
    }, function () {
        pseudo.clear()
        ua.fetch({
            url: 'http://127.0.0.1:7779/here'
        }, {
            url: '/there',
            payload: { a: 1 }
        }, {
            headers: {
                greeting: 'Hello, World!'
            }
        }, async())
    }, function () {
        assert(pseudo.shift(), {
            method: 'POST',
            headers: {
                'content-type': 'application/json',
                'content-length': '7',
                accept: 'application/json',
                host: '127.0.0.1:7779',
                greeting: 'Hello, World!',
                connection: 'keep-alive'
            },
            url: '/there',
            body: { a: 1 }
        }, 'post')
        pseudo.push({
            headers: {},
            payload: 'Hello, World!'
        })
        ua.fetch({
            url: 'http://127.0.0.1:7779/here'
        }, {
            method: 'GET',
            url: '/there'
        }, async())
    }, function () {
        assert(pseudo.shift().headers['content-type'] == null, 'null content-type')
        pseudo.push({
            statusCode: 200,
            headers: {
                'content-type': 'text/plain'
            },
            payload: 'Hello, World!'
        })
        ua.fetch({ url: 'http://127.0.0.1:7779' }, async())
    }, function (body, response) {
        assert(body.toString(), 'Hello, World!', 'text')
        assert(response.headers['content-type'], 'text/plain', 'text content-type')
        pseudo.push({
            statusCode: 200,
            headers: {
                'content-type': 'text/html'
            },
            payload: 'Hello, World!'
        })
        ua.fetch({ url: 'http://127.0.0.1:7779' }, async())
    }, function (body, response) {
        assert(body.toString(), 'Hello, World!', 'html')
        assert(response.headers['content-type'], 'text/html', 'html content-type')
        pseudo.push({
            statusCode: 200,
            headers: {
                'content-type': 'application/octet-stream'
            },
            payload: 'Hello, World!'
        })
        ua.fetch({ url: 'http://127.0.0.1:7779' }, async())
    }, function (body, response) {
        assert(body.toString(), 'Hello, World!', 'unknown')
        assert(response.headers['content-type'], 'application/octet-stream', 'unknown content-type')
        pseudo.push({ statusCode: 401 })
        ua.fetch({
            url: 'http://a:z@127.0.0.1:7779/here'
        }, {
            grant: 'cc',
            url: '/there',
        }, async())
    }, function (body, response) {
        assert(response.statusCode, 401, 'bad authentication')
        pseudo.clear()
        pseudo.push({
            payload: {
                token_type: 'Bearer',
                access_token: 'x'
            }
        })
        ua.fetch({
            url: 'http://a:z@127.0.0.1:7779/here'
        }, {
            grant: 'cc',
            url: '/there',
        }, async())
    }, function (body, response) {
        assert(response.statusCode, 200, 'good authentication')
        assert(pseudo.shift(), {
            method: 'POST',
            headers: {
                authorization: 'Basic YTp6',
                'content-type': 'application/json',
                accept: 'application/json',
                'content-length': '35',
                host: '127.0.0.1:7779',
                connection: 'keep-alive'
            },
            url: '/token',
            body: { grant_type: 'client_credentials' }
        }, 'token request')
        assert(pseudo.shift(), {
            method: 'GET',
            headers: {
                accept: 'application/json',
                authorization: 'Bearer x',
                host: '127.0.0.1:7779',
                connection: 'keep-alive'
            },
            url: '/there',
            body: {}
        }, 'request with token')
    }, function () {
        server.close(async())
    }, function () {
// SSL!
        binder = [
            { url: 'https://127.0.0.1:7779' }, pems
        ]
        server = require('https').createServer(pems, pseudo.dispatch())
        server.listen(7779, '127.0.0.1', async())
    }, function () {
        ua.fetch(binder, async())
    }, function (body, response) {
        assert(response.statusCode, 200, 'https code')
        assert(body, { message: 'Hello, World!' }, 'https body')
        pseudo.clear()
        ua.fetch({ url: 'https://www.google.com/' }, async())
    }, function (body, response) {
        assert(response.statusCode, 200, 'https fetch without pinned CA')
        ua.fetch(binder, { agent: false }, async())
    }, function () {
        assert(pseudo.shift().headers.connection, 'close', 'connection close')
    }, function () {
        server.close(async())
    }, function () {
        server = require('https').createServer({
            ca:                 pems.ca,
            key:                pems.key,
            cert:               pems.cert,
            requestCert:        true,
            rejectUnauthorized: true
        }, pseudo.dispatch())
        server.listen(7779, '127.0.0.1', async())
    }, function () {
        ua.fetch({
            url: 'https://127.0.0.1:7779',
            ca: pems.ca
        }, { agent: false }, async())
    }, function (body, response) {
        assert(response.statusCode, 599, 'TLS client authentication failed')
        ua.fetch(binder, pems, { agent: false }, async())
    }, function (body, response) {
        assert(response.statusCode, 200, 'TLS client authentication succeeded')
        server.close(async())
    })
}
<|endoftext|>


<commit_before>var builder = require('jest-trx-results-processor');

var processor = builder({
    outputFile: 'configurable.trx'
});

module.exports = processor;
<commit_msg>Improve exmaples<commit_after>var builder = require('jest-trx-results-processor');

var processor = builder({
    outputFile: 'relative/path/to/resulting.trx'
});

module.exports = processor;
<|endoftext|>


<commit_before>/**
 * Avalara © 2017
 * file: test/companies.spec.js
 */

import Avatax from '../';
import { account, licenseKey } from './test_creds';
import nock from 'nock';
import companyGetResponse from './fixtures/company_get_response';
import companiesListResponse from './fixtures/companies_list_response';

describe('Avatax Companies', () => {
  const baseUrl = 'https://sandbox-rest.avatax.com';
  const client = new Avatax({ account, licenseKey });

  describe('Get company by id', () => {
    const id = 12345;

    beforeEach(() => {
      nock(baseUrl).get(`/api/v2/companies/${id}`)
        .reply(200, companyGetResponse);
    });

    it('should return single company', () => {
      return client.getCompanyById({ id })
        .then( res => {
          console.log(JSON.stringify(res, null, 2));
          expect(res).toEqual(companyGetResponse);
        });
    });
  });

  describe('Listing companies for account', () => {

    beforeEach(() => {
      nock(baseUrl).get(`/api/v2/companies`)
        .reply(200, companiesListResponse);
    });

    it('should return list of companies', () => {
      return client.listCompanies()
        .then(res => {
          expect(res).toEqual(companiesListResponse);
        });
    });
  });
});

<commit_msg>remove console log<commit_after>/**
 * Avalara © 2017
 * file: test/companies.spec.js
 */

import Avatax from '../';
import { account, licenseKey } from './test_creds';
import nock from 'nock';
import companyGetResponse from './fixtures/company_get_response';
import companiesListResponse from './fixtures/companies_list_response';

describe('Avatax Companies', () => {
  const baseUrl = 'https://sandbox-rest.avatax.com';
  const client = new Avatax({ account, licenseKey });

  describe('Get company by id', () => {
    const id = 12345;

    beforeEach(() => {
      nock(baseUrl).get(`/api/v2/companies/${id}`)
        .reply(200, companyGetResponse);
    });

    it('should return single company', () => {
      return client.getCompanyById({ id })
        .then( res => {
          expect(res).toEqual(companyGetResponse);
        });
    });
  });

  describe('Listing companies for account', () => {

    beforeEach(() => {
      nock(baseUrl).get(`/api/v2/companies`)
        .reply(200, companiesListResponse);
    });

    it('should return list of companies', () => {
      return client.listCompanies()
        .then(res => {
          expect(res).toEqual(companiesListResponse);
        });
    });
  });
});

<|endoftext|>


<commit_before>'use strict';
var expect    = require('expect.js')
  , catchErr  = require('catch-error')
  , comparray = require('../index');

describe('comparray module', function(){

  /*
   * test for valid arguments
   */
  describe('when passing arrays as 1st and second arguments', function(){
    it('should return something', function(){
      // arrange
      var arg1 = [];
      var arg2 = [];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).not.to.be(undefined);
    });
  });

  describe('when passing anything other than an array as the 1st argument', function(){
    it('should throw an exception', function(){
      // arrange
      var arg1 = 'String';
      var arg2 = [];
      // act
      var result = catchErr({ func: comparray, args: [arg1, arg2] });
      // assert
      expect(result).to.be.an(Error);
    });
  });

  describe('when passing anything other than an array as the 2nd argument', function(){
    it('should throw an exception', function(){
      // arrange
      var arg1 = [];
      var arg2 = 'String';
      // act
      var result = catchErr({ func: comparray, args: [arg1, arg2] });
      // assert
      expect(result).to.be.an(Error);
    });
  });

  describe('when passing anything other than an object as the 3rd argument', function(){
    it('should throw an exception if 3rd arg is a string', function(){
      // arrange
      var arg1 = [];
      var arg2 = [];
      var arg3 = 'string';
      // act
      var result = catchErr({ func: comparray, args: [arg1, arg2, arg3] });
      // assert
      expect(result).to.be.an(Error);
    });
  });

  /*
   * test array comparision without optional 3rd argument
   */
  describe('when passing arrays as 1st and 2nd arguments without a 3rd argument', function(){
    it('should return true if the arrays have the same length', function(){
      // arrange
      var arg1 = [1,2];
      var arg2 = [1,2];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return false if the arrays have different lengths', function(){
      // arrange
      var arg1 = [1,2];
      var arg2 = [1,2,3];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(false);
    });
    it('should return false if the arrays have differing elements', function(){
      // arrange
      var arg1 = [1,2];
      var arg2 = [3,4];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(false);
    });
    it('should return true if the arrays have the same elements', function(){
      // arrange
      var arg1 = [1,2];
      var arg2 = [1,2];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return true if nested arrays have the same elements', function(){
      // arrange
      var arg1 = [1,2,[1,2]];
      var arg2 = [1,2,[1,2]];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return true if nested arrays have the same elements', function(){
      // arrange
      var arg1 = [1,2,[2,[3]]];
      var arg2 = [1,2,[2,[3]]];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return true if nested arrays have the same elements', function(){
      // arrange
      var arg1 = [1,[2,2],[3,[4]]];
      var arg2 = [1,[2,2],[3,[4]]];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return false if nested arrays have differing elements', function(){
      // arrange
      var arg1 = [1,2,[1,2]];
      var arg2 = [1,2,[3,4]];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(false);
    });
    it('should return true if matching elements are the same object', function(){
      // arrange
      var obj1 = {};
      var arg1 = [ 1, 2, obj1 ];
      var arg2 = [ 1, 2, obj1 ];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return false if matching elements are different objects', function(){
      // arrange
      var obj1 = {};
      var obj2 = {};
      var arg1 = [ 1, 2, obj1 ];
      var arg2 = [ 1, 2, obj2 ];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(false);
    });

    // test for comparing NaN with NaN
    describe('passing matching arrays with NaN elements in the same index', function(){
      it('should return true', function(){
        // arrange
        var arg1 = [1, 2, NaN, 4];
        var arg2 = [1, 2, NaN, 4];
        // act
        var result = comparray(arg1, arg2);
        // assert
        expect(result).to.be(true);
      });
    });

  });

  /*
   * test optional 3rd argument (option object)
   */
  describe('when passing arrays as 1st and 2nd arguments with a 3rd argument', function(){
    describe('if the arrays match and the third argument is an empty object', function(){
      it('should return true', function(){
        var arr1 = ['one', 'two'];
        var arr2 = ['one', 'two'];
        var obj  = {};
        var result = comparray(arr1, arr2, obj);
        expect(result).to.be(true);
      });
    });

    // test diff options
    describe('if the third argument contains the key show', function(){

      describe('with value: missing', function(){
        it('should return the elements in array1 that are not in array2', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['one', 'two'];
          var obj  = {
            show: 'missing'
          };
          var expected = ['three', 'four'];
          var result = comparray(arr1, arr2, obj);
          expect(result).to.eql(expected);
        });
      });

      describe('with value: common', function(){
        it('should return the elements in array1 that are also in array2', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['one', 'three', 'four', 'five'];
          var obj  = {
            show: 'common'
          };
          var expected = ['one', 'three', 'four'];
          var result = comparray(arr1, arr2, obj);
          expect(result).to.eql(expected);
        });
      });

      describe('with value: likeness', function(){
        it('should return a decimal fraction of elements common to both arrays', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['one', 'two'];
          var obj  = {
            show: 'likeness'
          };
          var expected = 0.5;
          var result = comparray(arr1, arr2, obj);
          expect(result).to.equal(expected);
        });
        it('should return a decimal fraction of elements common to both arrays', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['one', 'two', 'three'];
          var obj  = {
            show: 'likeness'
          };
          var expected = 0.75;
          var result = comparray(arr1, arr2, obj);
          expect(result).to.equal(expected);
        });
        it('should return a decimal fraction of elements common to both arrays', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['two'];
          var obj  = {
            show: 'likeness'
          };
          var expected = 0.25;
          var result = comparray(arr1, arr2, obj);
          expect(result).to.equal(expected);
        });
      });

    });
  });

});
<commit_msg>add test for arrays with different order<commit_after>'use strict';
var expect    = require('expect.js')
  , catchErr  = require('catch-error')
  , comparray = require('../index');

describe('comparray module', function(){

  /*
   * test for valid arguments
   */
  describe('when passing arrays as 1st and second arguments', function(){
    it('should return something', function(){
      // arrange
      var arg1 = [];
      var arg2 = [];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).not.to.be(undefined);
    });
  });

  describe('when passing anything other than an array as the 1st argument', function(){
    it('should throw an exception', function(){
      // arrange
      var arg1 = 'String';
      var arg2 = [];
      // act
      var result = catchErr({ func: comparray, args: [arg1, arg2] });
      // assert
      expect(result).to.be.an(Error);
    });
  });

  describe('when passing anything other than an array as the 2nd argument', function(){
    it('should throw an exception', function(){
      // arrange
      var arg1 = [];
      var arg2 = 'String';
      // act
      var result = catchErr({ func: comparray, args: [arg1, arg2] });
      // assert
      expect(result).to.be.an(Error);
    });
  });

  describe('when passing anything other than an object as the 3rd argument', function(){
    it('should throw an exception if 3rd arg is a string', function(){
      // arrange
      var arg1 = [];
      var arg2 = [];
      var arg3 = 'string';
      // act
      var result = catchErr({ func: comparray, args: [arg1, arg2, arg3] });
      // assert
      expect(result).to.be.an(Error);
    });
  });

  /*
   * test array comparision without optional 3rd argument
   */
  describe('when passing arrays as 1st and 2nd arguments without a 3rd argument', function(){
    it('should return true if the arrays have the same length', function(){
      // arrange
      var arg1 = [1,2];
      var arg2 = [1,2];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return false if the arrays have different lengths', function(){
      // arrange
      var arg1 = [1,2];
      var arg2 = [1,2,3];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(false);
    });
    it('should return false if the arrays have differing elements', function(){
      // arrange
      var arg1 = [1,2];
      var arg2 = [3,4];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(false);
    });
    it('should return true if the arrays have the same elements', function(){
      // arrange
      var arg1 = [1,2];
      var arg2 = [1,2];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return true if nested arrays have the same elements', function(){
      // arrange
      var arg1 = [1,2,[1,2]];
      var arg2 = [1,2,[1,2]];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return true if nested arrays have the same elements', function(){
      // arrange
      var arg1 = [1,2,[2,[3]]];
      var arg2 = [1,2,[2,[3]]];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return true if nested arrays have the same elements', function(){
      // arrange
      var arg1 = [1,[2,2],[3,[4]]];
      var arg2 = [1,[2,2],[3,[4]]];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return false if nested arrays have differing elements', function(){
      // arrange
      var arg1 = [1,2,[1,2]];
      var arg2 = [1,2,[3,4]];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(false);
    });
    it('should return true if matching elements are the same object', function(){
      // arrange
      var obj1 = {};
      var arg1 = [ 1, 2, obj1 ];
      var arg2 = [ 1, 2, obj1 ];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(true);
    });
    it('should return false if matching elements are different objects', function(){
      // arrange
      var obj1 = {};
      var obj2 = {};
      var arg1 = [ 1, 2, obj1 ];
      var arg2 = [ 1, 2, obj2 ];
      // act
      var result = comparray(arg1, arg2);
      // assert
      expect(result).to.be(false);
    });

    // test for comparing NaN with NaN
    describe('passing matching arrays with NaN elements in the same index', function(){
      it('should return true', function(){
        // arrange
        var arg1 = [1, 2, NaN, 4];
        var arg2 = [1, 2, NaN, 4];
        // act
        var result = comparray(arg1, arg2);
        // assert
        expect(result).to.be(true);
      });
    });

  });

  /*
   * test optional 3rd argument (option object)
   */
  describe('when passing arrays as 1st and 2nd arguments with a 3rd argument', function(){
    describe('if the arrays match and the third argument is an empty object', function(){
      it('should return true', function(){
        var arr1 = ['one', 'two'];
        var arr2 = ['one', 'two'];
        var obj  = {};
        var result = comparray(arr1, arr2, obj);
        expect(result).to.be(true);
      });
    });

    // test diff options
    describe('if the third argument contains the key show', function(){

      describe('with value: missing', function(){
        it('should return the elements in array1 that are not in array2', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['one', 'two'];
          var obj  = {
            show: 'missing'
          };
          var expected = ['three', 'four'];
          var result = comparray(arr1, arr2, obj);
          expect(result).to.eql(expected);
        });
      });

      describe('with value: common', function(){
        it('should return the elements in array1 that are also in array2', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['one', 'three', 'four', 'five'];
          var obj  = {
            show: 'common'
          };
          var expected = ['one', 'three', 'four'];
          var result = comparray(arr1, arr2, obj);
          expect(result).to.eql(expected);
        });
      });

      describe('with value: likeness', function(){
        it('should return a decimal fraction of elements common to both arrays', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['one', 'two'];
          var obj  = {
            show: 'likeness'
          };
          var expected = 0.5;
          var result = comparray(arr1, arr2, obj);
          expect(result).to.equal(expected);
        });
        it('should return a decimal fraction of elements common to both arrays', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['one', 'two', 'three'];
          var obj  = {
            show: 'likeness'
          };
          var expected = 0.75;
          var result = comparray(arr1, arr2, obj);
          expect(result).to.equal(expected);
        });
        it('should return a decimal fraction of elements common to both arrays', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['two'];
          var obj  = {
            show: 'likeness'
          };
          var expected = 0.25;
          var result = comparray(arr1, arr2, obj);
          expect(result).to.equal(expected);
        });
      });

    });

    describe('if the third argument contains the key order', function(){
      describe('with value false', function(){
        it('should return true if the arrays have the same elements regardless of order', function(){
          var arr1 = ['one', 'two', 'three', 'four'];
          var arr2 = ['three', 'one', 'four', 'two'];
          var obj = {
            order: false
          };
          var result = comparray(arr1, arr2, obj);
          expect(result).to.be(true);
        });
      });
    });
  });

});
<|endoftext|>