<commit_before>/**
 * @license
 * Patterns @VERSION@ tooltip - tooltips
 *
 * Copyright 2008-2012 Simplon B.V.
 * Copyright 2011 Humberto Sermeño
 * Copyright 2011 SYSLAB.COM GmbH
 */
define([
    'require',
    '../core/init',
    '../utils'
], function(require) {
    var utils = require('../utils'),
        mapal = require('../core/init');

    var tooltip = {
        count: 0,

        init: function() {
        },

        initContent: function(root) {
            var $root = $(root);
            var init = function($trigger) {
                var options = utils.parseOptions($trigger.data("tooltip"));
                options.title = $trigger.attr("title");
                $trigger.removeAttr("title");
                $trigger.data("mapal.tooltip", options);
                tooltip.setupShowEvents($trigger);
            };
            if ($root.is('[data-tooltip]')) init($root);
            $("*[data-tooltip]", $root).each(function() {
                init($(this));
            });
        },

        setupShowEvents: function($trigger) {
            var parameters = $trigger.data("mapal.tooltip");
            if (parameters.click) {
                $trigger.on("click.tooltip", $trigger, tooltip.show);
            } else {
                $trigger.on("mouseover.tooltip", $trigger, tooltip.show);
                // Make sure click on the trigger element becomes a NOP
                $trigger.on("click.tooltip", $trigger, tooltip.blockDefault);
            }
        },

        removeShowEvents: function($trigger) {
            $trigger.off(".tooltip");
        },

        setupHideEvents: function($trigger) {
            var $container = tooltip.getContainer($trigger),
                parameters = $trigger.data("mapal.tooltip");
            if (parameters.sticky) {
                $container.find(".closePanel")
                    .on("click.tooltip", $trigger, tooltip.hide);
                // Make sure click on the trigger element becomes a NOP
                $trigger.on("click.tooltip", $trigger, tooltip.blockDefault);
            } else {
                if (parameters.click) {
                    $container.on("click.tooltip", $trigger, function(ev) {
                        ev.stopPropagation();
                    });
                    $(document).on("click.tooltip", $trigger, tooltip.hide);
                    $trigger.on("click.tooltip", tooltip.blockDefault);
                    // close if something inside the tooltip triggered an injection
                    $container.on('patterns-inject-triggered.tooltip',
                                  $trigger, tooltip.hide);
                    $container.on('patterns-inject_interim-triggered.tooltip',
                                  $trigger, tooltip.hide);
                    $container.on('submit.tooltip', $trigger, tooltip.hide);
                } else {
                    $container.on("click.tooltip", $trigger, tooltip.hide);
                    $trigger.on("mouseleave.tooltip", $trigger, tooltip.hide);
                    $trigger.on("click.tooltip", tooltip.blockDefault);
                }
            }
        },

        removeHideEvents: function($trigger) {
            var $container = tooltip.getContainer($trigger);
            $(document).off(".tooltip");
            $container.off(".tooltip");
            $container.find(".closePanel").off(".tooltip");
            $trigger.off(".tooltip");
        },

        blockDefault: function(event) {
            event.preventDefault();
        },

        show: function(event) {
            var $trigger = event.data,
                $container = tooltip.getContainer($trigger),
                options = $trigger.data("mapal.tooltip");

            tooltip.removeShowEvents($trigger);
	    // Wrap in a timeout to make sure this click is not used to
	    // trigger a hide as well.
	    setTimeout(function() { tooltip.setupHideEvents($trigger) }, 50);

            function ajax_show() {
                $container.find(">div >*").css("opacity", 1);
                tooltip.positionContainer($trigger, $container);
            }

            if (options.ajax) {
                var source = $trigger.attr("href").split("#"),
                    target_id = $container.find("progress").attr("id");
                mapal.injection.load($trigger, source[0], target_id+":replace", source[1] || [],
                        ajax_show, true);
                delete options.ajax;
                $trigger.data("mapal.tooltip", options);
            }

            tooltip.positionContainer($trigger, $container);
            $container.css("visibility", "visible");

	    // reposition tooltip everytime we scroll
	    $trigger.parents(':scrollable').scroll(function () {
                 tooltip.positionContainer($trigger, $container);
	    });

            event.preventDefault();
        },

        hide: function(event) {
            var $trigger = event.data,
                $container = tooltip.getContainer($trigger);
            tooltip.removeHideEvents($trigger);
            $container.css("visibility", "hidden");
            tooltip.setupShowEvents($trigger);
        },

        getContainer: function($trigger) {
            var $container = $trigger.data("mapal.tooltip.container");
            if ($container===undefined) {
                $container=tooltip.createContainer($trigger);
                $trigger.data("mapal.tooltip.container", $container);
            }
            return $container;
        },

        createContainer: function($trigger) {
            var options = $trigger.data("mapal.tooltip"),
                $content, $container;

            $container = $("
", {"class": "tooltip-container"});
            $container.css("visibility", "hidden");
            if (options.ajax) {
                $content = $("<progress/>", {"id": "tooltip-" + ++tooltip.count});
            } else {
                $content = $("
").text(options.title);
            }
            $container.append(
                $("
").css("display", "block").append($content))
                .append($("", {"class": "pointer"}));
            if (options.sticky && !options.noclose) {
                $("<button/>", {"class": "closePanel"})
                    .text("Close")
                    .insertBefore($container.find("*"));
            }
            $("body").append($container);
            return $container;
        },

        boundingBox: function($el) {
            var box = $el.offset();
            box.height = $el.height();
            box.width = $el.width();
            box.bottom = box.top + box.height;
            box.right = box.left + box.width;
            return box;
        },

        positionStatus: function($trigger, $container) {
            var trigger_box = tooltip.boundingBox($trigger),
                tooltip_box = tooltip.boundingBox($container),
                $window = $(window),
                window_width = $window.width(),
                window_height = $window.height(),
                trigger_center,
                space = {},
                container_offset = {},
                tip_offset = {},
                cls = "";

            trigger_center = {top: trigger_box.top + (trigger_box.height/2),
                              left: trigger_box.left + (trigger_box.width/2)};
            space.top = trigger_box.top - $window.scrollTop();
            space.bottom = window_height - space.top - trigger_box.height;
            space.left = trigger_box.left - $window.scrollLeft();
            space.right = window_width - space.left - trigger_box.width;

            return {"space": space,
                    "trigger_center": trigger_center,
                    "trigger_box": trigger_box,
                    "tooltip_box": tooltip_box};
        },

        // Help function to determine the best position for a tooltip.  Takes
        // the positioning status (as generated by positionStatus) as input
        // and returns a two-character position indiciator.
        findBestPosition: function(status) {
            var space = status.space,
                 cls = "";

            if (space.top > Math.max(space.right, space.bottom, space.left)) {
                cls = "t";
            } else if (space.right > Math.max(space.bottom, space.left, space.top)) {
                cls = "r";
            } else if (space.bottom > Math.max(space.left, space.top, space.right)) {
                cls = "b";
            } else {
                cls = "l";
            }

            switch (cls[0]) {
            case "t":
            case "b":
                if (Math.abs(space.left-space.right) < 20) {
                    cls += "m";
                } else if (space.left > space.right) {
                    cls += "r";
                } else {
                    cls += "l";
                }
                break;
            case "l":
            case "r":
                if (Math.abs(space.top-space.bottom) < 20) {
                    cls += "m";
                } else if (space.top > space.bottom) {
                    cls += "b";
                } else {
                    cls += "t";
                }
            }
            return cls;
        },

        isVisible: function(status, position) {
            var space = status.space,
                tooltip_box = status.tooltip_box;

            switch (position[0]) {
            case "t":
                if (tooltip_box.height > space.bottom) {
                    return false;
                }
                break;
            case "r":
                if (tooltip_box.width > space.left) {
                    return false;
                }
                break;
            case "b":
                if (tooltip_box.height > space.top) {
                    return false;
                }
                break;
            case "l":
                if (tooltip_box.width > space.right) {
                    return false;
                }
                break;
            default:
                return false;
            }

            switch (position[0]) {
            case "t":
            case "b":
                switch (position[1]) {
                    case "l":
                        if ((tooltip_box.width-20)>space.right) {
                            return false;
                        }
                        break;
                    case "m":
                        if ((tooltip_box.width/2)>space.left || (tooltip_box.width/2)>space.right) {
                            return false;
                        }
                        break;
                    case "r":
                        if ((tooltip_box.width-20)>space.left) {
                            return false;
                        }
                        break;
                    default:
                        return false;
                }
                break;
            case "l":
            case "r":
                switch (position[1]) {
                    case "t":
                        if ((tooltip_box.height-20)>space.bottom) {
                            return false;
                        }
                        break;
                    case "m":
                        if ((tooltip_box.height/2)>space.top || (tooltip_box.height/2)>space.bottom) {
                            return false;
                        }
                        break;
                    case "b":
                        if ((tooltip_box.height-20)>space.top) {
                            return false;
                        }
                    default:
                        return false;
                }
                break;
            }
            return true;
        },

        VALIDPOSITION: /^([lr][tmb]|[tb][lmr])$/,

        positionContainer: function($trigger, $container) {
            var status = tooltip.positionStatus($trigger, $container),
                options = $trigger.data("mapal.tooltip"),
                container_offset = {},
                tip_offset = {},
                position;

            if (options.position) {
                var positions = options.position.split("-"), i;
                for (i=0; i<positions.length; i++) {
                    if (!tooltip.VALIDPOSITION.test(positions[i])) {
                        continue;
                    }

                    if (options.forcePosition || tooltip.isVisible(status, positions[i])) {
                        position = positions[i];
                        break;
                    }
                }
            }

            if (!position) {
                position = tooltip.findBestPosition(status);
            }

            var trigger_box = status.trigger_box,
                tooltip_box = status.tooltip_box,
                trigger_center = status.trigger_center;

            switch (position[0]) {
            case "t":
                container_offset.top = trigger_box.bottom + 20;
                tip_offset.top = -23;
                break;
            case "r":
                container_offset.left = trigger_box.right + 20;
                tip_offset.left = 0;
                break;
            case "b":
                container_offset.top = trigger_box.top - tooltip_box.height + 10;
                tip_offset.top = tooltip_box.height - 23;
                break;
            case "l":
                container_offset.left = trigger_box.left - tooltip_box.width - 20;
                tip_offset.left = tooltip_box.width - 23;
                break;
            }

            switch (position[0]) {
            case "t":
            case "b":
                switch (position[1]) {
                case "l":
                    container_offset.left = trigger_center.left - 20;
                    tip_offset.left = 0;
                    break;
                case "m":
                    container_offset.left = trigger_center.left - (tooltip_box.width/2);
                    tip_offset.left = tooltip_box.width/2 - 10;
                    break;
                case "r":
                    container_offset.left = trigger_center.left + 29 - tooltip_box.width;
                    tip_offset.left = tooltip_box.width - 20;
                    break;
                }
                break;
            case "l":
            case "r":
                switch (position[1]) {
                    case "t":
                        container_offset.top = trigger_center.top - 30;
                        tip_offset.top = 0;
                        break;
                    case "m":
                        container_offset.top = trigger_center.top - (tooltip_box.height/2);
                        tip_offset.top = tooltip_box.height/2 - 10;
                        break;
                    case "b":
                        container_offset.top = trigger_center.top + 20 - tooltip_box.height;
                        tip_offset.top = tooltip_box.height - 20;
                        break;
                }
                break;
            }

            $container.attr("class", "tooltip-container " + position);
            $container.css({
                top: container_offset.top+"px",
                left: container_offset.left+"px"});
            $container.find(".pointer").css({
                top: tip_offset.top+"px",
                left: tip_offset.left+"px"});
        }
    };

    return tooltip;
});
<commit_msg>always load ajax tooltips - don't cache their content<commit_after>/**
 * @license
 * Patterns @VERSION@ tooltip - tooltips
 *
 * Copyright 2008-2012 Simplon B.V.
 * Copyright 2011 Humberto Sermeño
 * Copyright 2011 SYSLAB.COM GmbH
 */
define([
    'require',
    '../core/init',
    '../utils'
], function(require) {
    var utils = require('../utils'),
        mapal = require('../core/init');

    var tooltip = {
        count: 0,

        init: function() {
        },

        initContent: function(root) {
            var $root = $(root);
            var init = function($trigger) {
                var options = utils.parseOptions($trigger.data("tooltip"));
                options.title = $trigger.attr("title");
                $trigger.removeAttr("title");
                $trigger.data("mapal.tooltip", options);
                tooltip.setupShowEvents($trigger);
            };
            if ($root.is('[data-tooltip]')) init($root);
            $("*[data-tooltip]", $root).each(function() {
                init($(this));
            });
        },

        setupShowEvents: function($trigger) {
            var parameters = $trigger.data("mapal.tooltip");
            if (parameters.click) {
                $trigger.on("click.tooltip", $trigger, tooltip.show);
            } else {
                $trigger.on("mouseover.tooltip", $trigger, tooltip.show);
                // Make sure click on the trigger element becomes a NOP
                $trigger.on("click.tooltip", $trigger, tooltip.blockDefault);
            }
        },

        removeShowEvents: function($trigger) {
            $trigger.off(".tooltip");
        },

        setupHideEvents: function($trigger) {
            var $container = tooltip.getContainer($trigger),
                parameters = $trigger.data("mapal.tooltip");
            if (parameters.sticky) {
                $container.find(".closePanel")
                    .on("click.tooltip", $trigger, tooltip.hide);
                // Make sure click on the trigger element becomes a NOP
                $trigger.on("click.tooltip", $trigger, tooltip.blockDefault);
            } else {
                if (parameters.click) {
                    $container.on("click.tooltip", $trigger, function(ev) {
                        ev.stopPropagation();
                    });
                    $(document).on("click.tooltip", $trigger, tooltip.hide);
                    $trigger.on("click.tooltip", tooltip.blockDefault);
                    // close if something inside the tooltip triggered an injection
                    $container.on('patterns-inject-triggered.tooltip',
                                  $trigger, tooltip.hide);
                    $container.on('patterns-inject_interim-triggered.tooltip',
                                  $trigger, tooltip.hide);
                    $container.on('submit.tooltip', $trigger, tooltip.hide);
                } else {
                    $container.on("click.tooltip", $trigger, tooltip.hide);
                    $trigger.on("mouseleave.tooltip", $trigger, tooltip.hide);
                    $trigger.on("click.tooltip", tooltip.blockDefault);
                }
            }
        },

        removeHideEvents: function($trigger) {
            var $container = tooltip.getContainer($trigger);
            $(document).off(".tooltip");
            $container.off(".tooltip");
            $container.find(".closePanel").off(".tooltip");
            $trigger.off(".tooltip");
        },

        blockDefault: function(event) {
            event.preventDefault();
        },

        show: function(event) {
            var $trigger = event.data,
                $container = tooltip.getContainer($trigger),
                options = $trigger.data("mapal.tooltip");

            tooltip.removeShowEvents($trigger);
	    // Wrap in a timeout to make sure this click is not used to
	    // trigger a hide as well.
	    setTimeout(function() { tooltip.setupHideEvents($trigger) }, 50);

            function ajax_show() {
                $container.find(">div >*").css("opacity", 1);
                tooltip.positionContainer($trigger, $container);
            }

            if (options.ajax) {
                var source = $trigger.attr("href").split("#"),
                    target_id = $container.find("progress").attr("id");
                mapal.injection.load($trigger, source[0], target_id+":replace", source[1] || [],
                        ajax_show, true);
                // always load fresh tooltips
                // delete options.ajax;
                $trigger.data("mapal.tooltip", options);
            }

            tooltip.positionContainer($trigger, $container);
            $container.css("visibility", "visible");

	    // reposition tooltip everytime we scroll
	    $trigger.parents(':scrollable').scroll(function () {
                 tooltip.positionContainer($trigger, $container);
	    });

            event.preventDefault();
        },

        hide: function(event) {
            var $trigger = event.data,
                $container = tooltip.getContainer($trigger);
            tooltip.removeHideEvents($trigger);
            $container.css("visibility", "hidden");
            tooltip.setupShowEvents($trigger);
        },

        getContainer: function($trigger) {
            var $container = $trigger.data("mapal.tooltip.container");
            if ($container===undefined) {
                $container=tooltip.createContainer($trigger);
                $trigger.data("mapal.tooltip.container", $container);
            }
            return $container;
        },

        createContainer: function($trigger) {
            var options = $trigger.data("mapal.tooltip"),
                $content, $container;

            $container = $("
", {"class": "tooltip-container"});
            $container.css("visibility", "hidden");
            if (options.ajax) {
                $content = $("<progress/>", {"id": "tooltip-" + ++tooltip.count});
            } else {
                $content = $("
").text(options.title);
            }
            $container.append(
                $("
").css("display", "block").append($content))
                .append($("", {"class": "pointer"}));
            if (options.sticky && !options.noclose) {
                $("<button/>", {"class": "closePanel"})
                    .text("Close")
                    .insertBefore($container.find("*"));
            }
            $("body").append($container);
            return $container;
        },

        boundingBox: function($el) {
            var box = $el.offset();
            box.height = $el.height();
            box.width = $el.width();
            box.bottom = box.top + box.height;
            box.right = box.left + box.width;
            return box;
        },

        positionStatus: function($trigger, $container) {
            var trigger_box = tooltip.boundingBox($trigger),
                tooltip_box = tooltip.boundingBox($container),
                $window = $(window),
                window_width = $window.width(),
                window_height = $window.height(),
                trigger_center,
                space = {},
                container_offset = {},
                tip_offset = {},
                cls = "";

            trigger_center = {top: trigger_box.top + (trigger_box.height/2),
                              left: trigger_box.left + (trigger_box.width/2)};
            space.top = trigger_box.top - $window.scrollTop();
            space.bottom = window_height - space.top - trigger_box.height;
            space.left = trigger_box.left - $window.scrollLeft();
            space.right = window_width - space.left - trigger_box.width;

            return {"space": space,
                    "trigger_center": trigger_center,
                    "trigger_box": trigger_box,
                    "tooltip_box": tooltip_box};
        },

        // Help function to determine the best position for a tooltip.  Takes
        // the positioning status (as generated by positionStatus) as input
        // and returns a two-character position indiciator.
        findBestPosition: function(status) {
            var space = status.space,
                 cls = "";

            if (space.top > Math.max(space.right, space.bottom, space.left)) {
                cls = "t";
            } else if (space.right > Math.max(space.bottom, space.left, space.top)) {
                cls = "r";
            } else if (space.bottom > Math.max(space.left, space.top, space.right)) {
                cls = "b";
            } else {
                cls = "l";
            }

            switch (cls[0]) {
            case "t":
            case "b":
                if (Math.abs(space.left-space.right) < 20) {
                    cls += "m";
                } else if (space.left > space.right) {
                    cls += "r";
                } else {
                    cls += "l";
                }
                break;
            case "l":
            case "r":
                if (Math.abs(space.top-space.bottom) < 20) {
                    cls += "m";
                } else if (space.top > space.bottom) {
                    cls += "b";
                } else {
                    cls += "t";
                }
            }
            return cls;
        },

        isVisible: function(status, position) {
            var space = status.space,
                tooltip_box = status.tooltip_box;

            switch (position[0]) {
            case "t":
                if (tooltip_box.height > space.bottom) {
                    return false;
                }
                break;
            case "r":
                if (tooltip_box.width > space.left) {
                    return false;
                }
                break;
            case "b":
                if (tooltip_box.height > space.top) {
                    return false;
                }
                break;
            case "l":
                if (tooltip_box.width > space.right) {
                    return false;
                }
                break;
            default:
                return false;
            }

            switch (position[0]) {
            case "t":
            case "b":
                switch (position[1]) {
                    case "l":
                        if ((tooltip_box.width-20)>space.right) {
                            return false;
                        }
                        break;
                    case "m":
                        if ((tooltip_box.width/2)>space.left || (tooltip_box.width/2)>space.right) {
                            return false;
                        }
                        break;
                    case "r":
                        if ((tooltip_box.width-20)>space.left) {
                            return false;
                        }
                        break;
                    default:
                        return false;
                }
                break;
            case "l":
            case "r":
                switch (position[1]) {
                    case "t":
                        if ((tooltip_box.height-20)>space.bottom) {
                            return false;
                        }
                        break;
                    case "m":
                        if ((tooltip_box.height/2)>space.top || (tooltip_box.height/2)>space.bottom) {
                            return false;
                        }
                        break;
                    case "b":
                        if ((tooltip_box.height-20)>space.top) {
                            return false;
                        }
                    default:
                        return false;
                }
                break;
            }
            return true;
        },

        VALIDPOSITION: /^([lr][tmb]|[tb][lmr])$/,

        positionContainer: function($trigger, $container) {
            var status = tooltip.positionStatus($trigger, $container),
                options = $trigger.data("mapal.tooltip"),
                container_offset = {},
                tip_offset = {},
                position;

            if (options.position) {
                var positions = options.position.split("-"), i;
                for (i=0; i<positions.length; i++) {
                    if (!tooltip.VALIDPOSITION.test(positions[i])) {
                        continue;
                    }

                    if (options.forcePosition || tooltip.isVisible(status, positions[i])) {
                        position = positions[i];
                        break;
                    }
                }
            }

            if (!position) {
                position = tooltip.findBestPosition(status);
            }

            var trigger_box = status.trigger_box,
                tooltip_box = status.tooltip_box,
                trigger_center = status.trigger_center;

            switch (position[0]) {
            case "t":
                container_offset.top = trigger_box.bottom + 20;
                tip_offset.top = -23;
                break;
            case "r":
                container_offset.left = trigger_box.right + 20;
                tip_offset.left = 0;
                break;
            case "b":
                container_offset.top = trigger_box.top - tooltip_box.height + 10;
                tip_offset.top = tooltip_box.height - 23;
                break;
            case "l":
                container_offset.left = trigger_box.left - tooltip_box.width - 20;
                tip_offset.left = tooltip_box.width - 23;
                break;
            }

            switch (position[0]) {
            case "t":
            case "b":
                switch (position[1]) {
                case "l":
                    container_offset.left = trigger_center.left - 20;
                    tip_offset.left = 0;
                    break;
                case "m":
                    container_offset.left = trigger_center.left - (tooltip_box.width/2);
                    tip_offset.left = tooltip_box.width/2 - 10;
                    break;
                case "r":
                    container_offset.left = trigger_center.left + 29 - tooltip_box.width;
                    tip_offset.left = tooltip_box.width - 20;
                    break;
                }
                break;
            case "l":
            case "r":
                switch (position[1]) {
                    case "t":
                        container_offset.top = trigger_center.top - 30;
                        tip_offset.top = 0;
                        break;
                    case "m":
                        container_offset.top = trigger_center.top - (tooltip_box.height/2);
                        tip_offset.top = tooltip_box.height/2 - 10;
                        break;
                    case "b":
                        container_offset.top = trigger_center.top + 20 - tooltip_box.height;
                        tip_offset.top = tooltip_box.height - 20;
                        break;
                }
                break;
            }

            $container.attr("class", "tooltip-container " + position);
            $container.css({
                top: container_offset.top+"px",
                left: container_offset.left+"px"});
            $container.find(".pointer").css({
                top: tip_offset.top+"px",
                left: tip_offset.left+"px"});
        }
    };

    return tooltip;
});
<|endoftext|>


<commit_before>/*jshint expr: true*/ // prevent error in ...be.a.Function

describe('taaspace', function () {

  it('should have submodules', function () {
    taaspace.should.have.keys('Taa', 'Space', 'HTMLSpaceView',
      'version');
  });

  describe('Taa', function () {
    it('should fire "loaded" event', function (done) {
      var taa = new taaspace.Taa('assets/taa.png');
      taa.on('loaded', function (err, taa2) {
        should.equal(err, null);
        taa2.image.should.equal(taa.image);
        done();
      });
    });
  });

  describe('HTMLSpaceView', function () {
    var space;
    var view;

    beforeEach(function () {
      // Reset the sandbox
      var cont = document.getElementById('taaspace-sandbox');
      cont.innerHTML = '';
      space = new taaspace.Space();
      view = new taaspace.HTMLSpaceView(space, cont);
    });

    // Easier to debug
    afterEach(function () {
      if (this.currentTest.state === 'failed') {
        takeScreenshot();
      }
    });

    it('should be able to create an img element immediately', function () {
      // Without need to wait for the image to load
      var taa = new taaspace.Taa('assets/taa.png');
      var spacetaa = space.add(taa);
      var el = $('img.taaspace-taa');
      el.should.exist;
      var st2 = view.getSpaceTaaByElementId(el.attr('id'));
      st2.should.equal(spacetaa);
    });

    it('should position the taa correctly', function (done) {
      var taa = new taaspace.Taa('assets/taa.png');
      var spacetaa = space.add(taa);
      spacetaa.at([0,0]).to(view).xy.should.eql([0,0]);
      spacetaa.atNorm([1,1]).to(view).xy.should.eql([256,256]);
      spacetaa.atNorm([1,1]).xy.should.eql([256,256]);
      spacetaa.translate(spacetaa.at([0,0]), view.at([256,256]));
      setTimeout(function () {
        spacetaa.at([0,0]).to(view).xy.should.eql([256,256]);
        done();
      }, 200);
    });

    it('should be able to translate', function () {
      var taa = new taaspace.Taa('assets/taa.png');
      var spacetaa = space.add(taa);
      spacetaa.translate(spacetaa.atNorm([0,0]), spacetaa.atNorm([1,1]));
      var el1 = document.elementFromPoint(300, 300); // null if outside window
      //console.log('elem', el1);
      var el2 = $('img.taaspace-taa')[0];
      el1.should.equal(el2);
    });
  });

  /*
  describe('SpaceTaa', function () {
    var space, view, taa;

    beforeEach(function (done) {
      var cont = document.getElementById('taaspace-sandbox');
      cont.innerHTML = '';
      space = new taaspace.Space();
      view = new taaspace.HTMLSpaceView(space, cont);
      taa = new taaspace.Taa('assets/taa.png', done);
    });

    it('should have an id', function () {
      var a = space.add(taa);
      var b = space.add(taa);
      a.should.have.property('id');
      a.id.should.be.a.String;
      b.id.should.be.a.String;
      a.id.should.not.equal(b.id);
    });

    it('should be removable', function () {
      var a = space.add(taa);
      a.remove();
      space.content.hasOwnProperty(a.id).should.equal(false);
    });

    it('should be able to return a SpacePoint', function () {
      var a = space.add(taa);
      var p = a.at(new taaspace.Vector2D(1, 1));
      var vp = p.projectTo(view);
      var epsilon = 0.01;
      var val = 256;
      vp.xy.x.should.be.within(val - epsilon, val + epsilon);
      vp.xy.y.should.be.within(val - epsilon, val + epsilon);
    });

    it('should be transformable', function () {
      var a = space.add(taa);
      var r180o = (new taaspace.Matrix2D()).rotate(Math.PI);
      a.transformBy(r180o);
      var p = a.at(new taaspace.Vector2D(1, 1));
      var vp = p.projectTo(view);
      var epsilon = 0.01;
      var val = -256;
      vp.xy.x.should.be.within(val - epsilon, val + epsilon);
      vp.xy.y.should.be.within(val - epsilon, val + epsilon);
    });
  });*/

});
<commit_msg>Revived old SpaceTaa tests<commit_after>/*jshint expr: true*/ // prevent error in ...be.a.Function

describe('taaspace', function () {

  function getEmptyContainer() {
    var cont = document.getElementById('taaspace-sandbox');
    cont.innerHTML = '';
    return cont;
  }

  it('should have submodules', function () {
    taaspace.should.have.keys('Taa', 'Space', 'HTMLSpaceView',
      'version');
  });

  describe('Taa', function () {
    it('should fire "loaded" event', function (done) {
      var taa = new taaspace.Taa('assets/taa.png');
      taa.on('loaded', function (err, taa2) {
        should.equal(err, null);
        taa2.image.should.equal(taa.image);
        done();
      });
    });
  });

  describe('HTMLSpaceView', function () {
    var space;
    var view;

    beforeEach(function () {
      var cont = getEmptyContainer();
      space = new taaspace.Space();
      view = new taaspace.HTMLSpaceView(space, cont);
    });

    // Easier to debug
    afterEach(function () {
      if (this.currentTest.state === 'failed') {
        takeScreenshot();
      }
    });

    it('should be able to create an img element immediately', function () {
      // Without need to wait for the image to load
      var taa = new taaspace.Taa('assets/taa.png');
      var spacetaa = space.add(taa);
      var el = $('img.taaspace-taa');
      el.should.exist;
      var st2 = view.getSpaceTaaByElementId(el.attr('id'));
      st2.should.equal(spacetaa);
    });

    it('should position the taa correctly', function (done) {
      var taa = new taaspace.Taa('assets/taa.png');
      var spacetaa = space.add(taa);
      spacetaa.at([0,0]).to(view).xy.should.eql([0,0]);
      spacetaa.atNorm([1,1]).to(view).xy.should.eql([256,256]);
      spacetaa.atNorm([1,1]).xy.should.eql([256,256]);
      spacetaa.translate(spacetaa.at([0,0]), view.at([256,256]));
      setTimeout(function () {
        spacetaa.at([0,0]).to(view).xy.should.eql([256,256]);
        done();
      }, 200);
    });

    it('should be able to translate', function () {
      var taa = new taaspace.Taa('assets/taa.png');
      var spacetaa = space.add(taa);
      spacetaa.translate(spacetaa.atNorm([0,0]), spacetaa.atNorm([1,1]));
      var el1 = document.elementFromPoint(300, 300); // null if outside window
      //console.log('elem', el1);
      var el2 = $('img.taaspace-taa')[0];
      el1.should.equal(el2);
    });
  });

  describe('SpaceTaa', function () {
    var space, view, taa;

    beforeEach(function (done) {
      var cont = getEmptyContainer();
      space = new taaspace.Space();
      view = new taaspace.HTMLSpaceView(space, cont);
      taa = new taaspace.Taa('assets/taa.png', done);
    });

    it('should have an id', function () {
      var a = space.add(taa);
      var b = space.add(taa);
      a.should.have.property('id');
      a.id.should.be.a.String;
      b.id.should.be.a.String;
      a.id.should.not.equal(b.id);
    });

    it('should be removable', function () {
      var a = space.add(taa);
      a.remove();
      space.content.hasOwnProperty(a.id).should.equal(false);
    });

    it('should be able to return a SpacePoint', function () {
      var a = space.add(taa);
      var p = a.atNorm([1,1]);
      var vp = p.to(view);
      var epsilon = 0.01;
      var val = 256;
      vp.xy[0].should.be.within(val - epsilon, val + epsilon);
      vp.xy[1].should.be.within(val - epsilon, val + epsilon);
    });
  });

});
<|endoftext|>


<commit_before>// import { SERVER_RESPONSE_DELAY } from "../../_support/constants/Timeouts";
function setFilter(param) {
  cy.visitUrl({ url: "/services/overview" });
  cy.get("[placeholder='Filter']").click();
  cy.get("label").contains(param).click();
}

function testFilterByStatus(param) {
  setFilter(param);

  cy
    .get(".service-table")
    .getTableColumn("Status")
    .get(".status-bar-text")
    .contents()
    .each(function(v) {
      expect(v).to.eq(param);
    });
}

describe("Services Filter", function() {
  context("Status", function() {
    context("Running / Deploying tasks", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-task-healthy",
          nodeHealth: true
        });
      });

      it("Filters Running services", function() {
        testFilterByStatus("Running");
      });

      it("Filters Deploying services", function() {
        testFilterByStatus("Deploying");
      });
    });

    context("Suspended tasks", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-service-suspended",
          nodeHealth: true
        });
      });

      it("Filters Stopped services", function() {
        testFilterByStatus("Stopped");
      });
    });

    context("Recovering tasks", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-service-recovering",
          nodeHealth: true,
          mesosStream: true
        });
      });

      it("Filters Recovering services", function() {
        testFilterByStatus("Recovering");
      });
    });

    context("Deleting tasks", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-service-deleting",
          nodeHealth: true
        });
      });

      it("Filters Deleting services", function() {
        testFilterByStatus("Deleting");
      });
    });
  });

  context("Health", function() {
    beforeEach(function() {
      cy.configureCluster({
        mesos: "1-task-healthy",
        nodeHealth: true
      });
    });

    it("filters Healthy services", function() {
      setFilter("Healthy");

      cy
        .get(".service-table")
        .getTableColumn("Name")
        .get(".table-cell-link-primary")
        .contents()
        .each(function(v) {
          expect(v).to.eq("sleep");
        });
    });

    it("filters Unhealthy services", function() {
      setFilter("Unhealthy");

      cy
        .get(".service-table")
        .getTableColumn("Name")
        .get(".table-cell-link-primary")
        .contents()
        .should("deep.equal", ["unhealthy", "unhealthy-sleep"]);
    });

    it("filters N/A services", function() {
      setFilter("N/A");

      cy
        .get(".service-table")
        .getTableColumn("Name")
        .get(".table-cell-link-primary")
        .contents()
        .should("deep.equal", ["group-with-pods", "podEFGH"]);
    });
  });

  context("Other", function() {
    context("SDK", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-sdk-service",
          nodeHealth: true
        });
      });

      it("filters SDK services", function() {
        setFilter("Catalog");

        cy
          .get(".service-table")
          .getTableColumn("Name")
          .get(".table-cell-link-primary")
          .contents()
          .each(function(v) {
            expect(v).to.eq("sdk-sleep");
          });
      });
    });

    context("Pods", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-task-healthy",
          nodeHealth: true
        });
      });

      it("filters Pods", function() {
        setFilter("Pod");

        cy
          .get(".service-table")
          .getTableColumn("Name")
          .get(".table-cell-link-primary")
          .contents()
          .each(function(v) {
            expect(v).to.eq("podEFGH");
          });
      });
    });

    context("Volumes", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-task-healthy",
          nodeHealth: true
        });
      });

      it("filters services with Volumes", function() {
        setFilter("Volumes");

        cy
          .get(".service-table")
          .getTableColumn("Name")
          .get(".table-cell-link-primary")
          .contents()
          .each(function(v) {
            expect(v).to.eq("sleep");
          });
      });
    });
  });
});
<commit_msg>fix(ServicesFilter-cy.js): fix SDK service filter test<commit_after>// import { SERVER_RESPONSE_DELAY } from "../../_support/constants/Timeouts";
function setFilter(param) {
  cy.visitUrl({ url: "/services/overview" });
  cy.get("[placeholder='Filter']").click();
  cy.get("label")
    .contains(param)
    .click();
}

function testFilterByStatus(param) {
  setFilter(param);

  cy.get(".service-table")
    .getTableColumn("Status")
    .get(".status-bar-text")
    .contents()
    .each(function(v) {
      expect(v).to.eq(param);
    });
}

describe("Services Filter", function() {
  context("Status", function() {
    context("Running / Deploying tasks", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-task-healthy",
          nodeHealth: true
        });
      });

      it("Filters Running services", function() {
        testFilterByStatus("Running");
      });

      it("Filters Deploying services", function() {
        testFilterByStatus("Deploying");
      });
    });

    context("Suspended tasks", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-service-suspended",
          nodeHealth: true
        });
      });

      it("Filters Stopped services", function() {
        testFilterByStatus("Stopped");
      });
    });

    context("Recovering tasks", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-service-recovering",
          nodeHealth: true,
          mesosStream: true
        });
      });

      it("Filters Recovering services", function() {
        testFilterByStatus("Recovering");
      });
    });

    context("Deleting tasks", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-service-deleting",
          nodeHealth: true
        });
      });

      it("Filters Deleting services", function() {
        testFilterByStatus("Deleting");
      });
    });
  });

  context("Health", function() {
    beforeEach(function() {
      cy.configureCluster({
        mesos: "1-task-healthy",
        nodeHealth: true
      });
    });

    it("filters Healthy services", function() {
      setFilter("Healthy");

      cy.get(".service-table")
        .getTableColumn("Name")
        .get(".table-cell-link-primary")
        .contents()
        .each(function(v) {
          expect(v).to.eq("sleep");
        });
    });

    it("filters Unhealthy services", function() {
      setFilter("Unhealthy");

      cy.get(".service-table")
        .getTableColumn("Name")
        .get(".table-cell-link-primary")
        .contents()
        .should("deep.equal", ["unhealthy", "unhealthy-sleep"]);
    });

    it("filters N/A services", function() {
      setFilter("N/A");

      cy.get(".service-table")
        .getTableColumn("Name")
        .get(".table-cell-link-primary")
        .contents()
        .should("deep.equal", ["group-with-pods", "podEFGH"]);
    });
  });

  context("Other", function() {
    context("SDK", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-sdk-service",
          nodeHealth: true
        });
      });

      it("filters SDK services", function() {
        setFilter("Catalog");

        const serviceNames = ["sdk-sleep", "sdk-sleep-with-image"];

        cy.get(".service-table")
          .getTableColumn("Name")
          .get(".table-cell-link-primary")
          .contents()
          .each(function(v, index) {
            expect(v).to.eq(serviceNames[index]);
          });
      });
    });

    context("Pods", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-task-healthy",
          nodeHealth: true
        });
      });

      it("filters Pods", function() {
        setFilter("Pod");

        cy.get(".service-table")
          .getTableColumn("Name")
          .get(".table-cell-link-primary")
          .contents()
          .each(function(v) {
            expect(v).to.eq("podEFGH");
          });
      });
    });

    context("Volumes", function() {
      beforeEach(function() {
        cy.configureCluster({
          mesos: "1-task-healthy",
          nodeHealth: true
        });
      });

      it("filters services with Volumes", function() {
        setFilter("Volumes");

        cy.get(".service-table")
          .getTableColumn("Name")
          .get(".table-cell-link-primary")
          .contents()
          .each(function(v) {
            expect(v).to.eq("sleep");
          });
      });
    });
  });
});
<|endoftext|>


<commit_before>var expect = require('chai').expect;

describe('template strings', function() {
  it('should be a string', function () {
    var string = 'abc';

    expect(string).to.be.a('string');

  });
  it('can evaluate variables', function () {
    var bar = `baz`;
    var string = `foo${bar}`;

    expect(string).to.equal('foobaz');

    });
    it('can execute functions', function () {
    var string = `The date is: ${new Date()}`;
    var date = new Date();
    expect(string).to.equal('The date is: ' + date);
    });
    it('can evaluate expressions', function () {
     var string = 2;

     expect(string).to.equal(1 + 1);

    });
    it('can test multi-line strings', function () {
    var string = `Hello\n
                  World`;

    expect(string).to.equal('Hello\n                World');

    });
  });
<commit_msg>added block scope and destrutoring tests<commit_after>var expect = require('chai').expect;

describe('template strings', function() {
  it('should be a string', function () {
    var string = 'abc';

    expect(string).to.be.a('string');

  });
  it('can evaluate variables', function () {
    var bar = `baz`;
    var string = `foo${bar}`;

    expect(string).to.equal('foobaz');

    });
    it('can execute functions', function () {
    var string = `The date is: ${new Date()}`;
    var date = new Date();
    expect(string).to.equal('The date is: ' + date);
    });
    it('can evaluate expressions', function () {
     var string = 2;

     expect(string).to.equal(1 + 1);

    });
    //it('can test multi-line strings', function () {
    //var string = `Hello\n
                  //World`;

    //expect(string).to.equal('Hello\n                World');

    //});
  });
<|endoftext|>


<commit_before>var remote = {
  host: document.location.hostname + ':1234'
};

module('replication', {
  setup : function () {
    this.name = 'idb://test_suite_db';
    this.remote = 'http://' + remote.host + '/test_suite_db/';
  }
});

var docs = [
  {_id: "0", integer: 0, string: '0'},
  {_id: "1", integer: 1, string: '1'},
  {_id: "2", integer: 2, string: '2'}
];

asyncTest("Test basic pull replication", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.bulkDocs({docs: docs}, {}, function(err, results) {
      db.replicate.from(self.remote, function(err, result) {
        ok(result.ok, 'replication was ok');
        ok(result.docs_written = docs.length, 'correct # docs written');
        start();
      });
    });
  });
});

asyncTest("Local DB contains documents", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.bulkDocs({docs: docs}, {}, function(err, _) {
      db.bulkDocs({docs: docs}, {}, function(err, _) {
        db.replicate.from(self.remote, function(err, _) {
          db.allDocs(function(err, result) {
            ok(result.rows.length === docs.length, 'correct # docs exist');
            start();
          });
        });
      });
    });
  });
});

asyncTest("Test basic push replication", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    db.bulkDocs({docs: docs}, {}, function(err, results) {
      db.replicate.to(self.remote, function(err, result) {
        ok(result.ok, 'replication was ok');
        ok(result.docs_written === docs.length, 'correct # docs written');
        start();
      });
    });
  });
});

asyncTest("Test basic push replication take 2", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    db.bulkDocs({docs: docs}, {}, function(err, _) {
      db.replicate.to(self.remote, function(err, _) {
        remote.allDocs(function(err, result) {
          ok(result.rows.length === docs.length, 'correct # docs written');
          start();
        });
      });
    });
  });
});

asyncTest("Test checkpoint", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.bulkDocs({docs: docs}, {}, function(err, results) {
      db.replicate.from(self.remote, function(err, result) {
        ok(result.ok, 'replication was ok');
        ok(result.docs_written === docs.length, 'correct # docs written');
        db.replicate.from(self.remote, function(err, result) {
          ok(result.ok, 'replication was ok');
          ok(result.docs_written === 0, 'correct # docs written');
          ok(result.docs_read === 0, 'no docs read');
          start();
        });
      });
    });
  });
});

asyncTest("Test checkpoint 2", function() {
  var self = this;
  var doc = {_id: "3", count: 0};
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.put(doc, {}, function(err, results) {
      db.replicate.from(self.remote, function(err, result) {
        ok(result.ok, 'replication was ok');
        doc._rev = results.rev;
        doc.count++;
        remote.put(doc, {}, function(err, results) {
          doc._rev = results.rev;
          doc.count++;
          remote.put(doc, {}, function(err, results) {
            db.replicate.from(self.remote, function(err, result) {
              ok(result.ok, 'replication was ok');
              ok(result.docs_written === 1, 'correct # docs written');
              start();
            });
          });
        });
      });
    });
  });
});

asyncTest("Test checkpoint 3 :)", function() {
  var self = this;
  var doc = {_id: "3", count: 0};
  initDBPair(this.name, this.remote, function(db, remote) {
    db.put(doc, {}, function(err, results) {
      Pouch.replicate(db, remote, {}, function(err, result) {
        ok(result.ok, 'replication was ok');
        doc._rev = results.rev;
        doc.count++;
        db.put(doc, {}, function(err, results) {
          doc._rev = results.rev;
          doc.count++;
          db.put(doc, {}, function(err, results) {
            Pouch.replicate(db, remote, {}, function(err, result) {
              ok(result.ok, 'replication was ok');
              ok(result.docs_written === 1, 'correct # docs written');
              start();
            });
          });
        });
      });
    });
  });
});

// CouchDB will not generate a conflict here, it uses a deteministic
// method to generate the revision number, however we cannot copy its
// method as it depends on erlangs internal data representation
asyncTest("Test basic conflict", function() {
  var self = this;
  var doc1 = {_id: 'adoc', foo:'bar'};
  var doc2 = {_id: 'adoc', bar:'baz'};
  initDBPair(this.name, this.remote, function(db, remote) {
    db.put(doc1, function(err, localres) {
      remote.put(doc2, function(err, remoteres) {
        db.replicate.to(self.remote, function(err, _) {
          remote.get('adoc', {conflicts: true}, function(err, result) {
            ok(result._conflicts, 'result has a conflict');
            start();
          });
        });
      });
    });
  });
});

asyncTest("Test basic continous pull replication", function() {
  var self = this;
  var doc1 = {_id: 'adoc', foo:'bar'};
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.bulkDocs({docs: docs}, {}, function(err, results) {
      var count = 0;
      var rep = db.replicate.from(self.remote, {continuous: true});
      var change = db.changes({
        onChange: function(change) {
          ++count;
          if (count === 4) {
            ok(true, 'Got all the changes');
            start();
          }
        },
        continuous: true,
      });
      setTimeout(function() {
        remote.put(doc1);
      }, 50);
    });
  });
});

asyncTest("Test basic continous push replication", function() {
  var self = this;
  var doc1 = {_id: 'adoc', foo:'bar'};
  initDBPair(this.name, this.remote, function(db, remote) {
    db.bulkDocs({docs: docs}, {}, function(err, results) {
      var count = 0;
      var rep = remote.replicate.from(db, {continuous: true});
      var change = remote.changes({
        onChange: function(change) {
          ++count;
          if (count === 4) {
            ok(true, 'Got all the changes');
            start();
          }
        },
        continuous: true,
      });
      setTimeout(function() {
        db.put(doc1, {});
      }, 50);
    });
  });
});
<commit_msg>Add test to cancel replication<commit_after>var remote = {
  host: document.location.hostname + ':1234'
};

module('replication', {
  setup : function () {
    this.name = 'idb://test_suite_db';
    this.remote = 'http://' + remote.host + '/test_suite_db/';
  }
});

var docs = [
  {_id: "0", integer: 0, string: '0'},
  {_id: "1", integer: 1, string: '1'},
  {_id: "2", integer: 2, string: '2'}
];

asyncTest("Test basic pull replication", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.bulkDocs({docs: docs}, {}, function(err, results) {
      db.replicate.from(self.remote, function(err, result) {
        ok(result.ok, 'replication was ok');
        ok(result.docs_written = docs.length, 'correct # docs written');
        start();
      });
    });
  });
});

asyncTest("Local DB contains documents", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.bulkDocs({docs: docs}, {}, function(err, _) {
      db.bulkDocs({docs: docs}, {}, function(err, _) {
        db.replicate.from(self.remote, function(err, _) {
          db.allDocs(function(err, result) {
            ok(result.rows.length === docs.length, 'correct # docs exist');
            start();
          });
        });
      });
    });
  });
});

asyncTest("Test basic push replication", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    db.bulkDocs({docs: docs}, {}, function(err, results) {
      db.replicate.to(self.remote, function(err, result) {
        ok(result.ok, 'replication was ok');
        ok(result.docs_written === docs.length, 'correct # docs written');
        start();
      });
    });
  });
});

asyncTest("Test basic push replication take 2", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    db.bulkDocs({docs: docs}, {}, function(err, _) {
      db.replicate.to(self.remote, function(err, _) {
        remote.allDocs(function(err, result) {
          ok(result.rows.length === docs.length, 'correct # docs written');
          start();
        });
      });
    });
  });
});

asyncTest("Test checkpoint", function() {
  var self = this;
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.bulkDocs({docs: docs}, {}, function(err, results) {
      db.replicate.from(self.remote, function(err, result) {
        ok(result.ok, 'replication was ok');
        ok(result.docs_written === docs.length, 'correct # docs written');
        db.replicate.from(self.remote, function(err, result) {
          ok(result.ok, 'replication was ok');
          ok(result.docs_written === 0, 'correct # docs written');
          ok(result.docs_read === 0, 'no docs read');
          start();
        });
      });
    });
  });
});

asyncTest("Test checkpoint 2", function() {
  var self = this;
  var doc = {_id: "3", count: 0};
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.put(doc, {}, function(err, results) {
      db.replicate.from(self.remote, function(err, result) {
        ok(result.ok, 'replication was ok');
        doc._rev = results.rev;
        doc.count++;
        remote.put(doc, {}, function(err, results) {
          doc._rev = results.rev;
          doc.count++;
          remote.put(doc, {}, function(err, results) {
            db.replicate.from(self.remote, function(err, result) {
              ok(result.ok, 'replication was ok');
              ok(result.docs_written === 1, 'correct # docs written');
              start();
            });
          });
        });
      });
    });
  });
});

asyncTest("Test checkpoint 3 :)", function() {
  var self = this;
  var doc = {_id: "3", count: 0};
  initDBPair(this.name, this.remote, function(db, remote) {
    db.put(doc, {}, function(err, results) {
      Pouch.replicate(db, remote, {}, function(err, result) {
        ok(result.ok, 'replication was ok');
        doc._rev = results.rev;
        doc.count++;
        db.put(doc, {}, function(err, results) {
          doc._rev = results.rev;
          doc.count++;
          db.put(doc, {}, function(err, results) {
            Pouch.replicate(db, remote, {}, function(err, result) {
              ok(result.ok, 'replication was ok');
              ok(result.docs_written === 1, 'correct # docs written');
              start();
            });
          });
        });
      });
    });
  });
});

// CouchDB will not generate a conflict here, it uses a deteministic
// method to generate the revision number, however we cannot copy its
// method as it depends on erlangs internal data representation
asyncTest("Test basic conflict", function() {
  var self = this;
  var doc1 = {_id: 'adoc', foo:'bar'};
  var doc2 = {_id: 'adoc', bar:'baz'};
  initDBPair(this.name, this.remote, function(db, remote) {
    db.put(doc1, function(err, localres) {
      remote.put(doc2, function(err, remoteres) {
        db.replicate.to(self.remote, function(err, _) {
          remote.get('adoc', {conflicts: true}, function(err, result) {
            ok(result._conflicts, 'result has a conflict');
            start();
          });
        });
      });
    });
  });
});

asyncTest("Test basic continous pull replication", function() {
  var self = this;
  var doc1 = {_id: 'adoc', foo:'bar'};
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.bulkDocs({docs: docs}, {}, function(err, results) {
      var count = 0;
      var rep = db.replicate.from(self.remote, {continuous: true});
      var change = db.changes({
        onChange: function(change) {
          ++count;
          if (count === 4) {
            ok(true, 'Got all the changes');
            start();
          }
        },
        continuous: true,
      });
      setTimeout(function() {
        remote.put(doc1);
      }, 50);
    });
  });
});

asyncTest("Test basic continous push replication", function() {
  var self = this;
  var doc1 = {_id: 'adoc', foo:'bar'};
  initDBPair(this.name, this.remote, function(db, remote) {
    db.bulkDocs({docs: docs}, {}, function(err, results) {
      var count = 0;
      var rep = remote.replicate.from(db, {continuous: true});
      var change = remote.changes({
        onChange: function(change) {
          ++count;
          if (count === 4) {
            ok(true, 'Got all the changes');
            start();
          }
        },
        continuous: true,
      });
      setTimeout(function() {
        db.put(doc1, {});
      }, 50);
    });
  });
});

asyncTest("Test cancel pull replication", function() {
  var self = this;
  var doc1 = {_id: 'adoc', foo:'bar'};
  initDBPair(this.name, this.remote, function(db, remote) {
    remote.bulkDocs({docs: docs}, {}, function(err, results) {
      var count = 0;
      var rep = db.replicate.from(self.remote, {continuous: true});
      var change = db.changes({
        onChange: function(change) {
          ++count;
          if (count === 4) {
            rep.cancel();
            remote.put(doc2);
            setTimeout(function() {
              ok(count === 4, 'got no more docs');
              start();
            }, 500);
          }
        },
        continuous: true,
      });
      setTimeout(function() {
        remote.put(doc1);
      }, 50);
    });
  });
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name       		Replace Editor on eBay.de
// @description		Replace eBay auctioneditor with TinyMCE and Dropbox integration
// @namespace		https://github.com/Netzvamp/tinymce-ebay
// @version			0.2
// @author			Robert Lieback (netzvamp)
// @supportURL 		https://github.com/Netzvamp/tinymce-ebay/issues
// @updateURL		https://rawgit.com/Netzvamp/tinymce-ebay/master/tinymce-ebay.de.user.js
// @downloadURL		https://rawgit.com/Netzvamp/tinymce-ebay/master/tinymce-ebay.de.user.js
// @match      		*://*.ebay.de/ws/eBayISAPI.dll*
// @copyright  		2015, Robert Lieback
// @require 		http://code.jquery.com/jquery-latest.js
// @require 		http://tinymce.cachefly.net/4.1/tinymce.min.js
// @require 		https://rawgit.com/Netzvamp/tinymce-ebay/master/langs/de.js
// ==/UserScript==

$(document).ready(function() {
    if ($("#description_secGrp").length) { // Check that we are on the right page

        $('#description').css('visibility', 'visible'); // Make textarea visible before adding tinymce to prevent problems
        $('#description').show();

        // Remove ebay editor
        $('#rte').hide();
        $('#rte_toolbar_inpGrp').hide();
        $('#descTabs').hide();

        // Add dropbox api
        $('head').append(''); // Replace with you own appkey

        tinyMCE.baseURL = 'http://tinymce.cachefly.net/4.1';
		tinymce.init({
			selector: 'textarea#description',
			relative_urls: false,
			width: '100%',
			height: 600,
			theme: "modern",
			fontsize_formats: "8pt 9pt 10pt 11pt 12pt 26pt 36pt",
			plugins: [
				"advlist autolink lists link image charmap print preview hr anchor pagebreak",
				"searchreplace wordcount visualblocks visualchars code fullscreen",
				"insertdatetime media nonbreaking save table contextmenu directionality",
				"emoticons paste textcolor colorpicker textpattern",
			],
			toolbar1: "insertfile undo redo | styleselect | fontselect | fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
			toolbar2: "print preview media | forecolor backcolor emoticons | db_template | db_image",
			image_advtab: true,
			allow_script_urls: true,
			valid_elements : '*[*]',
			valid_children : "+body[style],+body[link]",
			file_browser_callback: function(field_name, url, type, win) {
				Dropbox.choose({
					success: function(files) {
						$('#' + field_name).val(files[0].link.replace("dl=0", "dl=1"));
					},
					linkType: "direct",
					multiselect: false,
					extensions: ['.jpg', '.jpeg', '.png', '.gif'],
				});
			},
			setup: function(editor) { // We add an button to insert template from Dropbox
				editor.addButton('db_template', {
					text: 'Template einf\u00fcgen',
					title: 'Insert Template',
					icon: 'dropin-icon',
					onclick: function() {
						Dropbox.choose({
							success: function(files) {
								$.get(files[0].link, function(data) {
                                    // Load template in editor and replace {title} and {subtitle} in template with values from page
                                    editor.insertContent(data.replace('{title}', $('#title').val()).replace('{subtitle}', $('#subtitle').val()));
								});
							},
							linkType: "direct",
							multiselect: false,
							extensions: ['.txt', '.htm', '.html', '.tpl'],
						});
					}
				});
				editor.addButton('db_image', { // We add an button to insert image from Dropbox
					text: 'Bild einf\u00fcgen',
					title: 'insert',
					icon: 'dropin-icon',
					onclick: function() {
						Dropbox.choose({
							success: function(files) {
								editor.insertContent(''); // replace dl=0 to dl=1 to get imagefile and no preview page
							},
							linkType: "preview", // We have to use preview links, cause directlinks expire after some minutes
							multiselect: false,
							extensions: ['.jpg', '.jpeg', '.png', '.gif'],
						});
					}
				});
				editor.on('init', function(e) {
					$('.mce-i-dropin-icon').css({ // Add the dropbox icon to the buttons
						'display': 'inline-block',
						'vertical-align': 'middle',
						'background': 'transparent url("https://www.dropbox.com/static/images/widgets/dbx-saver-status.png") no-repeat',
					});
				});
			}
        });

    }
});<commit_msg>Changed Metadata to support more ebay TLDs<commit_after>// ==UserScript==
// @name           Replace Editor on eBay.de
// @description	   Replace eBay auctioneditor with TinyMCE and Dropbox integration
// @namespace      https://github.com/Netzvamp/tinymce-ebay
// @version        0.3
// @author         Robert Lieback (netzvamp)
// @supportURL     https://github.com/Netzvamp/tinymce-ebay/issues
// @updateURL      https://rawgit.com/Netzvamp/tinymce-ebay/master/tinymce-ebay.de.user.js
// @downloadURL    https://rawgit.com/Netzvamp/tinymce-ebay/master/tinymce-ebay.de.user.js
// @match          *://*.ebay.tld/ws/eBayISAPI.dll*
// @copyright      2015, Robert Lieback, Apache License 2.0
// @require        http://code.jquery.com/jquery-latest.js
// @require        http://tinymce.cachefly.net/4.1/tinymce.min.js
// @require        http://tinymce.cachefly.net/4.1/jquery.tinymce.min.js
// @require        https://rawgit.com/Netzvamp/tinymce-ebay/master/langs/de.js
// ==/UserScript==

$(document).ready(function() {
    if ($('#description_secGrp').length) { // Check that we are on the right page
        $('#description').css('visibility', 'visible'); // Make textarea visible before adding tinymce to prevent problems
        $('#description').show();
        // Remove ebay editor
        $('#rte').hide();
        $('#rte_toolbar_inpGrp').hide();
        $('#descTabs').hide();
        // Add dropbox api
        $('head').append(''); // Replace with you own appkey
        tinyMCE.baseURL = 'http://tinymce.cachefly.net/4.1';
        $('textarea#description').tinymce({
            //selector: 'textarea#description',
            relative_urls: false,
            width: '100%',
            height: 600,
            theme: 'modern',
            fontsize_formats: '8pt 9pt 10pt 11pt 12pt 26pt 36pt',
            plugins: [
                'advlist autolink lists link image charmap print preview hr anchor pagebreak',
                'searchreplace wordcount visualblocks visualchars code fullscreen',
                'insertdatetime media nonbreaking save table contextmenu directionality',
                'emoticons paste textcolor colorpicker textpattern',
            ],
            toolbar1: 'insertfile undo redo | styleselect | fontselect | fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
            toolbar2: 'print preview media | forecolor backcolor emoticons | db_template | db_image',
            image_advtab: true,
            allow_script_urls: true,
            valid_elements: '*[*]',
            valid_children: '+body[style],+body[link]',
            file_browser_callback: function(field_name, url, type, win) {
                Dropbox.choose({
                    success: function(files) {
                        $('#' + field_name).val(files[0].link.replace('dl=0', 'dl=1'));
                    },
                    linkType: 'direct',
                    multiselect: false,
                    extensions: [
                        '.jpg',
                        '.jpeg',
                        '.png',
                        '.gif'
                    ],
                });
            },
            setup: function(editor) { // We add an button to insert template from Dropbox
                editor.addButton('db_template', {
                    text: 'Template einfügen',
                    title: 'Insert Template',
                    icon: 'dropin-icon',
                    onclick: function() {
                        Dropbox.choose({
                            success: function(files) {
                                $.get(files[0].link, function(data) {
                                    // Load template in editor and replace {title} and {subtitle} in template with values from page
                                    editor.insertContent(data.replace('{title}', $('#title').val()).replace('{subtitle}', $('#subtitle').val()));
                                });
                            },
                            linkType: 'direct',
                            multiselect: false,
                            extensions: [
                                '.txt',
                                '.htm',
                                '.html',
                                '.tpl'
                            ],
                        });
                    }
                });
                editor.addButton('db_image', { // We add an button to insert image from Dropbox
                    text: 'Bild einfügen',
                    title: 'insert',
                    icon: 'dropin-icon',
                    onclick: function() {
                        Dropbox.choose({
                            success: function(files) {
                                editor.insertContent(''); // replace dl=0 to dl=1 to get imagefile and no preview page
                            },
                            linkType: 'preview', // We have to use preview links, cause directlinks expire after some minutes
                            multiselect: false,
                            extensions: [
                                '.jpg',
                                '.jpeg',
                                '.png',
                                '.gif'
                            ],
                        });
                    }
                });
                editor.on('init', function(e) {
                    $('.mce-i-dropin-icon').css({ // Add the dropbox icon to the buttons
                        'display': 'inline-block',
                        'vertical-align': 'middle',
                        'background': 'transparent url("https://www.dropbox.com/static/images/widgets/dbx-saver-status.png") no-repeat',
                    });
                });
            }
        });
    }
});<|endoftext|>


<commit_before>/**
 * @since 2019-09-22 05:30
 * @author vivaxy
 */
import * as ET from '../enums/event-types.js';
import * as GS from '../enums/game-state.js';

function init(ee) {
  let gameState = GS.NEW_GAME;
  let grid = Array.from({ length: 20 }, function() {
    return Array.from({ length: 10 }, function() {
      return null;
    });
  });
  let score = 0;
  let tetrominoMoving = false;
  let tetrominoDroping = false;
  let eliminatingRows = [];
  let speed = 100;
  let speedIndex = 0;

  ee.on(ET.GAME_STATE_CHANGE, handleGameStateChange);
  ee.on(ET.TICK, handleTick);
  ee.on(ET.TETROMINO_SETTLED, handleTetrominoSettled);
  ee.on(ET.TETROMINO_DOWN, handleTetrominoDown);

  function handleGameStateChange(et, { gameState: _gameState }) {
    gameState = _gameState;
    if (gameState === GS.PLAYING) {
      ee.emit(ET.UPDATE_GRID, { grid });
    }
  }

  function handleTick() {
    if (gameState === GS.PLAYING) {
      if (tetrominoDroping) {
        speedIndex = 0;
        ee.emit(ET.TETROMINO_MOVE);
      } else if (speedIndex > speed) {
        speedIndex = 0;
        if (tetrominoMoving) {
          ee.emit(ET.TETROMINO_MOVE);
        } else if (eliminatingRows.length) {
          let dropRowCount = 0;
          for (let i = grid.length - 1; i >= 0; i--) {
            if (eliminatingRows[eliminatingRows.length - 1] === i) {
              dropRowCount++;
              eliminatingRows.pop();
            }
            if (i - dropRowCount >= 0) {
              // TODO fix bug when eliminate multiple rows
              grid[i - dropRowCount].forEach(function(item, colIndex) {
                grid[i][colIndex] = item;
              });
            } else {
              grid[i].forEach(function(_, colIndex) {
                grid[i][colIndex] = null;
              });
            }
          }
          if (eliminatingRows.length !== 0) {
            throw new Error('Unexpect loop result');
          }
        } else {
          tetrominoMoving = true;
          ee.emit(ET.TETROMINO_CREATE);
        }
      } else {
        speedIndex++;
        if (eliminatingRows.length) {
          eliminatingRows.forEach(function(rowIndex) {
            grid[rowIndex].forEach(function(item) {
              if (item._color) {
                item.color = item._color;
                delete item._color;
              } else {
                item._color = item.color;
                item.color = '#fff';
              }
            });
          });
        }
      }
    }
  }

  function handleTetrominoSettled(et, { tetromino, position }) {
    tetrominoMoving = false;
    tetrominoDroping = false;
    score += 1;
    let gameOver = false;
    tetromino.forEach(function(row, rowIndex) {
      row.forEach(function(item) {
        if (item) {
          if (rowIndex + position[1] <= 0) {
            gameOver = true;
          }
        }
      });
    });

    eliminatingRows = [];
    grid.forEach(function(row, rowIndex) {
      let hasSpace = false;
      row.forEach(function(item) {
        if (!item) {
          hasSpace = true;
        }
      });
      if (!hasSpace) {
        eliminatingRows.push(rowIndex);
      }
    });
    if (gameOver) {
      ee.emit(GS.GAME_OVER);
    }
    console.log('score', score);
  }

  function handleTetrominoDown() {
    tetrominoDroping = true;
  }
}

export default {
  init,
};
<commit_msg>fix(tetris): :bug: fix bug when eliminate multiple rows<commit_after>/**
 * @since 2019-09-22 05:30
 * @author vivaxy
 */
import * as ET from '../enums/event-types.js';
import * as GS from '../enums/game-state.js';

function init(ee) {
  let gameState = GS.NEW_GAME;
  let grid = Array.from({ length: 20 }, function() {
    return Array.from({ length: 10 }, function() {
      return null;
    });
  });
  let score = 0;
  let tetrominoMoving = false;
  let tetrominoDroping = false;
  let eliminatingRows = [];
  let speed = 100;
  let speedIndex = 0;

  ee.on(ET.GAME_STATE_CHANGE, handleGameStateChange);
  ee.on(ET.TICK, handleTick);
  ee.on(ET.TETROMINO_SETTLED, handleTetrominoSettled);
  ee.on(ET.TETROMINO_DOWN, handleTetrominoDown);

  function handleGameStateChange(et, { gameState: _gameState }) {
    gameState = _gameState;
    if (gameState === GS.PLAYING) {
      ee.emit(ET.UPDATE_GRID, { grid });
    }
  }

  function handleTick() {
    if (gameState === GS.PLAYING) {
      if (tetrominoDroping) {
        speedIndex = 0;
        ee.emit(ET.TETROMINO_MOVE);
      } else if (speedIndex > speed) {
        speedIndex = 0;
        if (tetrominoMoving) {
          ee.emit(ET.TETROMINO_MOVE);
        } else if (eliminatingRows.length) {
          let dropRowCount = 0;
          for (let i = grid.length - 1; i >= 0; i--) {
            while (i - dropRowCount === eliminatingRows[eliminatingRows.length - 1]) {
              dropRowCount++;
              eliminatingRows.pop();
            }
            if (i - dropRowCount >= 0) {
              grid[i - dropRowCount].forEach(function(item, colIndex) {
                grid[i][colIndex] = item;
              });
            } else {
              grid[i].forEach(function(_, colIndex) {
                grid[i][colIndex] = null;
              });
            }
          }
          if (eliminatingRows.length !== 0) {
            throw new Error('Unexpect loop result');
          }
        } else {
          tetrominoMoving = true;
          ee.emit(ET.TETROMINO_CREATE);
        }
      } else {
        speedIndex++;
        if (eliminatingRows.length) {
          eliminatingRows.forEach(function(rowIndex) {
            grid[rowIndex].forEach(function(item) {
              if (item._color) {
                item.color = item._color;
                delete item._color;
              } else {
                item._color = item.color;
                item.color = '#fff';
              }
            });
          });
        }
      }
    }
  }

  function handleTetrominoSettled(et, { tetromino, position }) {
    tetrominoMoving = false;
    tetrominoDroping = false;
    score += 1;
    let gameOver = false;
    tetromino.forEach(function(row, rowIndex) {
      row.forEach(function(item) {
        if (item) {
          if (rowIndex + position[1] <= 0) {
            gameOver = true;
          }
        }
      });
    });

    eliminatingRows = [];
    grid.forEach(function(row, rowIndex) {
      let hasSpace = false;
      row.forEach(function(item) {
        if (!item) {
          hasSpace = true;
        }
      });
      if (!hasSpace) {
        eliminatingRows.push(rowIndex);
      }
    });
    if (gameOver) {
      ee.emit(GS.GAME_OVER);
    }
    console.log('score', score);
  }

  function handleTetrominoDown() {
    tetrominoDroping = true;
  }
}

export default {
  init,
};
<|endoftext|>


<commit_before>"use strict";
// :(
require.paths.unshift(__dirname +"/minitest");
require.paths.unshift(__dirname +"/../lib");

var middlewares = require('middlewares');

var JsonMiddleware    = middlewares.json;
var StatusMiddleware  = middlewares.status;
var RuntimeMiddleware = middlewares.runtime;
var OAuth1Middleware  = middlewares.oauth1;

var minitest = require("minitest");
var assert   = require("assert");

minitest.setupListeners();

minitest.context("json middleware", function () {
    this.setup(function () {
        this.middleware = JsonMiddleware;
        this.response = {
            headers: {},
            body: '[{"place":null,"text": "node-spore is awesome"}]'
        };
    });

    this.assertion("parse json if content type is application/json", function (test) {
        var response = this.response;
        response.headers['content-type'] = 'application/json; charset=utf-8';
        this.middleware({}, {}, function(c) {c(response);});
        assert.equal(this.response.body.length, 1);
        assert.equal(this.response.body[0].text, 'node-spore is awesome');
        test.finished();
    });

    this.assertion("do nothing with other content type", function (test) {
        var response = this.response;
        this.middleware({}, {}, function(c) {c(response);});
        assert.equal(this.response.body.length, 48);
        test.finished();
    });
});

minitest.context("status middleware", function () {
    this.setup(function () {
        this.middleware = StatusMiddleware;
        this.response = {
            headers: {},
            body: '[{"place":null,"text": "node-spore is awesome"}]'
        };
    });

    this.assertion("throw exception if status is not in expected_status array", function (test) {
        var that = this;
        this.response.status = 201;
        assert.throws(function () {
            test.finished();
            that.middleware({
                expected_status: [200, 500]
            }, {}, function(c) {c(that.response)});
        }, Error);
    });

    this.assertion("or not", function(test) {
        var that = this;
        this.response.status = 200;
        assert.doesNotThrow(function () {
            test.finished();
            that.middleware({
                expected_status: [200, 500]
            }, {}, function(c) {c(that.response); });
        }, Error);
    })
});

minitest.context("runtime middleware", function () {
    this.assertion("add X-Spore-Runtime", function(test) {
        var response = {
            headers: {},
            body: ''
        };
        RuntimeMiddleware({}, {}, function(c) {c(response) });
        assert.equal(response.headers['X-Spore-Runtime'], 0);
        test.finished();
    })
});

minitest.context("oauth1 middleware", function () {
    this.setup(function() {

    });

    this.assertion("add Authorization header", function(test) {
        var oauth = {
            authHeader: function(url, token, token_secret, method) {
                assert.equal(url, 'https://example.net/plop');
                assert.equal(token, "token");
                assert.equal(token_secret, "secret");
                return 'plop';
            }
        };
        var request = {
            headers: {},
            scheme: 'https',
            host: 'example.net',
            uri: '/plop'
        };
        OAuth1Middleware(oauth, "token", "secret")({authentication: true}, request, function() {});
        assert.equal(request.headers['Authorization'], 'plop');
        test.finished();
    })

    this.assertion("don't add Authorization header", function(test) {
        var oauth = {
        };
        var request = {
            headers: {},
            scheme: 'https',
            host: 'example.net',
            uri: '/plop'
        };
        OAuth1Middleware(oauth, "token", "secret")({authentication: false}, request, function() {});
        assert.equal(request.headers['Authorization'], undefined);
        test.finished();
    })
});
<commit_msg>cleanup tests<commit_after>"use strict";
// :(
require.paths.unshift(__dirname +"/minitest");
require.paths.unshift(__dirname +"/../lib");

var middlewares = require('middlewares');

var JsonMiddleware    = middlewares.json;
var StatusMiddleware  = middlewares.status;
var RuntimeMiddleware = middlewares.runtime;
var OAuth1Middleware  = middlewares.oauth1;

var minitest = require("minitest");
var assert   = require("assert");

minitest.setupListeners();

minitest.context("json middleware", function () {
    this.setup(function () {
        this.middleware = JsonMiddleware;
        this.response = {
            headers: {},
            body: '[{"place":null,"text": "node-spore is awesome"}]'
        };
    });

    this.assertion("parse json if content type is application/json", function (test) {
        var response = this.response;
        response.headers['content-type'] = 'application/json; charset=utf-8';
        this.middleware({}, {}, function(c) {c(response);});
        assert.equal(this.response.body.length, 1);
        assert.equal(this.response.body[0].text, 'node-spore is awesome');
        test.finished();
    });

    this.assertion("do nothing with other content type", function (test) {
        var response = this.response;
        this.middleware({}, {}, function(c) {c(response);});
        assert.equal(this.response.body.length, 48);
        test.finished();
    });
});

minitest.context("status middleware", function () {
    this.setup(function () {
        this.middleware = StatusMiddleware;
        this.response = {
            headers: {},
            body: '[{"place":null,"text": "node-spore is awesome"}]'
        };
    });

    this.assertion("throw exception if status is not in expected_status array", function (test) {
        var that = this;
        this.response.status = 201;
        assert.throws(function () {
            test.finished();
            that.middleware({
                expected_status: [200, 500]
            }, {}, function(c) {c(that.response)});
        }, Error);
    });

    this.assertion("or not", function(test) {
        var that = this;
        this.response.status = 200;
        assert.doesNotThrow(function () {
            test.finished();
            that.middleware({
                expected_status: [200, 500]
            }, {}, function(c) {c(that.response); });
        }, Error);
    })
});

minitest.context("runtime middleware", function () {
    this.assertion("add X-Spore-Runtime", function(test) {
        var response = {
            headers: {},
            body: ''
        };
        RuntimeMiddleware({}, {}, function(c) {c(response) });
        assert.equal(response.headers['X-Spore-Runtime'], 0);
        test.finished();
    })
});

minitest.context("oauth1 middleware", function () {
    this.setup(function() {
        this.request = {
            headers: {},
            scheme: 'https',
            host: 'example.net',
            uri: '/plop'
        };
    });

    this.assertion("add Authorization header", function(test) {
        var oauth = {
            authHeader: function(url, token, token_secret, method) {
                assert.equal(url, 'https://example.net/plop');
                assert.equal(token, "token");
                assert.equal(token_secret, "secret");
                return 'plop';
            }
        };
        OAuth1Middleware(oauth, "token", "secret")({authentication: true}, this.request, function() {});
        assert.equal(this.request.headers['Authorization'], 'plop');
        test.finished();
    })

    this.assertion("don't add Authorization header", function(test) {
        var oauth = {};
        OAuth1Middleware(oauth, "token", "secret")({authentication: false}, this.request, function() {});
        assert.equal(this.request.headers['Authorization'], undefined);
        test.finished();
    })
});
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { isEquivalent, isPartOf } from 'ember-data-factory-guy/utils/helper-functions';

module('isEquivalent | Helper Function');

let tomster = { name: 'Tomster', friends: ['Zoey',    'Yahuda', 'Tom'] };
let zoey    = { name: 'Zoey',    friends: ['Tomster', 'Yahuda', 'Tom'] };
let daniel  = { name: 'Daniel',  friends: ['Zoey',    'Yahuda', 'Tom'] };

test('#isEquivalent with numbers', function(assert) {
  assert.ok(  isEquivalent(1, 1),   'Equivalent numbers should return true'      );

  assert.ok( !isEquivalent(1, 2),   'Non-equivalent numbers should return false' );
  assert.ok( !isEquivalent(1, '1'), 'Non-equivalent values should return false'  );
});

test('#isEquivalent with strings', function(assert) {
  assert.ok(  isEquivalent(tomster.name, 'Tomster'), 'Equivalent strings should return true' );

  assert.ok( !isEquivalent(zoey.name,    'Tomster'), 'Non-equivalent strings should return false' );
});

test('#isEquivalent with booleans', function(assert) {
  assert.ok(  isEquivalent(true, true),   'true === true'  );
  assert.ok(  isEquivalent(false, false), 'false === false');

  assert.ok( !isEquivalent(true, false),  'true !== false' );
  assert.ok( !isEquivalent(true, 1),      'true !== 1'     );
  assert.ok( !isEquivalent(true, 'true'), 'true !== 1'     );
});

test('#isEquivalent with arrays', function(assert) {
  assert.ok(  isEquivalent(tomster.friends, daniel.friends), 'arrays with equivalent contents in the same order return true' );

  assert.ok( !isEquivalent(tomster.friends, zoey.friends),   'arrays with non-equivalent contents return false' );
  assert.ok( !isEquivalent(tomster.friends, ['Zoey', 'Tom', 'Yahuda']), 'arrays with equivalent contents but in a different order return false' );

  assert.ok( isEquivalent([
    1,
    [
      'a',
      [ true ]
    ]
  ],
  [
    1,
    [
      'a',
      [ true ]
    ]
  ]), 'matches equivalence on deeply nested arrays');

  assert.ok( !isEquivalent([
    1,
    [
      'a',
      [ true ]
    ]
  ],
  [
    1,
    [
      'b',
      [ true ]
    ]
  ]), 'filters equivalence on deeply nested arrays');
});

test('#isEquivalent with objects', function(assert) {
  assert.ok(  isEquivalent(tomster, {
    name: 'Tomster',
    friends: ['Zoey', 'Yahuda', 'Tom']
  }), 'returns true if object key-value pairs are equivalent' );

  assert.ok( !isEquivalent(tomster, zoey), 'returns false if object key-value pairs are not equivalent' );

  assert.ok( !isEquivalent(tomster, {
    name: 'Tomster',
    friends: ['Zoey', 'Daniel', 'Tom']
  }), 'returns false if object key-value pairs are not equivalent' );
});

test('#isEquivalent with deeply nested objects', function(assert) {
  // we don't use nestedTomster or nestedZoey in the friends array to avoid
  // infinite recurrsion

  let nestedTomster = {
    name:    tomster.name,
    friends: [ zoey, daniel ]
  };

  let nestedZoey = {
    name:    zoey.name,
    friends: [ tomster, daniel ]
  };

  assert.ok( isEquivalent(nestedTomster, {
    name:    tomster.name,
    friends: [ zoey, daniel ]
  }), 'returns true if object key-value pairs are equivalent' );

  assert.ok( !isEquivalent(nestedZoey, nestedTomster), 'returns false if object key-value pairs are not equivalent' );
});

test('#isPartOf', function(assert) {
  assert.ok( isPartOf(tomster, { name: 'Tomster' } ),
    'returns true if the first object contains all key-value pairs from the second object' );

  assert.ok( isPartOf(tomster, tomster),
    'returns true if the first object is the same as the second object' );

  assert.ok( isPartOf(tomster, {}),
    'returns true if the second object is empty' );

  assert.notOk( isPartOf(tomster, { name: 'Tomster', number: 1 } ),
    'returns false if the first object does not contains key-value pairs from the second object' );
});
<commit_msg>fluff to force rebuild<commit_after>import {module, test} from 'qunit';
import {isEquivalent, isPartOf} from 'ember-data-factory-guy/utils/helper-functions';

module('isEquivalent | Helper Function');

let tomster = { name: 'Tomster', friends: ['Zoey', 'Yahuda', 'Tom'] };
let zoey = { name: 'Zoey', friends: ['Tomster', 'Yahuda', 'Tom'] };
let daniel = { name: 'Daniel', friends: ['Zoey', 'Yahuda', 'Tom'] };

test('#isEquivalent with numbers', function(assert) {
  assert.ok(isEquivalent(1, 1), 'Equivalent numbers should return true');

  assert.ok(!isEquivalent(1, 2), 'Non-equivalent numbers should return false');
  assert.ok(!isEquivalent(1, '1'), 'Non-equivalent values should return false');
});

test('#isEquivalent with strings', function(assert) {
  assert.ok(isEquivalent(tomster.name, 'Tomster'), 'Equivalent strings should return true');

  assert.ok(!isEquivalent(zoey.name, 'Tomster'), 'Non-equivalent strings should return false');
});

test('#isEquivalent with booleans', function(assert) {
  assert.ok(isEquivalent(true, true), 'true === true');
  assert.ok(isEquivalent(false, false), 'false === false');

  assert.ok(!isEquivalent(true, false), 'true !== false');
  assert.ok(!isEquivalent(true, 1), 'true !== 1');
  assert.ok(!isEquivalent(true, 'true'), 'true !== 1');
});

test('#isEquivalent with arrays', function(assert) {
  assert.ok(isEquivalent(tomster.friends, daniel.friends), 'arrays with equivalent contents in the same order return true');

  assert.ok(!isEquivalent(tomster.friends, zoey.friends), 'arrays with non-equivalent contents return false');
  assert.ok(!isEquivalent(tomster.friends, ['Zoey', 'Tom', 'Yahuda']), 'arrays with equivalent contents but in a different order return false');

  assert.ok(isEquivalent([
      1,
      [
        'a',
        [true]
      ]
    ],
    [
      1,
      [
        'a',
        [true]
      ]
    ]), 'matches equivalence on deeply nested arrays');

  assert.ok(!isEquivalent([
      1,
      [
        'a',
        [true]
      ]
    ],
    [
      1,
      [
        'b',
        [true]
      ]
    ]), 'filters equivalence on deeply nested arrays');
});

test('#isEquivalent with objects', function(assert) {
  assert.ok(isEquivalent(tomster, {
    name: 'Tomster',
    friends: ['Zoey', 'Yahuda', 'Tom']
  }), 'returns true if object key-value pairs are equivalent');

  assert.ok(!isEquivalent(tomster, zoey), 'returns false if object key-value pairs are not equivalent');

  assert.ok(!isEquivalent(tomster, {
    name: 'Tomster',
    friends: ['Zoey', 'Daniel', 'Tom']
  }), 'returns false if object key-value pairs are not equivalent');
});

test('#isEquivalent with deeply nested objects', function(assert) {
  // we don't use nestedTomster or nestedZoey in the friends array to avoid
  // infinite recurrsion

  let nestedTomster = {
    name: tomster.name,
    friends: [zoey, daniel]
  };

  let nestedZoey = {
    name: zoey.name,
    friends: [tomster, daniel]
  };

  assert.ok(isEquivalent(nestedTomster, {
    name: tomster.name,
    friends: [zoey, daniel]
  }), 'returns true if object key-value pairs are equivalent');

  assert.ok(!isEquivalent(nestedZoey, nestedTomster), 'returns false if object key-value pairs are not equivalent');
});

test('#isPartOf', function(assert) {
  assert.ok(isPartOf(tomster, { name: 'Tomster' }),
    'returns true if the first object contains all key-value pairs from the second object');

  assert.ok(isPartOf(tomster, tomster),
    'returns true if the first object is the same as the second object');

  assert.ok(isPartOf(tomster, {}),
    'returns true if the second object is empty');

  assert.notOk(isPartOf(tomster, { name: 'Tomster', number: 1 }),
    'returns false if the first object does not contains key-value pairs from the second object');
});
<|endoftext|>