<commit_before>'use strict'

var test = require('tape')
var Flatten = require('./')

test('only flatten nested objects', function (t) {
  var flatten = Flatten()

  var obj = {
    number: 1,
    string: 'foo',
    bool: true,
    arr1: [1, 2, 3],
    arr2: [{ foo: 1 }, { bar: 2 }],
    sub: { foo: 1, bar: { baz: 3 } }
  }

  t.deepEqual(flatten(obj), {
    number: 1,
    string: 'foo',
    bool: true,
    arr1: [1, 2, 3],
    arr2: [{ foo: 1 }, { bar: 2 }],
    'sub.foo': 1,
    'sub.bar.baz': 3
  })

  t.end()
})

test('do not traverse black listed types', function (t) {
  var Klass = function () {
    this.foo = 1
  }
  var instance = new Klass()
  var flatten = Flatten({ blacklist: [Klass] })

  var obj = {
    a: {
      a: 1
    },
    b: {
      a: instance
    }
  }

  t.deepEqual(flatten(obj), {
    'a.a': 1,
    'b.a': instance
  })

  t.end()
})

test('support custom separator', function (t) {
  var obj = {
    sub: { foo: 1, bar: { baz: 3 } }
  }
  var flatten = Flatten({ separator: '_' })

  t.deepEqual(flatten(obj), {
    'sub_foo': 1,
    'sub_bar_baz': 3
  })

  t.end()
})

test('support empty string separator', function (t) {
  var obj = {
    sub: { foo: 1, bar: { baz: 3 } }
  }
  var flatten = Flatten({ separator: '' })

  t.deepEqual(flatten(obj), {
    'subfoo': 1,
    'subbarbaz': 3
  })

  t.end()
})

test('support no prefix', function (t) {
  var obj = {
    sub: { foo: 1, bar: { baz: 3 } }
  }
  var flatten = Flatten({ onlyLeaves: true })

  t.deepEqual(flatten(obj), {
    'foo': 1,
    'baz': 3
  })

  t.end()
})
<commit_msg>Code cleanup<commit_after>'use strict'

var test = require('tape')
var Flatten = require('./')

test('only flatten nested objects', function (t) {
  var flatten = Flatten()

  var obj = {
    number: 1,
    string: 'foo',
    bool: true,
    arr1: [1, 2, 3],
    arr2: [{ foo: 1 }, { bar: 2 }],
    sub: { foo: 1, bar: { baz: 3 } }
  }

  t.deepEqual(flatten(obj), {
    number: 1,
    string: 'foo',
    bool: true,
    arr1: [1, 2, 3],
    arr2: [{ foo: 1 }, { bar: 2 }],
    'sub.foo': 1,
    'sub.bar.baz': 3
  })

  t.end()
})

test('do not traverse black listed types', function (t) {
  var Klass = function () {
    this.foo = 1
  }
  var instance = new Klass()
  var flatten = Flatten({ blacklist: [Klass] })

  var obj = {
    a: {
      a: 1
    },
    b: {
      a: instance
    }
  }

  t.deepEqual(flatten(obj), {
    'a.a': 1,
    'b.a': instance
  })

  t.end()
})

test('support custom separator', function (t) {
  var obj = {
    sub: { foo: 1, bar: { baz: 3 } }
  }
  var flatten = Flatten({ separator: '_' })

  t.deepEqual(flatten(obj), {
    'sub_foo': 1,
    'sub_bar_baz': 3
  })

  t.end()
})

test('support empty string separator', function (t) {
  var obj = {
    sub: { foo: 1, bar: { baz: 3 } }
  }
  var flatten = Flatten({ separator: '' })

  t.deepEqual(flatten(obj), {
    'subfoo': 1,
    'subbarbaz': 3
  })

  t.end()
})

test('support no prefix', function (t) {
  var obj = {
    sub: { foo: 1, bar: { baz: 3 } }
  }
  var flatten = Flatten({ onlyLeaves: true })

  t.deepEqual(flatten(obj), {
    foo: 1,
    baz: 3
  })

  t.end()
})
<|endoftext|>


<commit_before>/**
 * @file
 * JS Integration between CiviCRM & Stripe.
 */
(function($, CRM) {

  var $form, $submit, buttonText;
  var isWebform = false;

  // Response from Stripe.createToken.
  function stripeResponseHandler(status, response) {
    if (response.error) {
      $('html, body').animate({scrollTop: 0}, 300);
      // Show the errors on the form.
      if ($(".messages.crm-error.stripe-message").length > 0) {
        $(".messages.crm-error.stripe-message").slideUp();
        $(".messages.crm-error.stripe-message:first").remove();
      }
      $form.prepend('
'
      + 'Payment Error Response:'
      + '
'
      + '
Error: ' + response.error.message + '
'
      + '
'
      + '
');

      $submit.removeAttr('disabled').attr('value', buttonText);

    }
    else {
      var token = response['id'];
      // Update form with the token & submit.
      $form.find("input#stripe-token").val(token);
      $form.find("input#credit_card_number").removeAttr('name');
      $form.find("input#cvv2").removeAttr('name');
      $submit.prop('disabled', false);
      window.onbeforeunload = null;
      $form.get(0).submit();
    }
  }

  // Prepare the form.
  $(document).ready(function() {
    $.getScript('https://js.stripe.com/v2/', function () {
      Stripe.setPublishableKey($('#stripe-pub-key').val());
    });

    if ($('.webform-client-form').length) {
      isWebform = true;
      $('form.webform-client-form').addClass('stripe-payment-form');
    }
    else {
      if (!($('.stripe-payment-form').length)) {
        $('#crm-container > form').addClass('stripe-payment-form');
      }
    }
    $form   = $('form.stripe-payment-form');
    if (isWebform) {
      $submit = $form.find('.button-primary');
    }
    else {
      $submit = $form.find('input[type="submit"][formnovalidate!="1"]');

      // If CiviDiscount button or field is submitted, flag the form.
      $form.data('cividiscount-dont-handle', '0');
      $form.find('input[type="submit"][formnovalidate="1"]').click( function() {
        $form.data('cividiscount-dont-handle', 1);
      });
      $form.find('input#discountcode').keypress( function(e) {
        if (e.which == 13) {
          $form.data('cividiscount-dont-handle', 1);
        }
      });
      $submit;
    }

    // For CiviCRM Webforms.
    if (isWebform) {
      if (!($('#action').length)) {
        $form.append('<input type="hidden" name="op" id="action" />');
      }
      $(document).keypress(function(event) {
        if (event.which == 13) {
          event.preventDefault();
          $submit.click();
        }
      });
      $(":submit").click(function() {
        $('#action').val(this.value);
      });
      $('#billingcheckbox:input').hide();
      $('label[for="billingcheckbox"]').hide();

      var webformPrevious = $('input.webform-previous').first().val();
    }
    else {
      // This is native civicrm form - check for existing token.
      if ($form.find("input#stripe-token").val()) {
        $('.credit_card_info-group').hide();
        $('#billing-payment-block').append('<input type="button" value="Edit CC details" id="ccButton" />');
        $('#ccButton').click(function() {
          $('.credit_card_info-group').show();
          $('#ccButton').hide();
          $form.find('input#stripe-token').val('');
        });
      }
    }

    $submit.removeAttr('onclick');

    $form.unbind('submit');

    // Intercept form submission.
    $form.submit(function (event) {
      // Don't handle submits generated by the CiviDiscount button.
      if ($form.data('cividiscount-dont-handle') == 1) {
        return true;
      }
      if (isWebform) {
        var $processorFields = $('.civicrm-enabled[name$="civicrm_1_contribution_1_contribution_payment_processor_id]"]');

        if ($('#action').attr('value') == webformPrevious) {
          return true;
        }
        if ($('#wf-crm-billing-total').length) {
          if ($('#wf-crm-billing-total').data('data-amount') == '0') {
            return true;
          }
        }
        if ($processorFields.length) {
          if ($processorFields.filter(':checked').val() == '0') {
            return true;
          }
          if (!($form.find('input[name="stripe_token"]').length)) {
            return true;
          }
        }
      }
      // Disable the submit button to prevent repeated clicks, cache button text, restore if Stripe returns error
      buttonText = $submit.attr('value');
      $submit.prop('disabled', true).attr('value', 'Processing');

      // Hide payment if total is 0 and no more participants.
      if ($('#priceset').length) {
        additionalParticipants = cj("#additional_participants").val();
        // The currentTotal is already being calculated in Form/Contribution/Main.tpl.
        if(typeof currentTotal !== 'undefined') {
          if (currentTotal == 0 && !additionalParticipants) {
            // This is also hit when "Going back", but we already have stripe_token.
            return true;
          }
        }
      }

      // Handle multiple payment options and Stripe not being chosen.
      if ($form.find(".crm-section.payment_processor-section").length > 0) {
        if ($form.find('input[name="payment_processor"]:checked').length) {
          processorId=$form.find('input[name="payment_processor"]:checked').val();
          if (!($form.find('input[name="stripe_token"]').length) || ($('#stripe-id').length && $('#stripe-id').val() != processorId)) {
            return true;
          }
        }
        else {
          // No payment processor is checked.
          return true;
        }
      }

      // Handle pay later (option value '0' in payment_processor radio group).
      if ($form.find('input[name="payment_processor"]:checked').length && !parseInt($form.find('input[name="payment_processor"]:checked').val())) {
        return true;
      }

      // Handle reuse of existing token
      if ($form.find("input#stripe-token").val()) {
        $form.find("input#credit_card_number").removeAttr('name');
        $form.find("input#cvv2").removeAttr('name');
        return true;
      }

      event.preventDefault();
      event.stopPropagation();

      // Handle changes introduced in CiviCRM 4.3.
      if ($form.find('#credit_card_exp_date_M').length > 0) {
        var cc_month = $form.find('#credit_card_exp_date_M').val();
        var cc_year = $form.find('#credit_card_exp_date_Y').val();
      }
      else {
        var cc_month = $form.find('#credit_card_exp_date\\[M\\]').val();
        var cc_year = $form.find('#credit_card_exp_date\\[Y\\]').val();
      }
      Stripe.card.createToken({
        name:        $form.find('#billing_first_name').val() + ' ' + $form.find('#billing_last_name').val(),
        address_zip: $form.find('#billing_postal_code-5').val(),
        number:      $form.find('#credit_card_number').val(),
        cvc:         $form.find('#cvv2').val(),
        exp_month:   cc_month,
        exp_year:    cc_year
      }, stripeResponseHandler);

      return false;
    });
  });
}(cj, CRM));
<commit_msg>Fixes #142 .  CiviCRM 4.7 changed radio selection of payment_processor to payment_processor_id.<commit_after>/**
 * @file
 * JS Integration between CiviCRM & Stripe.
 */
(function($, CRM) {

  var $form, $submit, buttonText;
  var isWebform = false;

  // Response from Stripe.createToken.
  function stripeResponseHandler(status, response) {
    if (response.error) {
      $('html, body').animate({scrollTop: 0}, 300);
      // Show the errors on the form.
      if ($(".messages.crm-error.stripe-message").length > 0) {
        $(".messages.crm-error.stripe-message").slideUp();
        $(".messages.crm-error.stripe-message:first").remove();
      }
      $form.prepend('
'
      + 'Payment Error Response:'
      + '
'
      + '
Error: ' + response.error.message + '
'
      + '
'
      + '
');

      $submit.removeAttr('disabled').attr('value', buttonText);

    }
    else {
      var token = response['id'];
      // Update form with the token & submit.
      $form.find("input#stripe-token").val(token);
      $form.find("input#credit_card_number").removeAttr('name');
      $form.find("input#cvv2").removeAttr('name');
      $submit.prop('disabled', false);
      window.onbeforeunload = null;
      $form.get(0).submit();
    }
  }

  // Prepare the form.
  $(document).ready(function() {
    $.getScript('https://js.stripe.com/v2/', function () {
      Stripe.setPublishableKey($('#stripe-pub-key').val());
    });

    if ($('.webform-client-form').length) {
      isWebform = true;
      $('form.webform-client-form').addClass('stripe-payment-form');
    }
    else {
      if (!($('.stripe-payment-form').length)) {
        $('#crm-container > form').addClass('stripe-payment-form');
      }
    }
    $form   = $('form.stripe-payment-form');
    if (isWebform) {
      $submit = $form.find('.button-primary');
    }
    else {
      $submit = $form.find('input[type="submit"][formnovalidate!="1"]');

      // If CiviDiscount button or field is submitted, flag the form.
      $form.data('cividiscount-dont-handle', '0');
      $form.find('input[type="submit"][formnovalidate="1"]').click( function() {
        $form.data('cividiscount-dont-handle', 1);
      });
      $form.find('input#discountcode').keypress( function(e) {
        if (e.which == 13) {
          $form.data('cividiscount-dont-handle', 1);
        }
      });
      $submit;
    }

    // For CiviCRM Webforms.
    if (isWebform) {
      if (!($('#action').length)) {
        $form.append('<input type="hidden" name="op" id="action" />');
      }
      $(document).keypress(function(event) {
        if (event.which == 13) {
          event.preventDefault();
          $submit.click();
        }
      });
      $(":submit").click(function() {
        $('#action').val(this.value);
      });
      $('#billingcheckbox:input').hide();
      $('label[for="billingcheckbox"]').hide();

      var webformPrevious = $('input.webform-previous').first().val();
    }
    else {
      // This is native civicrm form - check for existing token.
      if ($form.find("input#stripe-token").val()) {
        $('.credit_card_info-group').hide();
        $('#billing-payment-block').append('<input type="button" value="Edit CC details" id="ccButton" />');
        $('#ccButton').click(function() {
          $('.credit_card_info-group').show();
          $('#ccButton').hide();
          $form.find('input#stripe-token').val('');
        });
      }
    }

    $submit.removeAttr('onclick');

    $form.unbind('submit');

    // Intercept form submission.
    $form.submit(function (event) {
      // Don't handle submits generated by the CiviDiscount button.
      if ($form.data('cividiscount-dont-handle') == 1) {
        return true;
      }
      if (isWebform) {
        var $processorFields = $('.civicrm-enabled[name$="civicrm_1_contribution_1_contribution_payment_processor_id]"]');

        if ($('#action').attr('value') == webformPrevious) {
          return true;
        }
        if ($('#wf-crm-billing-total').length) {
          if ($('#wf-crm-billing-total').data('data-amount') == '0') {
            return true;
          }
        }
        if ($processorFields.length) {
          if ($processorFields.filter(':checked').val() == '0') {
            return true;
          }
          if (!($form.find('input[name="stripe_token"]').length)) {
            return true;
          }
        }
      }
      // Disable the submit button to prevent repeated clicks, cache button text, restore if Stripe returns error
      buttonText = $submit.attr('value');
      $submit.prop('disabled', true).attr('value', 'Processing');

      // Hide payment if total is 0 and no more participants.
      if ($('#priceset').length) {
        additionalParticipants = cj("#additional_participants").val();
        // The currentTotal is already being calculated in Form/Contribution/Main.tpl.
        if(typeof currentTotal !== 'undefined') {
          if (currentTotal == 0 && !additionalParticipants) {
            // This is also hit when "Going back", but we already have stripe_token.
            return true;
          }
        }
      }

      // Handle multiple payment options and Stripe not being chosen.
      if ($form.find(".crm-section.payment_processor-section").length > 0) {
        if ($form.find('input[name="payment_processor_id"]:checked').length) {
          processorId=$form.find('input[name="payment_processor_id"]:checked').val();
          if (!($form.find('input[name="stripe_token"]').length) || ($('#stripe-id').length && $('#stripe-id').val() != processorId)) {
            return true;
          }
        }
        else {
          // No payment processor is checked.
          return true;
        }
      }

      // Handle pay later (option value '0' in payment_processor radio group).
      if ($form.find('input[name="payment_processor_id"]:checked').length && !parseInt($form.find('input[name="payment_processor_id"]:checked').val())) {
        return true;
      }

      // Handle reuse of existing token
      if ($form.find("input#stripe-token").val()) {
        $form.find("input#credit_card_number").removeAttr('name');
        $form.find("input#cvv2").removeAttr('name');
        return true;
      }

      event.preventDefault();
      event.stopPropagation();

      // Handle changes introduced in CiviCRM 4.3.
      if ($form.find('#credit_card_exp_date_M').length > 0) {
        var cc_month = $form.find('#credit_card_exp_date_M').val();
        var cc_year = $form.find('#credit_card_exp_date_Y').val();
      }
      else {
        var cc_month = $form.find('#credit_card_exp_date\\[M\\]').val();
        var cc_year = $form.find('#credit_card_exp_date\\[Y\\]').val();
      }
      Stripe.card.createToken({
        name:        $form.find('#billing_first_name').val() + ' ' + $form.find('#billing_last_name').val(),
        address_zip: $form.find('#billing_postal_code-5').val(),
        number:      $form.find('#credit_card_number').val(),
        cvc:         $form.find('#cvv2').val(),
        exp_month:   cc_month,
        exp_year:    cc_year
      }, stripeResponseHandler);

      return false;
    });
  });
}(cj, CRM));
<|endoftext|>


<commit_before>function Downloader() {
	this.isActive = false;
	this.realtime = false;
	this.chunkStart = 0;
	this.chunkSize = 0;
	this.totalLength = 0;
	this.chunkTimeout = 1000;
	this.url = null;
	this.callback = null;
}

Downloader.prototype.reset = function() {
	this.chunkStart = 0;
	this.totalLength = 0;
}

Downloader.prototype.setRealTime = function(_realtime) {
	this.realtime = _realtime;
}

Downloader.prototype.setChunkSize = function(_size) {
	this.chunkSize = _size;
}

Downloader.prototype.setChunkStart = function(_start) {
	this.chunkStart = _start;
}

Downloader.prototype.setInterval = function(_timeout) {
	this.chunkTimeout = _timeout;
}

Downloader.prototype.setUrl = function(_url) {
	this.url = _url;
}

Downloader.prototype.setCallback = function(_callback) {
	this.callback = _callback;
}

Downloader.prototype.isStopped = function () {
	return !this.isActive;
}

Downloader.prototype.getFileLength = function () {
	return this.totalLength;
}

Downloader.prototype.getFile = function() {
	var dl = this;
	if (this.chunkStart === Infinity) {
		Log.i("Downloader", "File download done.");
		this.callback(null, true);
		return;
	}
	var xhr = new XMLHttpRequest();
	xhr.open("GET", this.url, true);
	xhr.responseType = "arraybuffer";
	var range = null;
	xhr.start = this.chunkStart;
	var maxRange;
	if (this.chunkStart+this.chunkSize < Infinity) {
		range = 'bytes=' + this.chunkStart + '-';
		maxRange = this.chunkStart+this.chunkSize-1;
		/* if the file length is known we limit the max range to that length */
		/*if (dl.totalLength !== 0) {
			maxRange = Math.min(maxRange, dl.totalLength);
		}*/
		range += maxRange;
		xhr.setRequestHeader('Range', range);
	}
	xhr.onerror = function(e) {
		dl.callback(null, false, true);
	}
	xhr.onreadystatechange = function (e) {
		if ((xhr.status == 200 || xhr.status == 206 || xhr.status == 304 || xhr.status == 416) && xhr.readyState == this.DONE) {
			var rangeReceived = xhr.getResponseHeader("Content-Range");
			Log.i("Downloader", "Received data range: "+rangeReceived);
			/* if the length of the file is not known, we get it from the response header */
			if (!dl.totalLength) {
				var sizeIndex;
				sizeIndex = rangeReceived.indexOf("/");
				if (sizeIndex > -1) {
					dl.totalLength = +rangeReceived.slice(sizeIndex+1);
				}
			}
			var eof = (xhr.response.byteLength !== dl.chunkSize);
			xhr.response.fileStart = xhr.start;
			dl.callback(xhr.response, eof);
			//dl.chunkStart+=dl.chunkSize;
			if (dl.isActive === true && eof === false) {
				var timeoutDuration = 0;
				if (!dl.realtime) {
					timeoutDuration = dl.chunkTimeout;
				} else {
					timeoutDuration = computeWaitingTimeFromBuffer(video);
				}
				Log.i("Downloader", "Next download scheduled in "+timeoutDuration+ ' ms.');
				window.setTimeout(dl.getFile.bind(dl), timeoutDuration);
			} else {
				/* end of file */
			}
		}
	};
	Log.i("Downloader", "Fetching "+this.url+(range ? (" with range: "+range): ""));
	xhr.send();
}

Downloader.prototype.start = function() {
	Log.i("Downloader", "Starting file download");
	this.chunkStart = 0;
	this.resume();
}

Downloader.prototype.resume = function() {
	Log.i("Downloader", "Resuming file download");
	this.isActive = true;
	if (this.chunkSize === 0) {
		this.chunkSize = Infinity;
	}
	this.getFile();
}

Downloader.prototype.stop = function() {
	Log.i("Downloader", "Stopping file download");
	this.isActive = false;
}
<commit_msg>fix downloader when reaching end of file<commit_after>function Downloader() {
	this.isActive = false;
	this.realtime = false;
	this.chunkStart = 0;
	this.chunkSize = 0;
	this.totalLength = 0;
	this.chunkTimeout = 1000;
	this.url = null;
	this.callback = null;
	this.eof = false;
}

Downloader.prototype.reset = function() {
	this.chunkStart = 0;
	this.totalLength = 0;
}

Downloader.prototype.setRealTime = function(_realtime) {
	this.realtime = _realtime;
}

Downloader.prototype.setChunkSize = function(_size) {
	this.chunkSize = _size;
}

Downloader.prototype.setChunkStart = function(_start) {
	this.chunkStart = _start;
}

Downloader.prototype.setInterval = function(_timeout) {
	this.chunkTimeout = _timeout;
}

Downloader.prototype.setUrl = function(_url) {
	this.url = _url;
}

Downloader.prototype.setCallback = function(_callback) {
	this.callback = _callback;
}

Downloader.prototype.isStopped = function () {
	return !this.isActive;
}

Downloader.prototype.getFileLength = function () {
	return this.totalLength;
}

Downloader.prototype.getFile = function() {
	var dl = this;
	if (dl.eof === true) {
		Log.i("Downloader", "File download done.");
		this.callback(null, true);
		return;
	}
	var xhr = new XMLHttpRequest();
	xhr.open("GET", this.url, true);
	xhr.responseType = "arraybuffer";
	var range = null;
	xhr.start = this.chunkStart;
	var maxRange;
	if (this.chunkStart+this.chunkSize < Infinity) {
		range = 'bytes=' + this.chunkStart + '-';
		maxRange = this.chunkStart+this.chunkSize-1;
		/* if the file length is known we limit the max range to that length */
		/*if (dl.totalLength !== 0) {
			maxRange = Math.min(maxRange, dl.totalLength);
		}*/
		range += maxRange;
		xhr.setRequestHeader('Range', range);
	}
	xhr.onerror = function(e) {
		dl.callback(null, false, true);
	}
	xhr.onreadystatechange = function (e) {
		if ((xhr.status == 200 || xhr.status == 206 || xhr.status == 304 || xhr.status == 416) && xhr.readyState == this.DONE) {
			var rangeReceived = xhr.getResponseHeader("Content-Range");
			Log.i("Downloader", "Received data range: "+rangeReceived);
			/* if the length of the file is not known, we get it from the response header */
			if (!dl.totalLength) {
				var sizeIndex;
				sizeIndex = rangeReceived.indexOf("/");
				if (sizeIndex > -1) {
					dl.totalLength = +rangeReceived.slice(sizeIndex+1);
				}
			}
			dl.eof = (xhr.response.byteLength !== dl.chunkSize) || (xhr.response.byteLength === dl.totalLength);
			xhr.response.fileStart = xhr.start;
			dl.callback(xhr.response, dl.eof);
			//dl.chunkStart+=dl.chunkSize;
			if (dl.isActive === true && dl.eof === false) {
				var timeoutDuration = 0;
				if (!dl.realtime) {
					timeoutDuration = dl.chunkTimeout;
				} else {
					timeoutDuration = computeWaitingTimeFromBuffer(video);
				}
				Log.i("Downloader", "Next download scheduled in "+timeoutDuration+ ' ms.');
				window.setTimeout(dl.getFile.bind(dl), timeoutDuration);
			} else {
				/* end of file */
			}
		}
	};
	Log.i("Downloader", "Fetching "+this.url+(range ? (" with range: "+range): ""));
	xhr.send();
}

Downloader.prototype.start = function() {
	Log.i("Downloader", "Starting file download");
	this.chunkStart = 0;
	this.resume();
}

Downloader.prototype.resume = function() {
	Log.i("Downloader", "Resuming file download");
	this.isActive = true;
	if (this.chunkSize === 0) {
		this.chunkSize = Infinity;
	}
	this.getFile();
}

Downloader.prototype.stop = function() {
	Log.i("Downloader", "Stopping file download");
	this.isActive = false;
}
<|endoftext|>


<commit_before>'use strict';

var test = require('tape');
var m = require('mithril');
var render = require('./index');

test('render', function(t) {
  t.equal(render(m('span', 'content')),
    'content', 'should render tag');
  t.equal(render(m('.foo', 'content')),
    '
content
', 'should render classname');
  t.equal(render(m('#bar', 'content')),
    '
content
', 'should render id');
  t.equal(render(m('br')), '
', 'should render short nodes when no children');
  t.equal(render(m('HR')), '
', 'should render short nodes when no children and tag name is uppercase');
  t.equal(render(m('!doctype')), '<!doctype>',
    'should render short node doctype');
  t.equal(render(m('!doctype', {html: true})), '<!doctype html>',
    'should render short node doctype HTML5');
  t.equal(render(m('span', {
    'data-foo': 'bar',
    selected: 'selected'
  })), '', 'should render attributes');
  t.equal(render(m('ul', 'huhu')), '
huhu
', 'should render string');
  t.equal(render([m('span', 'foo'), m('div', 'bar')]),
    'foo
bar
', 'should render arrays');
  t.equal(render(m('span', m('div'))), '

', 'should render children');
  t.equal(render(m('span', {
    onmousemove: function(event) {}
  })), '', 'should not render events');
  t.equal(render(m('span', {
    style: {
      paddingLeft: '10px',
      color: 'red'
    }
  })), '', 'should render children');
  t.equal(render(m('div', [
    1,
    m('span'),
    "2"
  ])), '
12
', 'should render numbers as text nodes');
  t.equal(render(m('div', 0)), '
0
');
  t.equal(render(m('div', false)), '
false
');
  t.equal(render(m('div', { a: true})), '

');
  t.equal(render(m('div', { a: false})), '

');
  t.equal(render(m('div', { a: undefined})), '

');
  t.equal(render(m('div', { style: null })), '

');
  t.equal(render(m('div', { style: '' })), '

');
  t.equal(render(m('div', { style: { color: '' } })), '

');
  t.equal(render(m('div', { style: { height: '20px', color: '' } })), '

');
  t.equal(render(m('div', { style: { height: '20px', color: '', width: '10px' } })), '

');
  t.equal(render(m('div', { a: 'foo'})), '

');
  t.equal(render(m('div', m.trust('<foo></foo>'))), '
<foo></foo>
');
  t.equal(render(m('div', '<foo></foo>')), '
<foo></foo>
');
  t.equal(render(m('div', {
    style: '">

<div a="'
  }), { escapeAttributeValue: function(value) { return value; } }), '

');
  t.equal('function', typeof render.escapeHtml);
  t.equal(render(m('pre', 'var = ' + JSON.stringify({foo: 1}))), '
var = {"foo":1}
');
  t.equal(render(m('svg', m('use', { href : "fooga.com" }))), '<svg><use xlink:href="fooga.com"></use></svg>');
  t.end();
});

test('components', function(t) {
  var events = {};
  var myComponent = {
    controller: function(data) {
      return {
        foo: 'bar',
        onunload: events.onunload
      };
    },
    view: function(scope, data) {
      return m('div', [
        'hello',
        scope.foo,
        data
      ]);
    }
  };
  t.equal(render(m('div', myComponent)), '

hellobar

');
  events.onunload = t.end;
  t.equal(render(m('span', m.component(myComponent, 'baz'))), '
hellobarbaz
');
  t.equal(render(m('div', {
    controller: function() {
      this.foo = 'bar';
    },
    view: function(ctrl) {
      return m('span', ctrl.foo);
    }
  })), '
bar
');
  t.equal(render(m('div', {
    controller: function() {
    },
    view: function() {
      return m('span', 'huhu');
    }
  })), '
huhu
');
  t.equal(render(m('div', {
    view: function() {
      return m('span', 'huhu');
    }
  })), '
huhu
');
});
<commit_msg>Add test for component shorthand<commit_after>'use strict';

var test = require('tape');
var m = require('mithril');
var render = require('./index');

test('render', function(t) {
  t.equal(render(m('span', 'content')),
    'content', 'should render tag');
  t.equal(render(m('.foo', 'content')),
    '
content
', 'should render classname');
  t.equal(render(m('#bar', 'content')),
    '
content
', 'should render id');
  t.equal(render(m('br')), '
', 'should render short nodes when no children');
  t.equal(render(m('HR')), '
', 'should render short nodes when no children and tag name is uppercase');
  t.equal(render(m('!doctype')), '<!doctype>',
    'should render short node doctype');
  t.equal(render(m('!doctype', {html: true})), '<!doctype html>',
    'should render short node doctype HTML5');
  t.equal(render(m('span', {
    'data-foo': 'bar',
    selected: 'selected'
  })), '', 'should render attributes');
  t.equal(render(m('ul', 'huhu')), '
huhu
', 'should render string');
  t.equal(render([m('span', 'foo'), m('div', 'bar')]),
    'foo
bar
', 'should render arrays');
  t.equal(render(m('span', m('div'))), '

', 'should render children');
  t.equal(render(m('span', {
    onmousemove: function(event) {}
  })), '', 'should not render events');
  t.equal(render(m('span', {
    style: {
      paddingLeft: '10px',
      color: 'red'
    }
  })), '', 'should render children');
  t.equal(render(m('div', [
    1,
    m('span'),
    "2"
  ])), '
12
', 'should render numbers as text nodes');
  t.equal(render(m('div', 0)), '
0
');
  t.equal(render(m('div', false)), '
false
');
  t.equal(render(m('div', { a: true})), '

');
  t.equal(render(m('div', { a: false})), '

');
  t.equal(render(m('div', { a: undefined})), '

');
  t.equal(render(m('div', { style: null })), '

');
  t.equal(render(m('div', { style: '' })), '

');
  t.equal(render(m('div', { style: { color: '' } })), '

');
  t.equal(render(m('div', { style: { height: '20px', color: '' } })), '

');
  t.equal(render(m('div', { style: { height: '20px', color: '', width: '10px' } })), '

');
  t.equal(render(m('div', { a: 'foo'})), '

');
  t.equal(render(m('div', m.trust('<foo></foo>'))), '
<foo></foo>
');
  t.equal(render(m('div', '<foo></foo>')), '
<foo></foo>
');
  t.equal(render(m('div', {
    style: '">

<div a="'
  }), { escapeAttributeValue: function(value) { return value; } }), '

');
  t.equal('function', typeof render.escapeHtml);
  t.equal(render(m('pre', 'var = ' + JSON.stringify({foo: 1}))), '
var = {"foo":1}
');
  t.equal(render(m('svg', m('use', { href : "fooga.com" }))), '<svg><use xlink:href="fooga.com"></use></svg>');
  t.end();
});

test('components', function(t) {
  var events = {};
  var myComponent = {
    controller: function(data) {
      return {
        foo: 'bar',
        onunload: events.onunload
      };
    },
    view: function(scope, data) {
      return m('div', [
        'hello',
        scope.foo,
        data
      ]);
    }
  };
  t.equal(render(m('div', myComponent)), '

hellobar

');
  t.equal(render(m('span', m.component(myComponent, 'baz'))), '
hellobarbaz
');
  events.onunload = t.end;
  t.equal(render(m('span', m(myComponent, 'foz'))), '
hellobarfoz
');
  t.equal(render(m('div', {
    controller: function() {
      this.foo = 'bar';
    },
    view: function(ctrl) {
      return m('span', ctrl.foo);
    }
  })), '
bar
');
  t.equal(render(m('div', {
    controller: function() {
    },
    view: function() {
      return m('span', 'huhu');
    }
  })), '
huhu
');
  t.equal(render(m('div', {
    view: function() {
      return m('span', 'huhu');
    }
  })), '
huhu
');
});
<|endoftext|>


<commit_before>var dotEnv = require('dotenv').config();
var db = require("../modules/testDB");
var driver = require("../modules/driverManager");
var assert = require('assert');

// Point the driverManager DB reference to modules/testDB
// Note that the scope of the path is driverManager, NOT
// this file.
driver.setDB('./testDB');

describe('drivers', function(){

	// Remove everytihng from the drivers table after each test
	afterEach(function() {
			db.query("DELETE FROM driver;");
	});

	describe('#getAllDrivers()', function() {
		// Before the test, add 4 drivers
		before(function() {
				db.query("ALTER SEQUENCE driver_id_seq RESTART;");
				db.query("DELETE FROM driver;");
				var queryStr = "INSERT INTO driver (id, name, phone, late_count) VALUES ";
				queryStr += "('3213', 'Jane Smith','473-834-3847', 1), ('3735', 'Karl Marx','573-583-7586', 0), ('2749', 'Not Hitler','999-999-9999', 3), ('43', 'Not Jesus','4', 0);";
				return db.query(queryStr);
		});
		it('should get all drivers', function() {
			return driver.getAllDrivers()
			.then(function(res) {
				assert(res.rowCount == 4, 'Result should contain 4 drivers.');
			});
		});
	});

	describe('#getDriverByID()', function() {
		//Insert 42entries into the database, retrieve 1
		before(function() {
			db.query("ALTER SEQUENCE driver_id_seq RESTART;");
			db.query("DELETE FROM driver;");
			var queryStr = "INSERT INTO driver (name, phone, late_count) VALUES ('Not Hitler','999-999-9999', 3), ('Not Jesus','4', 0);";
			db.query(queryStr);
		});
		it('should return a driver by id', function() {
			return driver.getDriverByID('1')
			.then(function(res) {
				assert.deepEqual(res.rows[0], {
					id: '1',
					name: 'Not Hitler',
					phone: '999-999-9999',
					late_count:'3'
				});
			})
		});
	});

	describe('#addDriver()', function() {
		before(function() {
			db.query("ALTER SEQUENCE driver_id_seq RESTART;");
			return db.query("DELETE FROM driver;");
		});
		// Uses an assert.deepEqual to check JSON equality
		it('should add the driver', function() {
			return driver.addDriver('Karl Marx','573-583-7586', '0')
			.then(function(res) {
				assert.deepEqual({
					id: '1',
					name: 'Karl Marx',
					phone: '573-583-7586',
					late_count:'0'
				}, res.rows[0]);
			});
		});
	});

	describe('#updateDriver()', function() {
		//Insert 4 entries into the database
		before(function() {
			db.query("ALTER SEQUENCE driver_id_seq RESTART;");
			db.query("DELETE FROM driver;");
			var queryStr = "INSERT INTO driver (name, phone, late_count) VALUES ('Jane Smith','473-834-3847', 1), ('Karl Marx','573-583-7586', 0), ('Not Hitler','999-999-9999', 3), ('Not Jesus','4', 0)";
			return db.query(queryStr);
		});

		it('should update the driver Karl Marx to have a new name, number and late count', function() {
			return driver.updateDriver(2, "Joseph Stalin", "685-738-5375", 6)
			.then(function(res) {
				assert.deepEqual({
					id: 2,
					name: 'Joseph Stalin',
					phone: '685-738-5375',
					late_count: 6
				}, res.rows[0]);
			})
		});
	});

	describe('#removeDriver()', function() {
		//Insert 4 entries into the database
		before(function() {
			db.query("ALTER SEQUENCE driver_id_seq RESTART;");
			db.query("DELETE FROM driver;");
			var queryStr = "INSERT INTO driver (name, phone, late_count) VALUES ('Jane Smith','473-834-3847', 1), ('Karl Marx','573-583-7586', 0), ('Not Hitler','999-999-9999', 3), ('Not Jesus','4', 0)";
			return db.query(queryStr);
		});

		it('Should remove Karl Marx', function() {
			return driver.removeDriver(2)
			.then(function(res) {
				assert(res.rowCount == 1, 'Result should contain 3 drivers');
			})
		});
	});

});

<commit_msg>Fixed getDriverByID test intermittently passing<commit_after>var dotEnv = require('dotenv').config();
var db = require("../modules/testDB");
var driver = require("../modules/driverManager");
var assert = require('assert');

// Point the driverManager DB reference to modules/testDB
// Note that the scope of the path is driverManager, NOT
// this file.
driver.setDB('./testDB');

describe('drivers', function(){

	// Remove everytihng from the drivers table after each test
	afterEach(function() {
			db.query("DELETE FROM driver;");
	});

	describe('#getAllDrivers()', function() {
		// Before the test, add 4 drivers
		before(function() {
				db.query("ALTER SEQUENCE driver_id_seq RESTART;");
				db.query("DELETE FROM driver;");
				var queryStr = "INSERT INTO driver (id, name, phone, late_count) VALUES ";
				queryStr += "('3213', 'Jane Smith','473-834-3847', 1), ('3735', 'Karl Marx','573-583-7586', 0), ('2749', 'Not Hitler','999-999-9999', 3), ('43', 'Not Jesus','4', 0);";
				return db.query(queryStr);
		});
		it('should get all drivers', function() {
			return driver.getAllDrivers()
			.then(function(res) {
				assert(res.rowCount == 4, 'Result should contain 4 drivers.');
			});
		});
	});

	describe('#getDriverByID()', function() {
		//Insert 42entries into the database, retrieve 1
		before(function() {
			db.query("ALTER SEQUENCE driver_id_seq RESTART;");
			db.query("DELETE FROM driver;");
			var queryStr = "INSERT INTO driver (name, phone, late_count) VALUES ('Not Hitler','999-999-9999', 3), ('Not Jesus','4', 0);";
			return db.query(queryStr);
		});
		it('should return a driver by id', function() {
			return driver.getDriverByID(1)
			.then(function(res) {
				assert.deepEqual(res.rows[0], {
					id: 1,
					name: 'Not Hitler',
					phone: '999-999-9999',
					late_count:'3'
				});
			})
		});
	});

	describe('#addDriver()', function() {
		before(function() {
			db.query("ALTER SEQUENCE driver_id_seq RESTART;");
			return db.query("DELETE FROM driver;");
		});
		// Uses an assert.deepEqual to check JSON equality
		it('should add the driver', function() {
			return driver.addDriver('Karl Marx','573-583-7586', '0')
			.then(function(res) {
				assert.deepEqual({
					id: '1',
					name: 'Karl Marx',
					phone: '573-583-7586',
					late_count:'0'
				}, res.rows[0]);
			});
		});
	});

	describe('#updateDriver()', function() {
		//Insert 4 entries into the database
		before(function() {
			db.query("ALTER SEQUENCE driver_id_seq RESTART;");
			db.query("DELETE FROM driver;");
			var queryStr = "INSERT INTO driver (name, phone, late_count) VALUES ('Jane Smith','473-834-3847', 1), ('Karl Marx','573-583-7586', 0), ('Not Hitler','999-999-9999', 3), ('Not Jesus','4', 0)";
			return db.query(queryStr);
		});

		it('should update the driver Karl Marx to have a new name, number and late count', function() {
			return driver.updateDriver(2, "Joseph Stalin", "685-738-5375", 6)
			.then(function(res) {
				assert.deepEqual({
					id: 2,
					name: 'Joseph Stalin',
					phone: '685-738-5375',
					late_count: 6
				}, res.rows[0]);
			})
		});
	});

	describe('#removeDriver()', function() {
		//Insert 4 entries into the database
		before(function() {
			db.query("ALTER SEQUENCE driver_id_seq RESTART;");
			db.query("DELETE FROM driver;");
			var queryStr = "INSERT INTO driver (name, phone, late_count) VALUES ('Jane Smith','473-834-3847', 1), ('Karl Marx','573-583-7586', 0), ('Not Hitler','999-999-9999', 3), ('Not Jesus','4', 0)";
			return db.query(queryStr);
		});

		it('Should remove Karl Marx', function() {
			return driver.removeDriver(2)
			.then(function(res) {
				assert(res.rowCount == 3, 'Result should contain 3 drivers');
			})
		});
	});

});

<|endoftext|>


<commit_before>const fs    = require('fs')
    , path  = require('path')
    , os    = require('os')

var location = path.join(os.tmpdir(), 'level-test-' + process.pid + '.db')

module.exports = function (test, level, options) {
  options = options || {}

  test('test db open and use, level(location, cb)', function (t) {
    level(location, function (err, db) {
      t.notOk(err, 'no error')
      db.put('test1', 'success', function (err) {
        t.notOk(err, 'no error')
        db.close(t.end.bind(t))
      })
    })
  })

  test('test db open and use, level(location, options, cb)', function (t) {
    level(location, { createIfMissing: false, errorIfExists: false }, function (err, db) {
      t.notOk(err, 'no error')
      db.put('test2', 'success', function (err) {
        t.notOk(err, 'no error')
        db.close(t.end.bind(t))
      })
    })
  })

  if (!options.skipErrorIfExistsTest) {
    // should use existing options object
    test('test db open and use, level(location, options, cb) force error', function (t) {
      level(location, { errorIfExists: true }, function (err, db) {
        t.ok(err, 'got error opening existing db')
        t.notOk(db, 'no db')
        t.end()
      })
    })
  }

  test('test db open and use, db=level(location)', function (t) {
    var db = level(location)
    db.put('test3', 'success', function (err) {
      t.notOk(err, 'no error')
      db.close(t.end.bind(t))
    })
  })

  test('test db values', function (t) {
    var c  = 0
      , db = level(location)
      , setup = options.nonPersistent
          ? function (callback) {
              db.batch([
                  { type: 'put', key: 'test1', value: 'success' }
                , { type: 'put', key: 'test2', value: 'success' }
                , { type: 'put', key: 'test3', value: 'success' }
              ], callback)
            }
          : function (callback) { callback() }

    function read (err, value) {
      t.notOk(err, 'no error')
      t.equal(value, 'success')
      if (++c == 3)
        db.close(t.end.bind(t))
    }

    setup(function (err) {
      t.notOk(err, 'no error')
      db.get('test1', read)
      db.get('test2', read)
      db.get('test3', read)
    })
  })

  if (!options.skipRepairTest) {
    test('test repair', function (t) {
      t.plan(1)
      level.repair(location, function (err) {
        t.notOk(err, 'no error')
      })
    })
  }

  if (!options.skipDestroyTest) {
    test('test destroy', function (t) {
      t.plan(4)
      t.ok(fs.statSync(location).isDirectory(), 'sanity check, directory exists')
      t.ok(fs.existsSync(path.join(location, 'LOG')), 'sanity check, log exists')
      level.destroy(location, function (err) {
        t.notOk(err, 'no error')
        t.notOk(fs.existsSync(path.join(location, 'LOG')), 'db gone (mostly)')
      })
    })
  }
}<commit_msg>0.8 compatible tests<commit_after>const fs    = require('fs')
    , path  = require('path')

var location = path.join(__dirname, 'level-test-' + process.pid + '.db')

module.exports = function (test, level, options) {
  options = options || {}

  test('test db open and use, level(location, cb)', function (t) {
    level(location, function (err, db) {
      t.notOk(err, 'no error')
      db.put('test1', 'success', function (err) {
        t.notOk(err, 'no error')
        db.close(t.end.bind(t))
      })
    })
  })

  test('test db open and use, level(location, options, cb)', function (t) {
    level(location, { createIfMissing: false, errorIfExists: false }, function (err, db) {
      t.notOk(err, 'no error')
      db.put('test2', 'success', function (err) {
        t.notOk(err, 'no error')
        db.close(t.end.bind(t))
      })
    })
  })

  if (!options.skipErrorIfExistsTest) {
    // should use existing options object
    test('test db open and use, level(location, options, cb) force error', function (t) {
      level(location, { errorIfExists: true }, function (err, db) {
        t.ok(err, 'got error opening existing db')
        t.notOk(db, 'no db')
        t.end()
      })
    })
  }

  test('test db open and use, db=level(location)', function (t) {
    var db = level(location)
    db.put('test3', 'success', function (err) {
      t.notOk(err, 'no error')
      db.close(t.end.bind(t))
    })
  })

  test('test db values', function (t) {
    var c  = 0
      , db = level(location)
      , setup = options.nonPersistent
          ? function (callback) {
              db.batch([
                  { type: 'put', key: 'test1', value: 'success' }
                , { type: 'put', key: 'test2', value: 'success' }
                , { type: 'put', key: 'test3', value: 'success' }
              ], callback)
            }
          : function (callback) { callback() }

    function read (err, value) {
      t.notOk(err, 'no error')
      t.equal(value, 'success')
      if (++c == 3)
        db.close(t.end.bind(t))
    }

    setup(function (err) {
      t.notOk(err, 'no error')
      db.get('test1', read)
      db.get('test2', read)
      db.get('test3', read)
    })
  })

  if (!options.skipRepairTest) {
    test('test repair', function (t) {
      t.plan(1)
      level.repair(location, function (err) {
        t.notOk(err, 'no error')
      })
    })
  }

  if (!options.skipDestroyTest) {
    test('test destroy', function (t) {
      t.plan(4)
      t.ok(fs.statSync(location).isDirectory(), 'sanity check, directory exists')
      t.ok(fs.existsSync(path.join(location, 'LOG')), 'sanity check, log exists')
      level.destroy(location, function (err) {
        t.notOk(err, 'no error')
        t.notOk(fs.existsSync(path.join(location, 'LOG')), 'db gone (mostly)')
      })
    })
  }
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('mano').i18n.bind('User: Notifications');

exports.trigger = require('eregistrations/users/users');
exports.subject = _("M01 Your account in the service has been created");

exports.text = _("Email message greeting ${ fullName }") + "\n\n"
	+ _("M01 Account registration\n\n" + "Email: ${ email }") + "\n\n" +
	_("Email message signature") + "\n";

exports.resolveGetters = true;
exports.variables = {
	fullName: function () {
		return this.user.fullName;
	},
	email: function () {
		return this.user.email;
	}
};
<commit_msg>#915 fixed require<commit_after>'use strict';

var _ = require('mano').i18n.bind('User: Notifications');

exports.trigger = require('../users/users');
exports.subject = _("M01 Your account in the service has been created");

exports.text = _("Email message greeting ${ fullName }") + "\n\n"
	+ _("M01 Account registration\n\n" + "Email: ${ email }") + "\n\n" +
	_("Email message signature") + "\n";

exports.resolveGetters = true;
exports.variables = {
	fullName: function () {
		return this.user.fullName;
	},
	email: function () {
		return this.user.email;
	}
};
<|endoftext|>


<commit_before>import Vue from 'vue'
import { compile } from 'web/compiler'
import { getAndRemoveAttr } from 'compiler/helpers'

describe('compile options', () => {
  it('should be compiled', () => {
    const { render, staticRenderFns, errors } = compile(`

        <input type="text" v-model="msg" required max="8" v-validate:field1.group1.group2>

    `, {
        directives: {
          validate (el, dir) {
            if (dir.name === 'validate' && dir.arg) {
              el.validate = {
                field: dir.arg,
                groups: dir.modifiers ? Object.keys(dir.modifiers) : []
              }
            }
          }
        },
        modules: [{
          transformNode (el) {
            el.validators = el.validators || []
            const validators = ['required', 'min', 'max', 'pattern', 'maxlength', 'minlength']
            validators.forEach(name => {
              const rule = getAndRemoveAttr(el, name)
              if (rule !== undefined) {
                el.validators.push({ name, rule })
              }
            })
          },
          genData (el) {
            let data = ''
            if (el.validate) {
              data += `validate:${JSON.stringify(el.validate)},`
            }
            if (el.validators) {
              data += `validators:${JSON.stringify(el.validators)},`
            }
            return data
          },
          transformCode (el, code) {
            // check
            if (!el.validate || !el.validators) {
              return code
            }
            // setup validation result props
            const result = { dirty: false } // define something other prop
            el.validators.forEach(validator => {
              result[validator.name] = null
            })
            // generate code
            return `_c('validate',{props:{
          field:${JSON.stringify(el.validate.field)},
          groups:${JSON.stringify(el.validate.groups)},
          validators:${JSON.stringify(el.validators)},
          result:${JSON.stringify(result)},
          child:${code}}
        })`
          }
        }]
      })
    expect(render).not.toBeUndefined()
    expect(staticRenderFns).toEqual([])
    expect(errors).toEqual([])

    const renderFn = new Function(render)
    const vm = new Vue({
      data: {
        msg: 'hello'
      },
      components: {
        validate: {
          props: ['field', 'groups', 'validators', 'result', 'child'],
          render (h) {
            return this.child
          },
          computed: {
            valid () {
              let ret = true
              for (let i = 0; i > this.validators.length; i++) {
                const { name } = this.validators[i]
                if (!this.result[name]) {
                  ret = false
                  break
                }
              }
              return ret
            }
          },
          mounted () {
            // initialize validation
            const value = this.$el.value
            this.validators.forEach(validator => {
              const ret = this[validator.name](value, validator.rule)
              this.result[validator.name] = ret
            })
          },
          methods: {
            // something validators logic
            required (val) {
              return val.length > 0
            },
            max (val, rule) {
              return !(parseInt(val, 10) > parseInt(rule, 10))
            }
          }
        }
      },
      render: renderFn,
      staticRenderFns
    }).$mount()
    expect(vm.$el.innerHTML).toBe('<input type="text">')
    expect(vm.$children[0].valid).toBe(true)
  })

  it('should collect errors', () => {
    let compiled = compile('hello')
    expect(compiled.errors.length).toBe(1)
    expect(compiled.errors[0]).toContain('root element')

    compiled = compile('
{{ b++++ }}
')
    expect(compiled.errors.length).toBe(2)
    expect(compiled.errors[0]).toContain('Raw expression: v-if="a----"')
    expect(compiled.errors[1]).toContain('Raw expression: {{ b++++ }}')
  })
})
<commit_msg>chore: fix formatting<commit_after>import Vue from 'vue'
import { compile } from 'web/compiler'
import { getAndRemoveAttr } from 'compiler/helpers'

describe('compile options', () => {
  it('should be compiled', () => {
    const { render, staticRenderFns, errors } = compile(`

        <input type="text" v-model="msg" required max="8" v-validate:field1.group1.group2>

    `, {
      directives: {
        validate (el, dir) {
          if (dir.name === 'validate' && dir.arg) {
            el.validate = {
              field: dir.arg,
              groups: dir.modifiers ? Object.keys(dir.modifiers) : []
            }
          }
        }
      },
      modules: [
        {
          transformNode (el) {
            el.validators = el.validators || []
            const validators = ['required', 'min', 'max', 'pattern', 'maxlength', 'minlength']
            validators.forEach(name => {
              const rule = getAndRemoveAttr(el, name)
              if (rule !== undefined) {
                el.validators.push({ name, rule })
              }
            })
          },
          genData (el) {
            let data = ''
            if (el.validate) {
              data += `validate:${JSON.stringify(el.validate)},`
            }
            if (el.validators) {
              data += `validators:${JSON.stringify(el.validators)},`
            }
            return data
          },
          transformCode (el, code) {
            // check
            if (!el.validate || !el.validators) {
              return code
            }
            // setup validation result props
            const result = { dirty: false } // define something other prop
            el.validators.forEach(validator => {
              result[validator.name] = null
            })
            // generate code
            return `_c('validate',{props:{
              field:${JSON.stringify(el.validate.field)},
              groups:${JSON.stringify(el.validate.groups)},
              validators:${JSON.stringify(el.validators)},
              result:${JSON.stringify(result)},
              child:${code}}
            })`
          }
        }
      ]
    })
    expect(render).not.toBeUndefined()
    expect(staticRenderFns).toEqual([])
    expect(errors).toEqual([])

    const renderFn = new Function(render)
    const vm = new Vue({
      data: {
        msg: 'hello'
      },
      components: {
        validate: {
          props: ['field', 'groups', 'validators', 'result', 'child'],
          render (h) {
            return this.child
          },
          computed: {
            valid () {
              let ret = true
              for (let i = 0; i > this.validators.length; i++) {
                const { name } = this.validators[i]
                if (!this.result[name]) {
                  ret = false
                  break
                }
              }
              return ret
            }
          },
          mounted () {
            // initialize validation
            const value = this.$el.value
            this.validators.forEach(validator => {
              const ret = this[validator.name](value, validator.rule)
              this.result[validator.name] = ret
            })
          },
          methods: {
            // something validators logic
            required (val) {
              return val.length > 0
            },
            max (val, rule) {
              return !(parseInt(val, 10) > parseInt(rule, 10))
            }
          }
        }
      },
      render: renderFn,
      staticRenderFns
    }).$mount()
    expect(vm.$el.innerHTML).toBe('<input type="text">')
    expect(vm.$children[0].valid).toBe(true)
  })

  it('should collect errors', () => {
    let compiled = compile('hello')
    expect(compiled.errors.length).toBe(1)
    expect(compiled.errors[0]).toContain('root element')

    compiled = compile('
{{ b++++ }}
')
    expect(compiled.errors.length).toBe(2)
    expect(compiled.errors[0]).toContain('Raw expression: v-if="a----"')
    expect(compiled.errors[1]).toContain('Raw expression: {{ b++++ }}')
  })
})
<|endoftext|>


<commit_before>'use strict';

require('mocha');
var os = require('os');
var assert = require('assert');
var file = require('./');

describe('file-normalize', function() {
  it('should normalize slashes', function() {
    assert.equal(file.normalizeSlash('foo\\bar'), 'foo/bar');
  });

  it('should strip trailing slashes by default', function() {
    assert.equal(file.normalizeSlash('foo\\bar\\'), 'foo/bar');
  });

  it('should not strip trailing slashes when false is passed', function() {
    assert.equal(file.normalizeSlash('foo\\bar\\', false), 'foo/bar/');
  });

  it('should normalize EOL', function() {
    assert.equal(file.normalizeEOL('foo\r\nbar'), 'foo' + os.EOL + 'bar');
    assert.equal(file.normalizeEOL('foo\nbar'), 'foo' + os.EOL + 'bar');
  });

  it('should normalize EOL to unix newlines', function() {
    assert.equal(file.normalizeEOL('foo\r\nbar'), 'foo\nbar');
    assert.equal(file.normalizeEOL('foo\r\n\r\nbar'), 'foo\n\nbar');
    assert.equal(file.normalizeEOL('foo\rbar'), 'foo\nbar');
    assert.equal(file.normalizeEOL('foo\nbar'), 'foo\nbar');
  });

  it('should strip byte-order marks', function() {
    assert.equal(file.stripBOM('\ufefffoo\nbar'), 'foo\nbar');
  });

  describe('appendBuffer', function() {
    it('should append the buffer suffix to the buffer prefix with \\r\\n', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc\r\n'), new Buffer('def')), new Buffer('abc\r\ndef\r\n'));
    });

    it('should append the buffer suffix to the buffer prefix with \\n:', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc\n'), new Buffer('def')), new Buffer('abc\ndef\n'));
    });

    it('should append the buffer suffix to the buffer prefix without EOL', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc'), new Buffer('def')), new Buffer('abc' + os.EOL + 'def'));
    });

    it('should append the string suffix to the buffer prefix with \\r\\n', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc\r\n'), 'def'), new Buffer('abc\r\ndef\r\n'));
    });

    it('should append the string suffix to the buffer prefix with \\n:', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc\n'), 'def'), new Buffer('abc\ndef\n'));
    });

    it('should append the string suffix to the buffer prefix without EOL', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc'), 'def'), new Buffer('abc' + os.EOL + 'def'));
    });
  });

  describe('appendString', function() {
    it('should append the string suffix to the string prefix with \\r\\n', function() {
      assert.equal(file.appendString('abc\r\n', 'def'), 'abc\r\ndef\r\n');
    });

    it('should append the string suffix to the string prefix with \\n:', function() {
      assert.equal(file.appendString('abc\n', 'def'), 'abc\ndef\n');
    });

    it('should append the string suffix to the string prefix without EOL', function() {
      assert.equal(file.appendString('abc', 'def'), 'abc' + os.EOL + 'def');
    });

    it('should append the buffer suffix to the string prefix with \\r\\n', function() {
      assert.equal(file.appendString('abc\r\n', new Buffer('def')), 'abc\r\ndef\r\n');
    });

    it('should append the buffer suffix to the string prefix with \\n:', function() {
      assert.equal(file.appendString('abc\n', new Buffer('def')), 'abc\ndef\n');
    });

    it('should append the buffer suffix to the string prefix without EOL', function() {
      assert.equal(file.appendString('abc', new Buffer('def')), 'abc' + os.EOL + 'def');
    });
  });

  describe('append', function() {
    it('should append the buffer suffix to the buffer prefix with \\r\\n', function() {
      assert.deepEqual(file.append(new Buffer('abc\r\n'), new Buffer('def')), new Buffer('abc\r\ndef\r\n'));
    });

    it('should append the buffer suffix to the buffer prefix with \\n:', function() {
      assert.deepEqual(file.append(new Buffer('abc\n'), new Buffer('def')), new Buffer('abc\ndef\n'));
    });

    it('should append the buffer suffix to the buffer prefix without EOL', function() {
      assert.deepEqual(file.append(new Buffer('abc'), new Buffer('def')), new Buffer('abc' + os.EOL + 'def'));
    });

    it('should append the string suffix to the string prefix with \\r\\n', function() {
      assert.equal(file.append('abc\r\n', 'def'), 'abc\r\ndef\r\n');
    });

    it('should append the string suffix to the string prefix with \\n:', function() {
      assert.equal(file.append('abc\n', 'def'), 'abc\ndef\n');
    });

    it('should append the string suffix to the string prefix without EOL', function() {
      assert.equal(file.append('abc', 'def'), 'abc' + os.EOL + 'def');
    });

    it('should append the string suffix to the buffer prefix with \\r\\n', function() {
      assert.deepEqual(file.append(new Buffer('abc\r\n'), 'def'), new Buffer('abc\r\ndef\r\n'));
    });

    it('should append the string suffix to the buffer prefix with \\n:', function() {
      assert.deepEqual(file.append(new Buffer('abc\n'), 'def'), new Buffer('abc\ndef\n'));
    });

    it('should append the string suffix to the buffer prefix without EOL', function() {
      assert.deepEqual(file.append(new Buffer('abc'), 'def'), new Buffer('abc' + os.EOL + 'def'));
    });

    it('should append the buffer suffix to the string prefix with \\r\\n', function() {
      assert.equal(file.append('abc\r\n', new Buffer('def')), 'abc\r\ndef\r\n');
    });

    it('should append the buffer suffix to the string prefix with \\n:', function() {
      assert.equal(file.append('abc\n', new Buffer('def')), 'abc\ndef\n');
    });

    it('should append the buffer suffix to the string prefix without EOL', function() {
      assert.equal(file.append('abc', new Buffer('def')), 'abc' + os.EOL + 'def');
    });
  });
});
<commit_msg>add eol override to normalizeEOL tests<commit_after>'use strict';

require('mocha');
var os = require('os');
var assert = require('assert');
var file = require('./');

describe('file-normalize', function() {
  it('should normalize slashes', function() {
    assert.equal(file.normalizeSlash('foo\\bar'), 'foo/bar');
  });

  it('should strip trailing slashes by default', function() {
    assert.equal(file.normalizeSlash('foo\\bar\\'), 'foo/bar');
  });

  it('should not strip trailing slashes when false is passed', function() {
    assert.equal(file.normalizeSlash('foo\\bar\\', false), 'foo/bar/');
  });

  it('should normalize EOL', function() {
    assert.equal(file.normalizeEOL('foo\r\nbar'), 'foo' + os.EOL + 'bar');
    assert.equal(file.normalizeEOL('foo\nbar'), 'foo' + os.EOL + 'bar');
  });

  it('should normalize EOL to unix newlines', function() {
    assert.equal(file.normalizeEOL('foo\r\nbar', '\n'), 'foo\nbar');
    assert.equal(file.normalizeEOL('foo\r\n\r\nbar', '\n'), 'foo\n\nbar');
    assert.equal(file.normalizeEOL('foo\rbar', '\n'), 'foo\nbar');
    assert.equal(file.normalizeEOL('foo\nbar', '\n'), 'foo\nbar');
  });

  it('should strip byte-order marks', function() {
    assert.equal(file.stripBOM('\ufefffoo\nbar'), 'foo\nbar');
  });

  describe('appendBuffer', function() {
    it('should append the buffer suffix to the buffer prefix with \\r\\n', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc\r\n'), new Buffer('def')), new Buffer('abc\r\ndef\r\n'));
    });

    it('should append the buffer suffix to the buffer prefix with \\n:', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc\n'), new Buffer('def')), new Buffer('abc\ndef\n'));
    });

    it('should append the buffer suffix to the buffer prefix without EOL', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc'), new Buffer('def')), new Buffer('abc' + os.EOL + 'def'));
    });

    it('should append the string suffix to the buffer prefix with \\r\\n', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc\r\n'), 'def'), new Buffer('abc\r\ndef\r\n'));
    });

    it('should append the string suffix to the buffer prefix with \\n:', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc\n'), 'def'), new Buffer('abc\ndef\n'));
    });

    it('should append the string suffix to the buffer prefix without EOL', function() {
      assert.deepEqual(file.appendBuffer(new Buffer('abc'), 'def'), new Buffer('abc' + os.EOL + 'def'));
    });
  });

  describe('appendString', function() {
    it('should append the string suffix to the string prefix with \\r\\n', function() {
      assert.equal(file.appendString('abc\r\n', 'def'), 'abc\r\ndef\r\n');
    });

    it('should append the string suffix to the string prefix with \\n:', function() {
      assert.equal(file.appendString('abc\n', 'def'), 'abc\ndef\n');
    });

    it('should append the string suffix to the string prefix without EOL', function() {
      assert.equal(file.appendString('abc', 'def'), 'abc' + os.EOL + 'def');
    });

    it('should append the buffer suffix to the string prefix with \\r\\n', function() {
      assert.equal(file.appendString('abc\r\n', new Buffer('def')), 'abc\r\ndef\r\n');
    });

    it('should append the buffer suffix to the string prefix with \\n:', function() {
      assert.equal(file.appendString('abc\n', new Buffer('def')), 'abc\ndef\n');
    });

    it('should append the buffer suffix to the string prefix without EOL', function() {
      assert.equal(file.appendString('abc', new Buffer('def')), 'abc' + os.EOL + 'def');
    });
  });

  describe('append', function() {
    it('should append the buffer suffix to the buffer prefix with \\r\\n', function() {
      assert.deepEqual(file.append(new Buffer('abc\r\n'), new Buffer('def')), new Buffer('abc\r\ndef\r\n'));
    });

    it('should append the buffer suffix to the buffer prefix with \\n:', function() {
      assert.deepEqual(file.append(new Buffer('abc\n'), new Buffer('def')), new Buffer('abc\ndef\n'));
    });

    it('should append the buffer suffix to the buffer prefix without EOL', function() {
      assert.deepEqual(file.append(new Buffer('abc'), new Buffer('def')), new Buffer('abc' + os.EOL + 'def'));
    });

    it('should append the string suffix to the string prefix with \\r\\n', function() {
      assert.equal(file.append('abc\r\n', 'def'), 'abc\r\ndef\r\n');
    });

    it('should append the string suffix to the string prefix with \\n:', function() {
      assert.equal(file.append('abc\n', 'def'), 'abc\ndef\n');
    });

    it('should append the string suffix to the string prefix without EOL', function() {
      assert.equal(file.append('abc', 'def'), 'abc' + os.EOL + 'def');
    });

    it('should append the string suffix to the buffer prefix with \\r\\n', function() {
      assert.deepEqual(file.append(new Buffer('abc\r\n'), 'def'), new Buffer('abc\r\ndef\r\n'));
    });

    it('should append the string suffix to the buffer prefix with \\n:', function() {
      assert.deepEqual(file.append(new Buffer('abc\n'), 'def'), new Buffer('abc\ndef\n'));
    });

    it('should append the string suffix to the buffer prefix without EOL', function() {
      assert.deepEqual(file.append(new Buffer('abc'), 'def'), new Buffer('abc' + os.EOL + 'def'));
    });

    it('should append the buffer suffix to the string prefix with \\r\\n', function() {
      assert.equal(file.append('abc\r\n', new Buffer('def')), 'abc\r\ndef\r\n');
    });

    it('should append the buffer suffix to the string prefix with \\n:', function() {
      assert.equal(file.append('abc\n', new Buffer('def')), 'abc\ndef\n');
    });

    it('should append the buffer suffix to the string prefix without EOL', function() {
      assert.equal(file.append('abc', new Buffer('def')), 'abc' + os.EOL + 'def');
    });
  });
});
<|endoftext|>


<commit_before>//var config = require('../../nightwatch.conf.BASIC.js');

module.exports = { // adapted from: https://git.io/vodU0
  'TTB Assert Home Page, navigation': function(browser) {
    browser
      .url('http://localhost:8000/index.html')
      .waitForElementVisible('body')
      .assert.title('Team ToolBox')
      //.pause(1000)
      .waitForElementVisible(".alert-info")
      .saveScreenshot('.tmp/nightwatch/ttb/screenshots/home.png')
      //test links
      .click('a[href="#home"]')
      .assert.visible("#home")
      .click('a[href="#team-list"]')
      .assert.visible("#team-list")
      .click('a[href="#archive-list"]')
      .assert.visible("#archive-list")
      .click('a[href="#settings"]')
      .assert.visible("#settings")
      .click('a[href="#about"]')
      .assert.visible("#about")
      //test actions
      /*
      .click('a[href="#home"]')
      .click('.actions a[href="#tool-build-teams"]')
      .assert.visible("#tool-build-teams")
      .click('a[href="#home"]')
      .click('.actions a[href="#tool-find-members"]')
      .assert.visible("#tool-find-members")
      .click('a[href="#home"]')
      .click('.actions a[href="#tool-next-member"]')
      .assert.visible("#tool-next-member")
      .click('a[href="#home"]')
      .click('.actions a[href="#tool-match"]')
      .assert.visible("#tool-match")
      */
  },
  'Add a team  ':function(browser){
    browser
    .url('http://localhost:8000/index.html#team-list')
    .waitForElementVisible('#team-list')
    .assert.elementNotPresent("ul.team-list li") //should have no team-list

    .perform(function(client, done){
      for (var i = 0; i <2; i++){ //perform creation of 2 teams
        client.click('#team-list a[href="#team-add"]')
        client.waitForElementVisible('#team-add form')
        client.setValue('#team-add input[name="name"]', 'team' +i)
        client.click('#team-add input[type="submit"]')
        client.waitForElementVisible('#team-list-details')
        client.back()
        client.waitForElementVisible('#team-list li')
      }
      done()
    })
    //.click('a[href="#team-list"]') //go back to team-list
    .waitForElementVisible('ul.team-list li')
    .elements('css selector', 'ul.team-list li', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,2, 'should have a list of 2 teams')
    })

    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-list.png')
  },
  'Remove a team  ':function(browser){
    browser
    .url('http://localhost:8000/index.html#team-list')
    .waitForElementVisible('#team-list ul.team-list li')
    .click('#team-list ul.team-list li a') //click on first team
    .waitForElementVisible('#team-list-details button[name="remove"]')
    .click('#team-list-details button[name="remove"]')
    .pause(500)
    .acceptAlert()
    .pause(500)
    .waitForElementVisible('#team-list ul.team-list li')
    .elements('css selector', 'ul.team-list li', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,1, 'should have a list of 1 team')
    })
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-list-removed-one.png')

  },
  'Team Members Add ':function(browser){
    browser
    .url('http://localhost:8000/index.html#team-list')
    .waitForElementVisible('#team-list ul.team-list li')
    .click('#team-list ul.team-list li a') //click on first team
    .waitForElementVisible('#team-list-details form')
    .perform(function(client, done){
      for (var i = 0; i <11; i++){
        client.setValue('#team-list-details input[name="name"]', 'member'+i);
        client.click('#team-list-details input[type="submit"]');
        client.waitForElementVisible('#team-list-details .team-members a');

      }
      done();
    })
    .assert.elementPresent("ul.team-members li")
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-members.png')
  },
  'Team Members Update ':function(browser){
    browser
    //modify users
    .click("ul.team-members li a") //click on first element
    .waitForElementVisible('#team-member-details')
    .setValue('#team-member-details input[name="name"]', 'modified member')
    .click('#team-member-details input[type="submit"]')
    .waitForElementVisible('#team-list-details')
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-members-after-rename.png')
  },
  'Team Members Delete ':function(browser){
    browser
    //remove a member
    .click("ul.team-members li:last-child a") //click on last element
    .waitForElementVisible('#team-member-details')
    .click('#team-member-details input[type="button"]')
    .pause(500)
    .acceptAlert()
    .pause(500)
    .waitForElementVisible('#team-list-details')
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-members-after-removeone.png')
  },
  'Random Teams test ':function(browser){
    browser
    .url('http://localhost:8000/index.html#tool-build-teams')
    .waitForElementVisible('#tool-build-teams')
    .setValue('#tool-build-teams .nb-members', 1)
    .click('input[type="submit"]')
    .waitForElementVisible('#tool-build-teams div.team')
    .pause(500)
    .assert.elementPresent("ul.list li")
    .elements('css selector', '#tool-build-teams .team h3', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,10, 'should generate a list of 10 teams')
    })
    .pause(1000)
    //------
    .setValue('#tool-build-teams .nb-members', 2)
    .click('input[type="submit"]')
    .waitForElementVisible('#tool-build-teams div.team')
    .assert.elementPresent("ul.list li")
    .elements('css selector', '#tool-build-teams .team h3', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,5, 'should generate a list of 5 teams')
    })
    .pause(1000)
    //save to archive
    .click('#tool-build-teams button[name="save"]')
    .waitForElementVisible('#archive-save')
    //test for empty name
    .setValue('#archive-save input[name="name"]', '')
    .click('#archive-save input[type="submit"]') //should do nothing (TODO handle msg error)
    //
    //.assert.urlContains('#archive-save')
    .setValue('#archive-save input[name="name"]', 'archive1')
    .setValue('#archive-save textarea', 'description for archive1')
    .click('#archive-save input[type="submit"]')
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-generation-save.png')
    .pause(500)
    .acceptAlert()
    .waitForElementVisible('#tool-build-teams',1000)
    .assert.cssClassNotPresent('#tool-build-teams .teams-result button', 'btn-success')

  },
  'Archive update ':function(browser){
    browser.url('http://localhost:8000/index.html#archive-list')
    //remove a member
    .waitForElementVisible('#archive-list .archive-list')
    .assert.elementPresent("#archive-list .archive-list li")
    .click("#archive-list .archive-list li:last-child a") //click on last element
    .waitForElementVisible('#archive-details')
    .setValue('#archive-details textarea[name="comment"]', 'comment for archive here')
    .click('#archive-details input[type="submit"]')
    .pause(500)
    .assert.containsText('#archive-details textarea','comment for archive here')
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/archive-update.png')
  },
  'Find members ':function(browser){
    browser.url('http://localhost:8000/index.html#tool-find-members')
    .waitForElementVisible('#tool-find-members form')
    .setValue('#tool-find-members .nb-members', 4)
    .click('#tool-find-members input[type="submit"]')
    .waitForElementVisible('#tool-find-members div.team')
    .assert.elementPresent("ul.list li")
    .elements('css selector', '#tool-find-members .team li', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,4, 'should generate a list of 4 members')
    })
    .end()
  }
  // ,
  // 'Next members ':function(browser){
  //   browser.url('http://localhost:8000/index.html#tool-next-member')
  //   .waitForElementVisible('#tool-next-member form')
  //   .setValue('#tool-find-members select[name="team-list"]', 4)
  //
  //   .waitForElementVisible('#teams-result')
  //   .assert.elementPresent("#teams-result ul.list li")
  //   .elements('css selector', '#tool-find-members .team li', function (elements) {
  //     var count = elements.value.length;
  //     this.assert.equal(count,4, 'should generate a list of 4 members')
  //   })
  //   .end();
  //}

};
<commit_msg>correct tests after title change<commit_after>//var config = require('../../nightwatch.conf.BASIC.js');

module.exports = { // adapted from: https://git.io/vodU0
  'TTB Assert Home Page, navigation': function(browser) {
    browser
      .url('http://localhost:8000/index.html')
      .waitForElementVisible('body')
      .assert.title('Team Toolbox')
      //.pause(1000)
      .waitForElementVisible(".alert-info")
      .saveScreenshot('.tmp/nightwatch/ttb/screenshots/home.png')
      //test links
      .click('a[href="#home"]')
      .assert.visible("#home")
      .click('a[href="#team-list"]')
      .assert.visible("#team-list")
      .click('a[href="#archive-list"]')
      .assert.visible("#archive-list")
      .click('a[href="#settings"]')
      .assert.visible("#settings")
      .click('a[href="#about"]')
      .assert.visible("#about")
      //test actions
      /*
      .click('a[href="#home"]')
      .click('.actions a[href="#tool-build-teams"]')
      .assert.visible("#tool-build-teams")
      .click('a[href="#home"]')
      .click('.actions a[href="#tool-find-members"]')
      .assert.visible("#tool-find-members")
      .click('a[href="#home"]')
      .click('.actions a[href="#tool-next-member"]')
      .assert.visible("#tool-next-member")
      .click('a[href="#home"]')
      .click('.actions a[href="#tool-match"]')
      .assert.visible("#tool-match")
      */
  },
  'Add a team  ':function(browser){
    browser
    .url('http://localhost:8000/index.html#team-list')
    .waitForElementVisible('#team-list')
    .assert.elementNotPresent("ul.team-list li") //should have no team-list

    .perform(function(client, done){
      for (var i = 0; i <2; i++){ //perform creation of 2 teams
        client.click('#team-list a[href="#team-add"]')
        client.waitForElementVisible('#team-add form')
        client.setValue('#team-add input[name="name"]', 'team' +i)
        client.click('#team-add input[type="submit"]')
        client.waitForElementVisible('#team-list-details')
        client.back()
        client.waitForElementVisible('#team-list li')
      }
      done()
    })
    //.click('a[href="#team-list"]') //go back to team-list
    .waitForElementVisible('ul.team-list li')
    .elements('css selector', 'ul.team-list li', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,2, 'should have a list of 2 teams')
    })

    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-list.png')
  },
  'Remove a team  ':function(browser){
    browser
    .url('http://localhost:8000/index.html#team-list')
    .waitForElementVisible('#team-list ul.team-list li')
    .click('#team-list ul.team-list li a') //click on first team
    .waitForElementVisible('#team-list-details button[name="remove"]')
    .click('#team-list-details button[name="remove"]')
    .pause(500)
    .acceptAlert()
    .pause(500)
    .waitForElementVisible('#team-list ul.team-list li')
    .elements('css selector', 'ul.team-list li', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,1, 'should have a list of 1 team')
    })
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-list-removed-one.png')

  },
  'Team Members Add ':function(browser){
    browser
    .url('http://localhost:8000/index.html#team-list')
    .waitForElementVisible('#team-list ul.team-list li')
    .click('#team-list ul.team-list li a') //click on first team
    .waitForElementVisible('#team-list-details form')
    .perform(function(client, done){
      for (var i = 0; i <11; i++){
        client.setValue('#team-list-details input[name="name"]', 'member'+i);
        client.click('#team-list-details input[type="submit"]');
        client.waitForElementVisible('#team-list-details .team-members a');

      }
      done();
    })
    .assert.elementPresent("ul.team-members li")
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-members.png')
  },
  'Team Members Update ':function(browser){
    browser
    //modify users
    .click("ul.team-members li a") //click on first element
    .waitForElementVisible('#team-member-details')
    .setValue('#team-member-details input[name="name"]', 'modified member')
    .click('#team-member-details input[type="submit"]')
    .waitForElementVisible('#team-list-details')
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-members-after-rename.png')
  },
  'Team Members Delete ':function(browser){
    browser
    //remove a member
    .click("ul.team-members li:last-child a") //click on last element
    .waitForElementVisible('#team-member-details')
    .click('#team-member-details input[type="button"]')
    .pause(500)
    .acceptAlert()
    .pause(500)
    .waitForElementVisible('#team-list-details')
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-members-after-removeone.png')
  },
  'Random Teams test ':function(browser){
    browser
    .url('http://localhost:8000/index.html#tool-build-teams')
    .waitForElementVisible('#tool-build-teams')
    .setValue('#tool-build-teams .nb-members', 1)
    .click('input[type="submit"]')
    .waitForElementVisible('#tool-build-teams div.team')
    .pause(500)
    .assert.elementPresent("ul.list li")
    .elements('css selector', '#tool-build-teams .team h3', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,10, 'should generate a list of 10 teams')
    })
    .pause(1000)
    //------
    .setValue('#tool-build-teams .nb-members', 2)
    .click('input[type="submit"]')
    .waitForElementVisible('#tool-build-teams div.team')
    .assert.elementPresent("ul.list li")
    .elements('css selector', '#tool-build-teams .team h3', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,5, 'should generate a list of 5 teams')
    })
    .pause(1000)
    //save to archive
    .click('#tool-build-teams button[name="save"]')
    .waitForElementVisible('#archive-save')
    //test for empty name
    .setValue('#archive-save input[name="name"]', '')
    .click('#archive-save input[type="submit"]') //should do nothing (TODO handle msg error)
    //
    //.assert.urlContains('#archive-save')
    .setValue('#archive-save input[name="name"]', 'archive1')
    .setValue('#archive-save textarea', 'description for archive1')
    .click('#archive-save input[type="submit"]')
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/team-generation-save.png')
    .pause(500)
    .acceptAlert()
    .waitForElementVisible('#tool-build-teams',1000)
    .assert.cssClassNotPresent('#tool-build-teams .teams-result button', 'btn-success')

  },
  'Archive update ':function(browser){
    browser.url('http://localhost:8000/index.html#archive-list')
    //remove a member
    .waitForElementVisible('#archive-list .archive-list')
    .assert.elementPresent("#archive-list .archive-list li")
    .click("#archive-list .archive-list li:last-child a") //click on last element
    .waitForElementVisible('#archive-details')
    .setValue('#archive-details textarea[name="comment"]', 'comment for archive here')
    .click('#archive-details input[type="submit"]')
    .pause(500)
    .assert.containsText('#archive-details textarea','comment for archive here')
    .saveScreenshot('.tmp/nightwatch/ttb/screenshots/archive-update.png')
  },
  'Find members ':function(browser){
    browser.url('http://localhost:8000/index.html#tool-find-members')
    .waitForElementVisible('#tool-find-members form')
    .setValue('#tool-find-members .nb-members', 4)
    .click('#tool-find-members input[type="submit"]')
    .waitForElementVisible('#tool-find-members div.team')
    .assert.elementPresent("ul.list li")
    .elements('css selector', '#tool-find-members .team li', function (elements) {
      var count = elements.value.length;
      this.assert.equal(count,4, 'should generate a list of 4 members')
    })
    .end()
  }
  // ,
  // 'Next members ':function(browser){
  //   browser.url('http://localhost:8000/index.html#tool-next-member')
  //   .waitForElementVisible('#tool-next-member form')
  //   .setValue('#tool-find-members select[name="team-list"]', 4)
  //
  //   .waitForElementVisible('#teams-result')
  //   .assert.elementPresent("#teams-result ul.list li")
  //   .elements('css selector', '#tool-find-members .team li', function (elements) {
  //     var count = elements.value.length;
  //     this.assert.equal(count,4, 'should generate a list of 4 members')
  //   })
  //   .end();
  //}

};
<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Clean Blog v3.3.7+1 (http://startbootstrap.com/template-overviews/clean-blog)
 * Copyright 2013-2016 Start Bootstrap
 * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE)
 */
$(function(){$("body").on("input propertychange",".floating-label-form-group",function(a){$(this).toggleClass("floating-label-form-group-with-value",!!$(a.target).val())}).on("focus",".floating-label-form-group",function(){$(this).addClass("floating-label-form-group-with-focus")}).on("blur",".floating-label-form-group",function(){$(this).removeClass("floating-label-form-group-with-focus")})}),jQuery(document).ready(function(a){var b=1170;if(a(window).width()>b){var c=a(".navbar-custom").height();a(window).on("scroll",{previousTop:0},function(){var b=a(window).scrollTop();a(".dropdown-menu").is(":visible")&&(a(".dropdown-menu").hide().end(),a("#rttrpmdropdown").mouseover(function(){a(this).find(".dropdown-menu").show().end()}).mouseout(function(){a(this).find(".dropdown-menu").hide().end()}),a("#systemsdropdown").mouseover(function(){a(this).find(".dropdown-menu").show().end()}).mouseout(function(){a(this).find(".dropdown-menu").hide().end()})),b<this.previousTop?b>0&&a(".navbar-custom").hasClass("is-fixed")?a(".navbar-custom").addClass("is-visible"):a(".navbar-custom").removeClass("is-visible is-fixed"):b>this.previousTop&&(a(".navbar-custom").removeClass("is-visible"),b>c&&!a(".navbar-custom").hasClass("is-fixed")&&a(".navbar-custom").addClass("is-fixed")),this.previousTop=b})}});<commit_msg>Syntax Error<commit_after>/*!
 * Start Bootstrap - Clean Blog v3.3.7+1 (http://startbootstrap.com/template-overviews/clean-blog)
 * Copyright 2013-2016 Start Bootstrap
 * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE)
 */
$(function(){$("body").on("input propertychange",".floating-label-form-group",function(o){$(this).toggleClass("floating-label-form-group-with-value",!!$(o.target).val())}).on("focus",".floating-label-form-group",function(){$(this).addClass("floating-label-form-group-with-focus")}).on("blur",".floating-label-form-group",function(){$(this).removeClass("floating-label-form-group-with-focus")})}),jQuery(document).ready(function(o){var s=1170;if(o(window).width()>s){var i=o(".navbar-custom").height();o(window).on("scroll",{previousTop:0},function(){var s=o(window).scrollTop();if(o('.dropdown-menu').is(':visible')){o('.dropdown-menu').hide().end();o('#rttrpmdropdown').mouseover(function() {o(this).find('.dropdown-menu').show().end()}).mouseout(function() {o(this).find('.dropdown-menu').hide().end()});o('#systemsdropdown').mouseover(function() {o(this).find('.dropdown-menu').show().end()}).mouseout(function() {o(this).find('.dropdown-menu').hide().end()});}s<this.previousTop?s>0&&o(".navbar-custom").hasClass("is-fixed")?o(".navbar-custom").addClass("is-visible"):o(".navbar-custom").removeClass("is-visible is-fixed"):s>this.previousTop&&(o(".navbar-custom").removeClass("is-visible"),s>i&&!o(".navbar-custom").hasClass("is-fixed")&&o(".navbar-custom").addClass("is-fixed")),this.previousTop=s})}});<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-13 18:41:14<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>const assert = require('assert');

assert.inDelta = (actual, expected, delta, message) => {
  if (!inDelta(actual, expected, delta)) {
    assert.fail(
      actual,
      expected,
      message || `expected {actual} to be in within *${delta}* of {expected}`,
      null,
      assert.inDelta
    );
  }
};

function inDelta(actual, expected, delta) {
  return (Array.isArray(expected) ? inDeltaArray : inDeltaNumber)(
    actual,
    expected,
    delta
  );
}

function inDeltaArray(actual, expected, delta) {
  const n = expected.length;
  let i = -1;
  if (actual.length !== n) return false;
  while (++i < n) {
    if (Array.isArray(actual[i])) {
      if (!inDeltaArray(actual[i], expected[i], delta)) return false;
    } else {
      if (!inDeltaNumber(actual[i], expected[i], delta)) return false;
    }
  }
  return true;
}

function inDeltaNumber(actual, expected, delta) {
  const d = Math.abs(actual - expected);
  return d < delta;
}

assert.inDeltaArray = (actual, expected, delta, message) => {
  if (!inDeltaArray(actual, expected, delta))
    assert.fail(
      actual,
      expected,
      message || `expected {actual} to equal to {expected} within ${delta}`
    );
  return true;
};

function inDeltaAbs(actual, expected, delta) {
  const d = Math.abs(Math.abs(actual) - Math.abs(expected));
  return d < delta;
}

assert.inDeltaArrayAbs = (actual, expected, delta, message) => {
  const n = expected.length;
  let i = -1;
  if (actual.length !== n) {
    assert.fail(
      actual,
      expected,
      message ||
        `expected {actual} to have the same length *${n}* as {expected}`,
      null,
      assert.inDeltaArrayAbs
    );
  }
  while (++i < n)
    if (!inDeltaAbs(actual[i], expected[i], delta))
      assert.fail(
        actual,
        expected,
        message || `expected {actual} to be in within *${delta}* of {expected}`,
        null,
        assert.inDeltaArrayAbs
      );
  return true;
};

function neg(a) {
  return a.map((x) => -x);
}

assert.inDeltaArrayOrNeg = (actual, expected, delta, message) => {
  if (
    !inDeltaArray(actual, expected, delta) &&
    !inDeltaArray(neg(actual), expected, delta)
  )
    assert.fail(
      actual,
      expected,
      message || `expected {actual} to equal to {expected} within ${delta}`
    );
  return true;
};

function permutationEqual(actual, expected) {
  let n;
  if (!(Array.isArray(actual) && Array.isArray(expected))) return false;
  n = actual.length;
  if (n != expected.length) return false;
  while (n--) if (actual[n] != expected[n]) return false;
  return true;
}

function permutationInverted(actual, expected) {
  let n, i;
  if (!(isArray(actual) && isArray(expected))) return false;
  n = actual.length;
  if (n != expected.length) return false;
  i = n - 1;
  while (n--) if (actual[n] != expected[i - n]) return false;
  return true;
}

assert.permutationEqual = (actual, expected, message) => {
  if (
    !permutationEqual(actual, expected) &&
    !permutationInverted(actual, expected)
  )
    assert.fail(
      actual,
      expected,
      message || 'expected {actual} to be equal or inverse of {expected}'
    );
  return true;
};
<commit_msg>Manual cleanup of env-assert.js<commit_after>const assert = require('assert');

assert.inDelta = (actual, expected, delta, message) => {
  if (!inDelta(actual, expected, delta)) {
    assert.fail(
      actual,
      expected,
      message || `expected {actual} to be in within *${delta}* of {expected}`,
      null,
      assert.inDelta
    );
  }
};

function inDelta(actual, expected, delta) {
  return (Array.isArray(expected) ? inDeltaArray : inDeltaNumber)(
    actual,
    expected,
    delta
  );
}

function inDeltaArray(actual, expected, delta) {
  const n = expected.length;
  let i = -1;
  if (actual.length !== n) return false;
  while (++i < n) {
    if (Array.isArray(actual[i])) {
      if (!inDeltaArray(actual[i], expected[i], delta)) return false;
    } else {
      if (!inDeltaNumber(actual[i], expected[i], delta)) return false;
    }
  }
  return true;
}

function inDeltaNumber(actual, expected, delta) {
  const d = Math.abs(actual - expected);
  return d < delta;
}

assert.inDeltaArray = (actual, expected, delta, message) => {
  if (!inDeltaArray(actual, expected, delta))
    assert.fail(
      actual,
      expected,
      message || `expected {actual} to equal to {expected} within ${delta}`
    );
  return true;
};

function inDeltaAbs(actual, expected, delta) {
  const d = Math.abs(Math.abs(actual) - Math.abs(expected));
  return d < delta;
}

assert.inDeltaArrayAbs = (actual, expected, delta, message) => {
  const n = expected.length;
  let i = -1;
  if (actual.length !== n) {
    assert.fail(
      actual,
      expected,
      message ||
        `expected {actual} to have the same length *${n}* as {expected}`,
      null,
      assert.inDeltaArrayAbs
    );
  }
  while (++i < n)
    if (!inDeltaAbs(actual[i], expected[i], delta))
      assert.fail(
        actual,
        expected,
        message || `expected {actual} to be in within *${delta}* of {expected}`,
        null,
        assert.inDeltaArrayAbs
      );
  return true;
};

function neg(a) {
  return a.map((x) => -x);
}

assert.inDeltaArrayOrNeg = (actual, expected, delta, message) => {
  if (
    !inDeltaArray(actual, expected, delta) &&
    !inDeltaArray(neg(actual), expected, delta)
  )
    assert.fail(
      actual,
      expected,
      message || `expected {actual} to equal to {expected} within ${delta}`
    );
  return true;
};

function permutationEqual(actual, expected) {
  if (!(Array.isArray(actual) && Array.isArray(expected))) return false;
  let n = actual.length;
  if (n != expected.length) return false;
  while (n--) if (actual[n] != expected[n]) return false;
  return true;
}

function permutationInverted(actual, expected) {
  if (!(isArray(actual) && isArray(expected))) return false;
  let n = actual.length;
  if (n != expected.length) return false;
  const i = n - 1;
  while (n--) if (actual[n] != expected[i - n]) return false;
  return true;
}

assert.permutationEqual = (actual, expected, message) => {
  if (
    !permutationEqual(actual, expected) &&
    !permutationInverted(actual, expected)
  )
    assert.fail(
      actual,
      expected,
      message || 'expected {actual} to be equal or inverse of {expected}'
    );
  return true;
};
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-3 11:20:42<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var H = require('../index').EventEmitter;
var _ = require('lodash');
var assert = require('assert');

describe('HevEmitter error', function () {

    it('should trigger "error" listeners', function (done) {
        var h = new H();
        h.on(['error'], function () {
            done();
        });
        h.emit(['error']);
    });

    it('should *NOT* trigger * listeners', function (done) {
        var h = new H();
        h.on(['*'], function () {
            done(true);
        });
        h.on(['*', '*'], function () {
            done(true);
        });
        h.on(['error'], function () {
            done();
        });
        h.emit(['error'], function () {});
    });

    it('should NOT trigger ** events', function (done) {
        var h = new H();
        h.on(['**'], function () {
            done(true);
        });
        h.on(['error'], function () {
            done();
        });
        h.emit(['error']);
    });

    it('should cause exception when there is no listener', function (done) {
        var h = new H();
        h.emit(['error'])
        .catch(function () {
            done();
        });
    });

    it('should allow sub listeners', function (done) {
        var h = new H();
        h.on(['error', 'smith'], function () {
            done(false);
        });
        h.on(['error', 'photo'], function () {
            done();
        });
        h.emit(['error', 'photo']);
    });

    it('should catch sub events on error', function (done) {
        var h = new H();
        h.on(['error'], function () {
            done();
        });
        h.emit(['error', 'photo']);
    });

});
<commit_msg>Clean up and update errorEvent tests.<commit_after>/*jslint node: true */
"use strict";

var _ = require('lodash');
var assert = require('assert');

var H = require('../index').EventEmitter;

describe('HevEmitter error', function () {

    var h;
    beforeEach(function () {
        h = new H();
    });

    it('should trigger "error" listeners', function (done) {
        h.on(['error'], function () {
            done();
        });
        h.emit(['error']);
    });

    it('should *NOT* trigger * listeners', function (done) {
        h.on(['*'], function () {
            done(true);
        });
        h.on(['*', '*'], function () {
            done(true);
        });
        h.on(['error'], function () {
            done();
        });
        h.emit(['error'], function () {});
    });

    it('should NOT trigger ** events', function (done) {
        h.on(['**'], function () {
            done(true);
        });
        h.on(['error'], function () {
            done();
        });
        h.emit(['error']);
    });

    it('should cause exception when there is no listener', function (done) {
        try {
            h.emit(['error']);
            return done(true);
        } catch (e) {
            return done();
        }
    });

    it('should allow sub listeners', function (done) {
        h.on(['error', 'smith'], function () {
            done(false);
        });
        h.on(['error', 'photo'], function () {
            done();
        });
        h.emit(['error', 'photo']);
    });

    it('should catch sub events on error', function (done) {
        h.on(['error'], function () {
            done();
        });
        h.emit(['error', 'photo']);
    });

});
<|endoftext|>