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

import {createFixtureIframe, pollForLayout, poll} from
    '../../testing/iframe';
import {timer} from
    '../../src/timer';

describe('Rendering of one ad', () => {
  let fixture;
  beforeEach(() => {
    return createFixtureIframe('test/fixtures/doubleclick.html', 3000)
      .then(f => {
        fixture = f;
      });
  });

  it('should create an iframe loaded', function() {
    this.timeout(20000);
    let iframe;
    let ampAd;
    const isEdge = navigator.userAgent.match(/Edge/);
    return pollForLayout(fixture.win, 1, 5500).then(() => {
      return poll('frame to be in DOM', () => {
        return fixture.doc.querySelector('iframe');
      });
    }).then(iframeElement => {
      iframe = iframeElement;
      expect(fixture.doc.querySelectorAll('iframe')).to.have.length(1);
      ampAd = iframe.parentElement;
      expect(iframe.src).to.contain('categoryExclusion');
      expect(iframe.src).to.contain('health');
      expect(iframe.src).to.contain('tagForChildDirectedTreatment');
      expect(iframe.src).to.match(/http\:\/\/localhost:9876\/base\/dist\.3p\//);
    }).then(() => {
      return poll('frame to load', () => {
        return iframe.contentWindow && iframe.contentWindow.document &&
            iframe.contentWindow.document.getElementById('c');
      });
    }).then(unusedCanvas => {
      return poll('3p JS to load.', () => iframe.contentWindow.context);
    }).then(context => {
      expect(context.hidden).to.be.false;
      // In some browsers the referrer is empty. But in Chrome it works, so
      // we always check there.
      if (context.referrer !== '' ||
          (navigator.userAgent.match(/Chrome/) && !isEdge)) {
        expect(context.referrer).to.equal('http://localhost:' + location.port +
            '/context.html');
      }
      expect(context.pageViewId).to.be.greaterThan(0);
      expect(context.data.tagForChildDirectedTreatment).to.be.false;
      expect(context.data.categoryExclusion).to.be.equal('health');
      expect(context.data.targeting).to.be.jsonEqual(
          {sport: ['rugby', 'cricket']});
      return poll('main ad JS is injected', () => {
        return iframe.contentWindow.document.querySelector(
            'script[src="https://www.googletagservices.com/tag/js/gpt.js"]');
      });
    }).then(() => {
      return poll('render-start message received', () => {
        return fixture.messages.filter(message => {
          return message.type == 'render-start';
        }).length;
      });
    }).then(() => {
      expect(iframe.style.visibility).to.equal('');
      const win = iframe.contentWindow;
      return poll('GPT loaded', () => {
        return win.googletag && win.googletag.pubads && win.googletag.pubads();
      });
    }).then(pubads => {
      const canvas = iframe.contentWindow.document.querySelector('#c');
      expect(pubads.get('page_url')).to.equal(
          'http://localhost:9876/doubleclick.html');
      const slot = canvas.slot;
      expect(slot).to.not.be.null;
      expect(slot.getCategoryExclusions()).to.jsonEqual(['health']);
      expect(slot.getTargeting('sport')).to.jsonEqual(['rugby', 'cricket']);
      return poll(
          'ad iframe to be initialized. Means that an actual ad was loaded.',
          () => {
            return canvas.querySelector(
                '[id="google_ads_iframe_/4119129/mobile_ad_banner_0"]');
          }, null, 5000);
    }).then(() => {
      expect(iframe.contentWindow.context.hidden).to.be.false;
      return new Promise(resolve => {
        iframe.contentWindow.addEventListener('amp:visibilitychange', resolve);
        fixture.win.AMP.viewer.visibilityState_ = 'hidden';
        fixture.win.AMP.viewer.onVisibilityChange_();
      });
    }).then(() => {
      expect(iframe.getAttribute('width')).to.equal('320');
      expect(iframe.getAttribute('height')).to.equal('50');
      if (isEdge) { // TODO(cramforce): Get this to pass in Edge
        return;
      }
      return poll('Creative id transmitted. Ad fully rendered.', () => {
        return ampAd.getAttribute('creative-id');
      }, null, 15000);
    }).then(creativeId => {
      if (isEdge) { // TODO(cramforce): Get this to pass in Edge
        return;
      }
      expect(creativeId).to.match(/^dfp-/);
    });
  });
});
<commit_msg>Remove extra import<commit_after>/**
 * Copyright 2015 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {createFixtureIframe, pollForLayout, poll} from
    '../../testing/iframe';

describe('Rendering of one ad', () => {
  let fixture;
  beforeEach(() => {
    return createFixtureIframe('test/fixtures/doubleclick.html', 3000)
      .then(f => {
        fixture = f;
      });
  });

  it('should create an iframe loaded', function() {
    this.timeout(20000);
    let iframe;
    let ampAd;
    const isEdge = navigator.userAgent.match(/Edge/);
    return pollForLayout(fixture.win, 1, 5500).then(() => {
      return poll('frame to be in DOM', () => {
        return fixture.doc.querySelector('iframe');
      });
    }).then(iframeElement => {
      iframe = iframeElement;
      expect(fixture.doc.querySelectorAll('iframe')).to.have.length(1);
      ampAd = iframe.parentElement;
      expect(iframe.src).to.contain('categoryExclusion');
      expect(iframe.src).to.contain('health');
      expect(iframe.src).to.contain('tagForChildDirectedTreatment');
      expect(iframe.src).to.match(/http\:\/\/localhost:9876\/base\/dist\.3p\//);
    }).then(() => {
      return poll('frame to load', () => {
        return iframe.contentWindow && iframe.contentWindow.document &&
            iframe.contentWindow.document.getElementById('c');
      });
    }).then(unusedCanvas => {
      return poll('3p JS to load.', () => iframe.contentWindow.context);
    }).then(context => {
      expect(context.hidden).to.be.false;
      // In some browsers the referrer is empty. But in Chrome it works, so
      // we always check there.
      if (context.referrer !== '' ||
          (navigator.userAgent.match(/Chrome/) && !isEdge)) {
        expect(context.referrer).to.equal('http://localhost:' + location.port +
            '/context.html');
      }
      expect(context.pageViewId).to.be.greaterThan(0);
      expect(context.data.tagForChildDirectedTreatment).to.be.false;
      expect(context.data.categoryExclusion).to.be.equal('health');
      expect(context.data.targeting).to.be.jsonEqual(
          {sport: ['rugby', 'cricket']});
      return poll('main ad JS is injected', () => {
        return iframe.contentWindow.document.querySelector(
            'script[src="https://www.googletagservices.com/tag/js/gpt.js"]');
      });
    }).then(() => {
      return poll('render-start message received', () => {
        return fixture.messages.filter(message => {
          return message.type == 'render-start';
        }).length;
      });
    }).then(() => {
      expect(iframe.style.visibility).to.equal('');
      const win = iframe.contentWindow;
      return poll('GPT loaded', () => {
        return win.googletag && win.googletag.pubads && win.googletag.pubads();
      });
    }).then(pubads => {
      const canvas = iframe.contentWindow.document.querySelector('#c');
      expect(pubads.get('page_url')).to.equal(
          'http://localhost:9876/doubleclick.html');
      const slot = canvas.slot;
      expect(slot).to.not.be.null;
      expect(slot.getCategoryExclusions()).to.jsonEqual(['health']);
      expect(slot.getTargeting('sport')).to.jsonEqual(['rugby', 'cricket']);
      return poll(
          'ad iframe to be initialized. Means that an actual ad was loaded.',
          () => {
            return canvas.querySelector(
                '[id="google_ads_iframe_/4119129/mobile_ad_banner_0"]');
          }, null, 5000);
    }).then(() => {
      expect(iframe.contentWindow.context.hidden).to.be.false;
      return new Promise(resolve => {
        iframe.contentWindow.addEventListener('amp:visibilitychange', resolve);
        fixture.win.AMP.viewer.visibilityState_ = 'hidden';
        fixture.win.AMP.viewer.onVisibilityChange_();
      });
    }).then(() => {
      expect(iframe.getAttribute('width')).to.equal('320');
      expect(iframe.getAttribute('height')).to.equal('50');
      if (isEdge) { // TODO(cramforce): Get this to pass in Edge
        return;
      }
      return poll('Creative id transmitted. Ad fully rendered.', () => {
        return ampAd.getAttribute('creative-id');
      }, null, 15000);
    }).then(creativeId => {
      if (isEdge) { // TODO(cramforce): Get this to pass in Edge
        return;
      }
      expect(creativeId).to.match(/^dfp-/);
    });
  });
});
<|endoftext|>


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

define(function(require) {
  var TemplateHTML = require('hbs!./range-slider/html');

  var sliderId = 0;
  _initialSetup();

  return {
    'insert': _insert,
    'html': _html
  }

  /*
    Insert a range slider
    @param {Object} opts Options for the slider
      opts.label Label for the input
      opts.name Name of the input, it will be used for the wizard_field value
        and the ID of the input
      opts.min Start value of the slider
      opts.max End value of the slider
      opts.step Step value of the slider
      opts.initial Initialize the slider with this value
      opts.enabled false to disable the inputs (true by default)
    @param {Object} context div to insert the range slider
    @returns {String} HTML row
   */
  function _insert(opts, context) {
    context.html(_html(opts));
  }

  function _html(opts) {
    opts['sliderId'] = sliderId;

    opts['ticks'] = [];
    if (opts.tick_size !== undefined){
      var tick_val = opts.tick_size * Math.ceil(opts.min / opts.tick_size);
      while (tick_val <= opts.max){
        opts['ticks'].push(tick_val);
        tick_val += opts.tick_size;
      }
    }

    sliderId += 1;
    return TemplateHTML(opts);
  }

  function _initialSetup() {
    $(document).off("input", "input.uinput-slider-val");
    $(document).on("input", "input.uinput-slider-val", function(){
      $("input[type=range]", $(this).closest('.uinput-slider-container')).val( this.value );
    });

    $(document).off("input", "input.uinput-slider");
    $(document).on("input", "input.uinput-slider", function(){
      $("input[type=number]", $(this).closest('.uinput-slider-container')).val( this.value );
    });
  }
});
<commit_msg>Max input slider (#197)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  var TemplateHTML = require('hbs!./range-slider/html');

  var sliderId = 0;
  _initialSetup();

  return {
    'insert': _insert,
    'html': _html
  }

  /*
    Insert a range slider
    @param {Object} opts Options for the slider
      opts.label Label for the input
      opts.name Name of the input, it will be used for the wizard_field value
        and the ID of the input
      opts.min Start value of the slider
      opts.max End value of the slider
      opts.step Step value of the slider
      opts.initial Initialize the slider with this value
      opts.enabled false to disable the inputs (true by default)
    @param {Object} context div to insert the range slider
    @returns {String} HTML row
   */
  function _insert(opts, context) {
    context.html(_html(opts));
  }

  function _html(opts) {
    opts['sliderId'] = sliderId;

    opts['ticks'] = [];
    if (opts.tick_size !== undefined){
      var tick_val = opts.tick_size * Math.ceil(opts.min / opts.tick_size);
      while (tick_val <= opts.max){
        opts['ticks'].push(tick_val);
        tick_val += opts.tick_size;
      }
    }

    sliderId += 1;
    return TemplateHTML(opts);
  }

  function _initialSetup() {
    $(document).off("input", "input.uinput-slider-val");
    $(document).on("input", "input.uinput-slider-val", function(){
      var max = $("input[type=number]", $(this).closest('.uinput-slider-container')).attr('max');
      $("input[type=range]", $(this).closest('.uinput-slider-container')).val( this.value );
      if(this.value > max)
        $("input[type=number]", $(this).closest('.uinput-slider-container')).val(max);
    });

    $(document).off("input", "input.uinput-slider");
    $(document).on("input", "input.uinput-slider", function(){
      $("input[type=number]", $(this).closest('.uinput-slider-container')).val( this.value );
    });
  }
});
<|endoftext|>


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

var support_tab = {
    title: '
 '+tr("Support"),
    no_content: true
}

var doc_tab = {
    title: tr("Documentation"),
    tabClass: 'subTab',
    parentTab: 'support-tab',
    no_content: true
}

var community_tab = {
    title: tr("Community"),
    tabClass: 'subTab',
    parentTab: 'support-tab',
    no_content: true
}

var enterprise_tab = {
    title: tr("Enterprise"),
    tabClass: 'subTab',
    parentTab: 'support-tab',
    no_content: true
}

Sunstone.addMainTab('support-tab',support_tab);
Sunstone.addMainTab('doc-tab',doc_tab);
Sunstone.addMainTab('community-tab',community_tab);
Sunstone.addMainTab('enterprise-tab',enterprise_tab);

$(document).on("click", "#li_doc-tab a", function(){
    window.open("http://docs.opennebula.org/4.6/");
    return false;
})

$(document).on("click", "#li_community-tab a", function(){
    window.open("http://opennebula.org/support/community/");
    return false;
})

$(document).on("click", "#li_enterprise-tab a", function(){
    window.open("http://c12g.com/support/");
    return false;
})
<commit_msg>Update documentation link<commit_after>// ------------------------------------------------------------------------ //
// Copyright 2010-2014, C12G Labs S.L.                                      //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License"); you may  //
// not use this file except in compliance with the License. You may obtain  //
// a copy of the License at                                                 //
//                                                                          //
// http://www.apache.org/licenses/LICENSE-2.0                               //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
//------------------------------------------------------------------------- //

var support_tab = {
    title: '
 '+tr("Support"),
    no_content: true
}

var doc_tab = {
    title: tr("Documentation"),
    tabClass: 'subTab',
    parentTab: 'support-tab',
    no_content: true
}

var community_tab = {
    title: tr("Community"),
    tabClass: 'subTab',
    parentTab: 'support-tab',
    no_content: true
}

var enterprise_tab = {
    title: tr("Enterprise"),
    tabClass: 'subTab',
    parentTab: 'support-tab',
    no_content: true
}

Sunstone.addMainTab('support-tab',support_tab);
Sunstone.addMainTab('doc-tab',doc_tab);
Sunstone.addMainTab('community-tab',community_tab);
Sunstone.addMainTab('enterprise-tab',enterprise_tab);

$(document).on("click", "#li_doc-tab a", function(){
    window.open("http://docs.opennebula.org/4.8/");
    return false;
})

$(document).on("click", "#li_community-tab a", function(){
    window.open("http://opennebula.org/support/community/");
    return false;
})

$(document).on("click", "#li_enterprise-tab a", function(){
    window.open("http://c12g.com/support/");
    return false;
})
<|endoftext|>


<commit_before>describe('Example suite', function() {

    var callbackFunc = function (req, responseText) {
	return '[' + responseText + ']';
    }
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

    beforeEach(function(done) {
        // Load app inside iframe
        openApp('http://localhost:8001/msl-sample-app/index.html');

        setTimeout(function() {
            done();
        }, 1000);
    });

    afterEach(function() {
        unRegisterMock('localhost', 8001, "");
    });

    it('Test for register and get mock response', function(done) {
        // Use msl-client to set mock response
        var mockResponse = {};
        mockResponse.requestPath = '/services/getlanguages';
        mockResponse.responseText = '[{"label":"apache"},{"label":"apple"}]';
        mockResponse.statusCode = 200;
        mockResponse.delayTime = 0;
        setMockRespond('localhost', 8001, mockResponse);

        // Type into first input field which triggers a REST call to return a JSON response
        getElement('#autocomplete').val('a');
        getElement('#autocomplete').keydown();

        setTimeout(function() {
            // Validate the drop down is display correctly with mock response
            expect(getElement('ul li:nth-of-type(1)').text()).toBe('apache');
            expect(getElement('ul li:nth-of-type(2)').text()).toBe('apple');

            // Click on the Second item from the drop down
            getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').click();

            // Validate that correct item was selected
            expect(getElement('#autocomplete').val()).toBe('apple');

            done();
        }, 1000);
    });

    it('Test for register and get mock response using function', function(done) {
        // Use msl-client to set mock response
        var mockResponse = {};
        mockResponse.requestPath = '/services/getlanguages';
        mockResponse.responseText = '{"label":"apache"},{"label":"apple"}';
	mockResponse.eval = callbackFunc;
        mockResponse.statusCode = 200;
        mockResponse.delayTime = 0;
        setMockRespond('localhost', 8001, mockResponse);

        // Type into first input field which triggers a REST call to return a JSON response
        getElement('#autocomplete').val('a');
        getElement('#autocomplete').keydown();

        setTimeout(function() {
            // Validate the drop down is display correctly with mock response
            expect(getElement('ul li:nth-of-type(1)').text()).toBe('apache');
            expect(getElement('ul li:nth-of-type(2)').text()).toBe('apple');

            // Click on the Second item from the drop down
            getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').click();

            // Validate that correct item was selected
            expect(getElement('#autocomplete').val()).toBe('apple');

            done();
        }, 1000);
    });

    it('Test setup mock response with template', function(done) {

        // Registering the template that will be used for the response
        registerTemplate('localhost', 8001,
            '[{"label":"{{param1}}"},{"label":"{{param2}}"}]', 'example');
        // Set up the object that contains our response configuration
        var configurations = {};
        configurations.requestPath = '/services/getlanguages';
        configurations.contentType = 'application/json';
        configurations.id = 'example';
        configurations.keyValues = {
            'param1': 'Boat',
            'param2': 'Cat'
        };
        configurations.statusCode = 200;
        configurations.delayTime = 0;
        // Use msl-client to set mock response
        setMockRespond('localhost', 8001, configurations);

        // Type into first input field which triggers a REST call to return a JSON response
        getElement('#autocomplete').val('b');
        getElement('#autocomplete').keydown();

        setTimeout(function() {
            // Validate the drop down is display correctly with mock response using template
            expect(getElement('ul li:nth-of-type(1)').text()).toBe('Boat');
            expect(getElement('ul li:nth-of-type(2)').text()).toBe('Cat');

            // Click on the first item from the drop down
            getElement('.ui-autocomplete .ui-menu-item:nth-of-type(1)').click();

            // Validate that correct item was selected
            expect(getElement('#autocomplete').val()).toBe('Boat');

            done();
        }, 1000);
    });

    it('Test XHR intercept, Get method', function(done) {
        // Use msl-client to register intercept
        setInterceptXHR('localhost', 8001, '/services/getservice');

        // Type into second input field and click GET button which triggers a GET request
        getElement('#getInput').val('testGet');
        getElement('#getRequest').click();

        // Retrieve intercepted XHR and validate correct GET request was made by the app
        getInterceptedXHR('localhost', 8001, '/services/getservice', function(resp) {
            var intrReq = JSON.parse(resp).xhr_1;
            expect(intrReq.xhr.url).toBe('/services/getservice?term=testGet');
            expect(intrReq.xhr.method).toBe('GET');
        });
        done();
    });

    it('Test XHR intercept, Post method', function(done) {
		// Use msl-client to register intercept
		setInterceptXHR('localhost', 8001, '/services/postservice');

		// Type into second input field and click GET button which triggers a GET request
		getElement('#output-box').val('testPost');
		getElement('#postRequest').click();

		setTimeout(function () {
			// Retrieve intercepted XHR and validate correct POST request was made by the app
			getInterceptedXHR('localhost', 8001, '/services/postservice', function (resp) {
				var intrReq = JSON.parse(resp).xhr_1;
				var regex = new RegExp('\\d*');
				expect(intrReq.xhr.url).toBe('/services/postservice');

				expect(regex.test(intrReq.post['timestamp'])).toBe(true);
				expect(intrReq.post['text']).toBe('testPost');
				expect(intrReq.xhr.method).toBe('POST');

			});

			done();
		}, 1000);
    });

    it('Test for setting the delay time of returning a mock response', function(done) {
		// Use msl-client to set mock response
		var mockResponse = {};
		mockResponse.requestPath = '/services/getlanguages?term=abc';
		mockResponse.responseText = '[{"label":"apache"},{"label":"apple"}]';
		mockResponse.statusCode = 200;
		mockResponse.delayTime = 3000;
		setMockRespond('localhost', 8001, mockResponse);

		// Type into first input field which triggers a REST call to return a JSON response
		getElement('#autocomplete').val('abc');
		getElement('#autocomplete').keydown();

		// Validate that the response is delayed
		expect(getElement('.ui-autocomplete .ui-menu-item:nth-of-type(1)').size()).toBe(0);
		expect(getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').size()).toBe(0);

		setTimeout(function () {
			// Validate the drop down is display correctly with mock response
			expect(getElement('ul li:nth-of-type(1)').text()).toBe('apache');
			expect(getElement('ul li:nth-of-type(2)').text()).toBe('apple');

			// Click on the Second item from the drop down
			getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').click();
			setTimeout(function () {
				// Validate that correct item was selected
				expect(getElement('#autocomplete').val()).toBe('apple');
				done();
			}, 500);

		}, 3500);
    });

    it('Test unRegisterMock function', function(done) {
        // Use msl-client to set mock response
        var mockResponse = {};
        mockResponse.requestPath = '/services/getlanguages';
        mockResponse.responseText = '[{"label":"Ice Cream"},{"label":"Candy"}]';
        mockResponse.statusCode = 200;
        mockResponse.delayTime = 0;
        setMockRespond('localhost', 8001, mockResponse);

        // Type into first input field which triggers a REST call to return a JSON response
        getElement('#autocomplete').val('I');
        getElement('#autocomplete').keydown();

        setTimeout(function() {
            // Click on the first item from the drop down
            expect(getElement('ul li:nth-of-type(1)').text()).toBe('Ice Cream');
            expect(getElement('ul li:nth-of-type(2)').text()).toBe('Candy');

            getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').click();

	    setTimeout(function() {
              // Validate that correct item was selected
              expect(getElement('#autocomplete').val()).toBe('Candy');
	      // Reload Page
              openApp('http://localhost:8001/msl-sample-app/index.html');
	      setTimeout(function() {
                unRegisterMock('localhost', 8001, '/services/getlanguages');
              	getElement('#autocomplete').val('I');
                expect(getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').size()).toBe(0);
		done();
	      }, 1000);
	    }, 1000);
	}, 1000);
    });

    it('Test mocking POST ajax success', function(done) {
      // Use msl-client to set mock response
      setMockRespond('localhost', 8001, {"requestPath":"/services/postservice", "responseText":'{"outputBoxValue":"hello"}'});

      // Type hellomsl on text area and click POST button
      getElement('#output-box').val('hellomsl');
      getElement('#postRequest').click();

      setTimeout(function() {
        // Validate that postResult span is populated with the text 'hello' which was the success call from the ajax call
        expect(getElement('#postResult').text()).toBe('hello');
        done();
      }, 1000);
    });
});
<commit_msg>Update MSLTestSpec.js<commit_after>describe('Example suite', function() {

    var callbackFunc = function (req, responseText) {
	return '[' + responseText + ']';
    }
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

    beforeEach(function(done) {
        // Load app inside iframe
        openApp('http://localhost:8001/msl-sample-app/index.html');

        setTimeout(function() {
            done();
        }, 200);
    });

    afterEach(function() {
        unRegisterMock('localhost', 8001, "");
    });

    it('Test for register and get mock response', function(done) {
        // Use msl-client to set mock response
        var mockResponse = {};
        mockResponse.requestPath = '/services/getlanguages';
        mockResponse.responseText = '[{"label":"apache"},{"label":"apple"}]';
        mockResponse.statusCode = 200;
        mockResponse.delayTime = 0;
        setMockRespond('localhost', 8001, mockResponse);

        // Type into first input field which triggers a REST call to return a JSON response
        getElement('#autocomplete').val('a');
        getElement('#autocomplete').keydown();

        setTimeout(function() {
            // Validate the drop down is display correctly with mock response
            expect(getElement('ul li:nth-of-type(1)').text()).toBe('apache');
            expect(getElement('ul li:nth-of-type(2)').text()).toBe('apple');

            // Click on the Second item from the drop down
            getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').click();

            // Validate that correct item was selected
            expect(getElement('#autocomplete').val()).toBe('apple');

            done();
        }, 500);
    });

    it('Test for register and get mock response using function', function(done) {
        // Use msl-client to set mock response
        var mockResponse = {};
        mockResponse.requestPath = '/services/getlanguages';
        mockResponse.responseText = '{"label":"apache"},{"label":"apple"}';
	mockResponse.eval = callbackFunc;
        mockResponse.statusCode = 200;
        mockResponse.delayTime = 0;
        setMockRespond('localhost', 8001, mockResponse);

        // Type into first input field which triggers a REST call to return a JSON response
        getElement('#autocomplete').val('a');
        getElement('#autocomplete').keydown();

        setTimeout(function() {
            // Validate the drop down is display correctly with mock response
            expect(getElement('ul li:nth-of-type(1)').text()).toBe('apache');
            expect(getElement('ul li:nth-of-type(2)').text()).toBe('apple');

            // Click on the Second item from the drop down
            getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').click();

            // Validate that correct item was selected
            expect(getElement('#autocomplete').val()).toBe('apple');

            done();
        }, 500);
    });

    it('Test setup mock response with template', function(done) {

        // Registering the template that will be used for the response
        registerTemplate('localhost', 8001,
            '[{"label":"{{param1}}"},{"label":"{{param2}}"}]', 'example');
        // Set up the object that contains our response configuration
        var configurations = {};
        configurations.requestPath = '/services/getlanguages';
        configurations.contentType = 'application/json';
        configurations.id = 'example';
        configurations.keyValues = {
            'param1': 'Boat',
            'param2': 'Cat'
        };
        configurations.statusCode = 200;
        configurations.delayTime = 0;
        // Use msl-client to set mock response
        setMockRespond('localhost', 8001, configurations);

        // Type into first input field which triggers a REST call to return a JSON response
        getElement('#autocomplete').val('b');
        getElement('#autocomplete').keydown();

        setTimeout(function() {
            // Validate the drop down is display correctly with mock response using template
            expect(getElement('ul li:nth-of-type(1)').text()).toBe('Boat');
            expect(getElement('ul li:nth-of-type(2)').text()).toBe('Cat');

            // Click on the first item from the drop down
            getElement('.ui-autocomplete .ui-menu-item:nth-of-type(1)').click();

            // Validate that correct item was selected
            expect(getElement('#autocomplete').val()).toBe('Boat');

            done();
        }, 500);
    });

    it('Test XHR intercept, Get method', function(done) {
        // Use msl-client to register intercept
        setInterceptXHR('localhost', 8001, '/services/getservice');

        // Type into second input field and click GET button which triggers a GET request
        getElement('#getInput').val('testGet');
        getElement('#getRequest').click();

        // Retrieve intercepted XHR and validate correct GET request was made by the app
        getInterceptedXHR('localhost', 8001, '/services/getservice', function(resp) {
            var intrReq = JSON.parse(resp).xhr_1;
            expect(intrReq.xhr.url).toBe('/services/getservice?term=testGet');
            expect(intrReq.xhr.method).toBe('GET');
        });
        done();
    });

    it('Test XHR intercept, Post method', function(done) {
		// Use msl-client to register intercept
		setInterceptXHR('localhost', 8001, '/services/postservice');

		// Type into second input field and click GET button which triggers a GET request
		getElement('#output-box').val('testPost');
		getElement('#postRequest').click();

		setTimeout(function () {
			// Retrieve intercepted XHR and validate correct POST request was made by the app
			getInterceptedXHR('localhost', 8001, '/services/postservice', function (resp) {
				var intrReq = JSON.parse(resp).xhr_1;
				var regex = new RegExp('\\d*');
				expect(intrReq.xhr.url).toBe('/services/postservice');

				expect(regex.test(intrReq.post['timestamp'])).toBe(true);
				expect(intrReq.post['text']).toBe('testPost');
				expect(intrReq.xhr.method).toBe('POST');

			});

			done();
		}, 500);
    });

    it('Test for setting the delay time of returning a mock response', function(done) {
		// Use msl-client to set mock response
		var mockResponse = {};
		mockResponse.requestPath = '/services/getlanguages?term=abc';
		mockResponse.responseText = '[{"label":"apache"},{"label":"apple"}]';
		mockResponse.statusCode = 200;
		mockResponse.delayTime = 3000;
		setMockRespond('localhost', 8001, mockResponse);

		// Type into first input field which triggers a REST call to return a JSON response
		getElement('#autocomplete').val('abc');
		getElement('#autocomplete').keydown();

		// Validate that the response is delayed
		expect(getElement('.ui-autocomplete .ui-menu-item:nth-of-type(1)').size()).toBe(0);
		expect(getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').size()).toBe(0);

		setTimeout(function () {
			// Validate the drop down is display correctly with mock response
			expect(getElement('ul li:nth-of-type(1)').text()).toBe('apache');
			expect(getElement('ul li:nth-of-type(2)').text()).toBe('apple');

			// Click on the Second item from the drop down
			getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').click();
			setTimeout(function () {
				// Validate that correct item was selected
				expect(getElement('#autocomplete').val()).toBe('apple');
				done();
			}, 500);

		}, 3500);
    });

    it('Test unRegisterMock function', function(done) {
        // Use msl-client to set mock response
        var mockResponse = {};
        mockResponse.requestPath = '/services/getlanguages';
        mockResponse.responseText = '[{"label":"Ice Cream"},{"label":"Candy"}]';
        mockResponse.statusCode = 200;
        mockResponse.delayTime = 0;
        setMockRespond('localhost', 8001, mockResponse);

        // Type into first input field which triggers a REST call to return a JSON response
        getElement('#autocomplete').val('I');
        getElement('#autocomplete').keydown();

        setTimeout(function() {
            // Click on the first item from the drop down
            expect(getElement('ul li:nth-of-type(1)').text()).toBe('Ice Cream');
            expect(getElement('ul li:nth-of-type(2)').text()).toBe('Candy');

            getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').click();

	    setTimeout(function() {
              // Validate that correct item was selected
              expect(getElement('#autocomplete').val()).toBe('Candy');
	      // Reload Page
              openApp('http://localhost:8001/msl-sample-app/index.html');
	      setTimeout(function() {
                unRegisterMock('localhost', 8001, '/services/getlanguages');
              	getElement('#autocomplete').val('I');
                expect(getElement('.ui-autocomplete .ui-menu-item:nth-of-type(2)').size()).toBe(0);
		done();
	      }, 200);
	    }, 500);
	}, 500);
    });

    it('Test mocking POST ajax success', function(done) {
      // Use msl-client to set mock response
      setMockRespond('localhost', 8001, {"requestPath":"/services/postservice", "responseText":'{"outputBoxValue":"hello"}'});

      // Type hellomsl on text area and click POST button
      getElement('#output-box').val('hellomsl');
      getElement('#postRequest').click();

      setTimeout(function() {
        // Validate that postResult span is populated with the text 'hello' which was the success call from the ajax call
        expect(getElement('#postResult').text()).toBe('hello');
        done();
      }, 500);
    });
});
<|endoftext|>


<commit_before>//
//  replication test : basic repl
//
//  Save an object in master
//  Wait for repl to slave
//  Save another object in master
//  Wait for repl to slave
//  check

__path__._repl(
    function( dbm , dbs, info){

    dbm.test.save({n:1});

    assert( dbm.test.findOne() );
    assert( dbm.test.findOne().n == 1 );
    assert.eq( dbm.test.count() , 1 );

    print( " **** " + info.replTimeMS + "ms wait for replication***" );

    sleep(info.replTimeMS);

    assert( dbs.test.findOne() , "nothing in slave table" );
    assert( dbs.test.findOne().n == 1 , "what's in slave table is wrong" );

    var cnt = dbs.test.count();
    assert( cnt == 1 , "object count in slave != 1  found :  " + cnt);

    print( " **** adding second object to master ***" );

    dbm.test.save({n:2});
    assert.eq(dbm.test.count() , 2);

    print( " **** " + info.replTimeMS + "ms wait for replication***" );

    sleep(info.replTimeMS);

    assert( dbs.test.findOne() , "error : slave table empty" );

    // check to see that we have only 2 objects, and they are the right objects

    var n = dbs.test.count();
    assert( n == 2, "error count != 2 : " + n);

    n = dbs.test.find({n:1}).length();
    assert(n == 1, "incorrect count for {n:1} objects in slave table : " + n);

    n = dbs.test.find({n:2}).length();
    assert(n == 1, "incorrect count for {n:2} objects in slave table : " + n);

    assert(dbm.test.validate().valid, "master table test failed validation");
    assert(dbs.test.validate().valid, "slave table test failed validation");
});
<commit_msg>using the checksum<commit_after>//
//  replication test : basic repl
//
//  Save an object in master
//  Wait for repl to slave
//  Save another object in master
//  Wait for repl to slave
//  check

__path__._repl(
    function( dbm , dbs, info){

    dbm.test.save({n:1});

    assert( dbm.test.findOne() );
    assert( dbm.test.findOne().n == 1 );
    assert.eq( dbm.test.count() , 1 );

    print( " **** " + info.replTimeMS + "ms wait for replication***" );

    sleep(info.replTimeMS);

    assert( dbs.test.findOne() , "nothing in slave table" );
    assert( dbs.test.findOne().n == 1 , "what's in slave table is wrong" );

    var cnt = dbs.test.count();
    assert( cnt == 1 , "object count in slave != 1  found :  " + cnt);

    assert(dbm.test.checksum() == dbs.test.checksum());

    print( " **** adding second object to master ***" );

    dbm.test.save({n:2});
    assert.eq(dbm.test.count() , 2);

    print( " **** " + info.replTimeMS + "ms wait for replication***" );

    sleep(info.replTimeMS);

    assert( dbs.test.findOne() , "error : slave table empty" );

    // check to see that we have only 2 objects, and they are the right objects

    var n = dbs.test.count();
    assert( n == 2, "error count != 2 : " + n);

    n = dbs.test.find({n:1}).length();
    assert(n == 1, "incorrect count for {n:1} objects in slave table : " + n);

    n = dbs.test.find({n:2}).length();
    assert(n == 1, "incorrect count for {n:2} objects in slave table : " + n);

    assert(dbm.test.validate().valid, "master table test failed validation");
    assert(dbs.test.validate().valid, "slave table test failed validation");
});
<|endoftext|>


<commit_before>const _ = require('lodash');
const should = require('should');
const supertest = require('supertest');
const Promise = require('bluebird');
const sinon = require('sinon');
const moment = require('moment-timezone');
const SchedulingDefault = require('../../../../core/server/adapters/scheduling/SchedulingDefault');
const models = require('../../../../core/server/models');
const config = require('../../../../core/shared/config');
const testUtils = require('../../../utils');
const localUtils = require('./utils');

describe('Canary Schedules API', function () {
    const resources = [];
    let request;

    before(function () {
        models.init();

        // @NOTE: mock the post scheduler, otherwise it will auto publish the post
        sinon.stub(SchedulingDefault.prototype, '_pingUrl').resolves();
    });

    after(function () {
        sinon.restore();
    });

    before(async function () {
        await localUtils.startGhost();

        request = supertest.agent(config.get('url'));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            author_id: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().add(30, 'seconds').toDate(),
            status: 'scheduled',
            slug: 'first'
        }));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            author_id: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().subtract(30, 'seconds').toDate(),
            status: 'scheduled',
            slug: 'second'
        }));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            author_id: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().add(10, 'minute').toDate(),
            status: 'scheduled',
            slug: 'third'
        }));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            author_id: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().subtract(10, 'minute').toDate(),
            status: 'scheduled',
            slug: 'fourth'
        }));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            author_id: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().add(30, 'seconds').toDate(),
            status: 'scheduled',
            slug: 'fifth',
            type: 'page'
        }));

        const result = await Promise.mapSeries(resources, function (post) {
            return models.Post.add(post, {context: {internal: true}});
        });

        result.length.should.eql(5);
    });

    describe('publish', function () {
        let token;

        before(function () {
            const schedulerKey = _.find(testUtils.getExistingData().apiKeys, {integration: {slug: 'ghost-scheduler'}});

            token = localUtils.getValidAdminToken('/admin/', schedulerKey);
        });

        it('publishes posts', async function () {
            const res = await request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[0].id}/?token=${token}`))
                .set('Origin', config.get('url'))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            jsonResponse.posts[0].id.should.eql(resources[0].id);
            jsonResponse.posts[0].status.should.eql('published');
        });

        it('publishes page', async function () {
            const res = await request
                .put(localUtils.API.getApiQuery(`schedules/pages/${resources[4].id}/?token=${token}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            jsonResponse.pages[0].id.should.eql(resources[4].id);
            jsonResponse.pages[0].status.should.eql('published');
        });

        it('no access', function () {
            const zapierKey = _.find(testUtils.getExistingData().apiKeys, {integration: {slug: 'ghost-backup'}});
            const zapierToken = localUtils.getValidAdminToken('/admin/', zapierKey);

            return request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[0].id}/?token=${zapierToken}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(403);
        });

        it('should fail with invalid resource type', function () {
            return request
                .put(localUtils.API.getApiQuery(`schedules/this_is_invalid/${resources[0].id}/?token=${token}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(422);
        });

        it('published_at is x seconds in past, but still in tolerance', function () {
            return request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[1].id}/?token=${token}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);
        });

        it('not found', function () {
            return request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[2].id}/?token=${token}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(404);
        });

        it('force publish', function () {
            return request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[3].id}/?token=${token}`))
                .send({
                    force: true
                })
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);
        });
    });
});
<commit_msg>Cleaned up schedules test suite from author_id field<commit_after>const _ = require('lodash');
const should = require('should');
const supertest = require('supertest');
const Promise = require('bluebird');
const sinon = require('sinon');
const moment = require('moment-timezone');
const SchedulingDefault = require('../../../../core/server/adapters/scheduling/SchedulingDefault');
const models = require('../../../../core/server/models');
const config = require('../../../../core/shared/config');
const testUtils = require('../../../utils');
const localUtils = require('./utils');

describe('Canary Schedules API', function () {
    const resources = [];
    let request;

    before(function () {
        models.init();

        // @NOTE: mock the post scheduler, otherwise it will auto publish the post
        sinon.stub(SchedulingDefault.prototype, '_pingUrl').resolves();
    });

    after(function () {
        sinon.restore();
    });

    before(async function () {
        await localUtils.startGhost();

        request = supertest.agent(config.get('url'));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().add(30, 'seconds').toDate(),
            status: 'scheduled',
            slug: 'first',
            authors: [{
                id: testUtils.getExistingData().users[0].id
            }]
        }));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().subtract(30, 'seconds').toDate(),
            status: 'scheduled',
            slug: 'second',
            authors: [{
                id: testUtils.getExistingData().users[0].id
            }]
        }));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().add(10, 'minute').toDate(),
            status: 'scheduled',
            slug: 'third',
            authors: [{
                id: testUtils.getExistingData().users[0].id
            }]
        }));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().subtract(10, 'minute').toDate(),
            status: 'scheduled',
            slug: 'fourth',
            authors: [{
                id: testUtils.getExistingData().users[0].id
            }]
        }));

        resources.push(testUtils.DataGenerator.forKnex.createPost({
            created_by: testUtils.getExistingData().users[0].id,
            published_by: testUtils.getExistingData().users[0].id,
            published_at: moment().add(30, 'seconds').toDate(),
            status: 'scheduled',
            slug: 'fifth',
            type: 'page',
            authors: [{
                id: testUtils.getExistingData().users[0].id
            }]
        }));

        const result = await Promise.mapSeries(resources, function (post) {
            return models.Post.add(post, {context: {internal: true}});
        });

        result.length.should.eql(5);
    });

    describe('publish', function () {
        let token;

        before(function () {
            const schedulerKey = _.find(testUtils.getExistingData().apiKeys, {integration: {slug: 'ghost-scheduler'}});

            token = localUtils.getValidAdminToken('/admin/', schedulerKey);
        });

        it('publishes posts', async function () {
            const res = await request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[0].id}/?token=${token}`))
                .set('Origin', config.get('url'))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            jsonResponse.posts[0].id.should.eql(resources[0].id);
            jsonResponse.posts[0].status.should.eql('published');
        });

        it('publishes page', async function () {
            const res = await request
                .put(localUtils.API.getApiQuery(`schedules/pages/${resources[4].id}/?token=${token}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            jsonResponse.pages[0].id.should.eql(resources[4].id);
            jsonResponse.pages[0].status.should.eql('published');
        });

        it('no access', function () {
            const zapierKey = _.find(testUtils.getExistingData().apiKeys, {integration: {slug: 'ghost-backup'}});
            const zapierToken = localUtils.getValidAdminToken('/admin/', zapierKey);

            return request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[0].id}/?token=${zapierToken}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(403);
        });

        it('should fail with invalid resource type', function () {
            return request
                .put(localUtils.API.getApiQuery(`schedules/this_is_invalid/${resources[0].id}/?token=${token}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(422);
        });

        it('published_at is x seconds in past, but still in tolerance', function () {
            return request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[1].id}/?token=${token}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);
        });

        it('not found', function () {
            return request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[2].id}/?token=${token}`))
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(404);
        });

        it('force publish', function () {
            return request
                .put(localUtils.API.getApiQuery(`schedules/posts/${resources[3].id}/?token=${token}`))
                .send({
                    force: true
                })
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);
        });
    });
});
<|endoftext|>


<commit_before>load([
        'Plus/Services/CacheFactory',
        'Plus/Services/Cache'
    ],
    function (/**Plus.Services.CacheFactory*/CacheFactory,
              /**Plus.Services.Cache*/Cache) {

        beforeEach(function () {
            CacheFactory.clear();
        });

        describe('singleton', function () {
            it('is injected as a service', function () {
                CacheFactory.should.be.an.Object();
            });
        });

        describe('clear', function () {
            it('clears the caches from memory', function () {
                CacheFactory.count().should.be.equal(0);
                CacheFactory.create('Test').should.be.an.instanceOf(Cache);
                CacheFactory.count().should.be.equal(1);
                CacheFactory.clear();
                CacheFactory.count().should.be.equal(0);
            });
        });

        describe('create', function () {
            throws('cache Test already exists.', function () {
                CacheFactory.create('Test');
                CacheFactory.create('Test');
            });
            it('creates a new cache', function () {
                CacheFactory.has('Test').should.be.False();
                var c = CacheFactory.create('Test');
                CacheFactory.has('Test').should.be.True();
                c.should.be.an.instanceOf(Cache);
            });
        });

        describe('get', function () {
            throws('cache Test not found.', function () {
                CacheFactory.get('Test');
            });
            it('creates a cache object', function () {
                var c1 = CacheFactory.create('Test');
                var c2 = CacheFactory.get('Test');
                c1.should.be.an.instanceOf(Cache);
                c2.should.be.an.instanceOf(Cache);
                c1.should.be.equal(c2);
            });
        });

        // uses Date.UTC so test pass when timezone is different (i.e. travis-ci)
        describe('toObject', function () {
            it('returns empty object if factory is empty', function () {
                CacheFactory.toObject().should.be.eql({version: 1, caches: []});
            });
            it('sets a version', function () {
                CacheFactory.create('Test', new Date(Date.UTC(2015, 1, 1, 0, 0, 0)), 60);
                var obj = CacheFactory.toObject();
                obj.version.should.be.equal(1);
            });
            it('stores caches in an array', function () {
                CacheFactory.create('Test', new Date(Date.UTC(2015, 1, 1, 0, 0, 0)), 60);
                var obj = CacheFactory.toObject();
                obj.caches.should.be.an.Array().and.length(1);
            });
            it('attaches each cache to the object', function () {
                CacheFactory.create('Test', new Date(Date.UTC(2015, 1, 1, 0, 0, 0)), 60);
                var obj = CacheFactory.toObject();
                obj.caches.should.be.length(1);
                obj.caches[0].should.be.eql({
                    name: 'Test',
                    expires: 'Sun, 01 Feb 2015 01:00:00 GMT',
                    ttl: 60,
                    data: {}
                });
            });
            it('skips caches without a TTL', function () {
                CacheFactory.create('John');
                CacheFactory.create('Smith', new Date(), 120);
                var obj = CacheFactory.toObject();
                obj.caches.should.be.an.Array().and.length(1);
                obj.caches[0].name.should.be.equal('Smith');
            });
        });

        describe('fromObject', function () {
            throws('unexpected data in cache file.', function () {
                CacheFactory.fromObject({
                    version: 1,
                    caches: [
                        {name: 'Test'}
                    ]
                });
            });
            throws('unsupported version', function () {
                CacheFactory.fromObject({
                    version: 2
                });
            });
            throws('expected an array', function () {
                CacheFactory.fromObject({
                    version: 1,
                    caches: {}
                });
            });
            it('clears the caches', function () {
                CacheFactory.create('Test');
                CacheFactory.fromObject({
                    version: 1,
                    caches: []
                });
                CacheFactory.count().should.be.equal(0);
            });
            it('keeps if not expired', function () {
                var obj = {
                    version: 1,
                    caches: [
                        {
                            name: 'Test',
                            expires: (new Date(2099, 1, 1)).toGMTString(),
                            ttl: 60,
                            data: {
                                name: 'ThinkingMedia'
                            }
                        }
                    ]
                };
                CacheFactory.fromObject(obj);
                var c = CacheFactory.get('Test');
                c.should.be.instanceOf(Cache);
                c.get('name').should.be.equal('ThinkingMedia');
            });
            it('skips expired caches', function () {
                var obj = {
                    version: 1,
                    caches: [
                        {
                            name: 'Test',
                            expires: (new Date(1999, 1, 1)).toGMTString(),
                            ttl: 60,
                            data: {
                                name: 'ThinkingMedia'
                            }
                        }, {
                            name: 'Smith',
                            expires: (new Date(2099, 1, 1)).toGMTString(),
                            ttl: 60,
                            data: {
                                name: 'House'
                            }
                        }
                    ]
                };
                CacheFactory.fromObject(obj);
                CacheFactory.has('Test').should.be.False();
                var c = CacheFactory.get('Smith');
                c.should.be.an.instanceOf(Cache);
                c.get('name').should.be.equal('House');
            });
        });

        describe('save', function () {
            throws('invalid fileName', function () {
                CacheFactory.save(null);
            });
            writes('basic file if no caches', function (loader) {
                /**
                 * @type {Plus.Services.CacheFactory}
                 */
                var factory = loader.resolve('Plus/Services/CacheFactory');
                factory.create('Test').put('name', 'thinkingmedia');
                factory.save('readme.json');
            }, function (name, value) {
                name.should.be.equal('readme.json');
                value.should.be.equal('{"version":1,"caches":[]}');
            });
            writes('data to disk', function (loader) {
                /**
                 * @type {Plus.Services.CacheFactory}
                 */
                var factory = loader.resolve('Plus/Services/CacheFactory');
                factory.create('Test', new Date(2015, 1, 1), 60).put('name', 'thinkingmedia');
                factory.save('readme.json');
            }, function (name, value) {
                name.should.be.equal('readme.json');
                value.should.be.equal('{"version":1,"caches":[{"name":"Test","expires":"Sun, 01 Feb 2015 06:00:00 GMT","ttl":60,"data":{"name":"thinkingmedia"}}]}');
            });
        });

        describe('load', function () {
            throws('invalid fileName', function () {
                CacheFactory.load(null);
            });

            reads('empty file', function (loader) {
                var factory = loader.resolve('Plus/Services/CacheFactory');
                (function () {
                    factory.load('readme.json');
                }).should.throw('invalid file: readme.json');
            }, '');

            reads('loads caches that have not expired', function (loader) {
                /**
                 * @type {Plus.Services.CacheFactory}
                 */
                var factory = loader.resolve('Plus/Services/CacheFactory');
                factory.load('readme.json');
                var c = factory.get('Test');
                // @todo why does this fail?
                //c.should.be.an.instanceOf(Cache);
                c.get('name').should.be.equal('thinkingmedia');
            }, '{"version":1,"caches":[{"name":"Test","expires":"Sun, 01 Feb 2099 06:00:00 GMT","ttl":60,"data":{"name":"thinkingmedia"}}]}', function (name) {
                name.should.be.equal('readme.json');
            });

            reads('skips caches that have expired', function (loader) {
                /**
                 * @type {Plus.Services.CacheFactory}
                 */
                var factory = loader.resolve('Plus/Services/CacheFactory');
                factory.load('readme.json');
                factory.has('Test').should.be.False();
            }, '{"version":1,"caches":[{"name":"Test","expires":"1999-02-01T06:00:00.000Z","ttl":60,"data":{"name":"thinkingmedia"}}]}', function (name) {
                name.should.be.equal('readme.json');
            });
        })

    });<commit_msg>fixes timezone for tests #39<commit_after>load([
        'Plus/Services/CacheFactory',
        'Plus/Services/Cache'
    ],
    function (/**Plus.Services.CacheFactory*/CacheFactory,
              /**Plus.Services.Cache*/Cache) {

        beforeEach(function () {
            CacheFactory.clear();
        });

        describe('singleton', function () {
            it('is injected as a service', function () {
                CacheFactory.should.be.an.Object();
            });
        });

        describe('clear', function () {
            it('clears the caches from memory', function () {
                CacheFactory.count().should.be.equal(0);
                CacheFactory.create('Test').should.be.an.instanceOf(Cache);
                CacheFactory.count().should.be.equal(1);
                CacheFactory.clear();
                CacheFactory.count().should.be.equal(0);
            });
        });

        describe('create', function () {
            throws('cache Test already exists.', function () {
                CacheFactory.create('Test');
                CacheFactory.create('Test');
            });
            it('creates a new cache', function () {
                CacheFactory.has('Test').should.be.False();
                var c = CacheFactory.create('Test');
                CacheFactory.has('Test').should.be.True();
                c.should.be.an.instanceOf(Cache);
            });
        });

        describe('get', function () {
            throws('cache Test not found.', function () {
                CacheFactory.get('Test');
            });
            it('creates a cache object', function () {
                var c1 = CacheFactory.create('Test');
                var c2 = CacheFactory.get('Test');
                c1.should.be.an.instanceOf(Cache);
                c2.should.be.an.instanceOf(Cache);
                c1.should.be.equal(c2);
            });
        });

        // uses Date.UTC so test pass when timezone is different (i.e. travis-ci)
        describe('toObject', function () {
            it('returns empty object if factory is empty', function () {
                CacheFactory.toObject().should.be.eql({version: 1, caches: []});
            });
            it('sets a version', function () {
                CacheFactory.create('Test', new Date(Date.UTC(2015, 1, 1, 0, 0, 0)), 60);
                var obj = CacheFactory.toObject();
                obj.version.should.be.equal(1);
            });
            it('stores caches in an array', function () {
                CacheFactory.create('Test', new Date(Date.UTC(2015, 1, 1, 0, 0, 0)), 60);
                var obj = CacheFactory.toObject();
                obj.caches.should.be.an.Array().and.length(1);
            });
            it('attaches each cache to the object', function () {
                CacheFactory.create('Test', new Date(Date.UTC(2015, 1, 1, 0, 0, 0)), 60);
                var obj = CacheFactory.toObject();
                obj.caches.should.be.length(1);
                obj.caches[0].should.be.eql({
                    name: 'Test',
                    expires: 'Sun, 01 Feb 2015 01:00:00 GMT',
                    ttl: 60,
                    data: {}
                });
            });
            it('skips caches without a TTL', function () {
                CacheFactory.create('John');
                CacheFactory.create('Smith', new Date(), 120);
                var obj = CacheFactory.toObject();
                obj.caches.should.be.an.Array().and.length(1);
                obj.caches[0].name.should.be.equal('Smith');
            });
        });

        describe('fromObject', function () {
            throws('unexpected data in cache file.', function () {
                CacheFactory.fromObject({
                    version: 1,
                    caches: [
                        {name: 'Test'}
                    ]
                });
            });
            throws('unsupported version', function () {
                CacheFactory.fromObject({
                    version: 2
                });
            });
            throws('expected an array', function () {
                CacheFactory.fromObject({
                    version: 1,
                    caches: {}
                });
            });
            it('clears the caches', function () {
                CacheFactory.create('Test');
                CacheFactory.fromObject({
                    version: 1,
                    caches: []
                });
                CacheFactory.count().should.be.equal(0);
            });
            it('keeps if not expired', function () {
                var obj = {
                    version: 1,
                    caches: [
                        {
                            name: 'Test',
                            expires: (new Date(2099, 1, 1)).toGMTString(),
                            ttl: 60,
                            data: {
                                name: 'ThinkingMedia'
                            }
                        }
                    ]
                };
                CacheFactory.fromObject(obj);
                var c = CacheFactory.get('Test');
                c.should.be.instanceOf(Cache);
                c.get('name').should.be.equal('ThinkingMedia');
            });
            it('skips expired caches', function () {
                var obj = {
                    version: 1,
                    caches: [
                        {
                            name: 'Test',
                            expires: (new Date(1999, 1, 1)).toGMTString(),
                            ttl: 60,
                            data: {
                                name: 'ThinkingMedia'
                            }
                        }, {
                            name: 'Smith',
                            expires: (new Date(2099, 1, 1)).toGMTString(),
                            ttl: 60,
                            data: {
                                name: 'House'
                            }
                        }
                    ]
                };
                CacheFactory.fromObject(obj);
                CacheFactory.has('Test').should.be.False();
                var c = CacheFactory.get('Smith');
                c.should.be.an.instanceOf(Cache);
                c.get('name').should.be.equal('House');
            });
        });

        describe('save', function () {
            throws('invalid fileName', function () {
                CacheFactory.save(null);
            });
            writes('basic file if no caches', function (loader) {
                /**
                 * @type {Plus.Services.CacheFactory}
                 */
                var factory = loader.resolve('Plus/Services/CacheFactory');
                factory.create('Test').put('name', 'thinkingmedia');
                factory.save('readme.json');
            }, function (name, value) {
                name.should.be.equal('readme.json');
                value.should.be.equal('{"version":1,"caches":[]}');
            });
            writes('data to disk', function (loader) {
                /**
                 * @type {Plus.Services.CacheFactory}
                 */
                var factory = loader.resolve('Plus/Services/CacheFactory');
                factory.create('Test', new Date(Date.UTC(2015, 1, 1)), 60).put('name', 'thinkingmedia');
                factory.save('readme.json');
            }, function (name, value) {
                name.should.be.equal('readme.json');
                value.should.be.equal('{"version":1,"caches":[{"name":"Test","expires":"Sun, 01 Feb 2015 01:00:00 GMT","ttl":60,"data":{"name":"thinkingmedia"}}]}');
            });
        });

        describe('load', function () {
            throws('invalid fileName', function () {
                CacheFactory.load(null);
            });

            reads('empty file', function (loader) {
                var factory = loader.resolve('Plus/Services/CacheFactory');
                (function () {
                    factory.load('readme.json');
                }).should.throw('invalid file: readme.json');
            }, '');

            reads('loads caches that have not expired', function (loader) {
                /**
                 * @type {Plus.Services.CacheFactory}
                 */
                var factory = loader.resolve('Plus/Services/CacheFactory');
                factory.load('readme.json');
                var c = factory.get('Test');
                // @todo why does this fail?
                //c.should.be.an.instanceOf(Cache);
                c.get('name').should.be.equal('thinkingmedia');
            }, '{"version":1,"caches":[{"name":"Test","expires":"Sun, 01 Feb 2099 06:00:00 GMT","ttl":60,"data":{"name":"thinkingmedia"}}]}', function (name) {
                name.should.be.equal('readme.json');
            });

            reads('skips caches that have expired', function (loader) {
                /**
                 * @type {Plus.Services.CacheFactory}
                 */
                var factory = loader.resolve('Plus/Services/CacheFactory');
                factory.load('readme.json');
                factory.has('Test').should.be.False();
            }, '{"version":1,"caches":[{"name":"Test","expires":"1999-02-01T06:00:00.000Z","ttl":60,"data":{"name":"thinkingmedia"}}]}', function (name) {
                name.should.be.equal('readme.json');
            });
        })

    });<|endoftext|>


<commit_before>/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}<commit_msg>- removed unused webtoolkit.base64.js library<commit_after><|endoftext|>


<commit_before>test(
  'OptionSomeTest',

  [
    'ephox.katamari.api.Fun',
    'ephox.katamari.api.Option',
    'ephox.katamari.test.arb.ArbDataTypes',
    'ephox.wrap.Jsc',
    'global!Array',
    'global!Math'
  ],

  function (Fun, Option, ArbDataTypes, Jsc, Array, Math) {
    var testSanity = function () {
      var boom = function(f) { throw 'Should not be called'; };

      var s = Option.some(5);
      assert.eq(true, s.isSome());
      assert.eq(false, s.isNone());
      assert.eq(5, s.getOr(6));
      assert.eq(5, s.getOrThunk(function () { return 6; }));
      assert.eq(5, s.getOrDie('Died!'));
      assert.eq(5, s.or(Option.some(6)).getOrDie());
      assert.eq(5, s.orThunk(boom).getOrDie());

      assert.eq(11, s.fold(boom, function (v) {
        return v + 6;
      }));

      assert.eq(10, s.map(function (v) {
        return v * 2;
      }).getOrDie());

      assert.eq('test5', s.bind(function (v) {
        return Option.some('test' + v);
      }).getOrDie());

      assert.eq(5, Option.some(s).flatten().getOrDie());
      assert.eq(true, Option.some(Option.none()).flatten().isNone());
      assert.eq(5, s.filter(Fun.constant(true)).getOrDie());
      assert.eq(true, s.filter(Fun.constant(false)).flatten().isNone());

      assert.eq(true, Option.from(5).isSome());
      assert.eq(5, Option.from(5).getOrDie('Died!'));

      assert.eq(false, Option.some(4).equals(Option.none()));
      assert.eq(false, Option.some(2).equals(Option.some(4)));
      assert.eq(true, Option.some(5).equals(Option.some(5)));
      assert.eq(false, Option.some(5.1).equals(Option.some(5.3)));

      var comparator = function(a, b) { return Math.round(a) === Math.round(b); };

      assert.eq(true, Option.some(5.1).equals_(Option.some(5.3), comparator));
      assert.eq(false, Option.some(5.1).equals_(Option.some(5.9), comparator));
      assert.eq(true, Option.equals_(Option.some(5.1), Option.some(5.3), comparator));

      assert.eq([1], Option.some(1).toArray());
      assert.eq([{ cat: 'dog' }], Option.some({ cat: 'dog' }).toArray());
      assert.eq([[ 1 ]], Option.some([1]).toArray());

      var plus2 = function(a) { return a + 2; };
      assert.eq(true, Option.some(5).ap(Option.some(plus2)).equals(Option.some(7)));
      assert.eq(true, Option.some(5).ap(Option.none()).equals(Option.none()));

      var person = function (name) {
        return function (age) {
          return function (address) {
            return { name: name, age: age, address: address };
          };
        };
      };

      assert.eq({name:'bob', age:25, address:'the moon'}, Option.some('the moon').ap(Option.some(25).ap(Option.some('bob').map(person))).getOrDie());

      assert.eq(true, Option.some(6).or(Option.some(7)).equals(Option.some(6)));
      assert.eq(true, Option.some(3).or(Option.none()).equals(Option.some(3)));

      var assertOptionEq = function(expected, actual) {
        var same = expected.isNone() ? actual.isNone() : (actual.isSome() && expected.getOrDie() === actual.getOrDie());
        if (!same) {
          // assumes toString() works
          assert.fail('Expected: ' + expected.toString() + ' Actual: ' + actual.toString());
        }
      };

      assertOptionEq(Option.some(6), Option.some(6).filter(function(x) { return x === 6; }));
      assertOptionEq(Option.some(6), Option.some(6).filter(Fun.constant(true)));

      assert.eq('a', Option.some('a').fold(Fun.die('boom'), Fun.identity));
      assert.eq(['z'], Option.some('z').fold(Fun.die('boom'), function () { return Array.prototype.slice.call(arguments); }));
      assert.eq('az', Option.some('a').fold(Fun.die('boom'), function(x) { return x + 'z'; }));
    };

    var testSpecs = function () {
      var arbOptionSome = ArbDataTypes.optionSome;

      Jsc.property('Checking some(x).fold(die, id) === x', 'json', function (json) {
        var opt = Option.some(json);
        var actual = opt.fold(Fun.die('Should not be none!'), Fun.identity);
        return Jsc.eq(json, actual);
      });

      Jsc.property('Checking some(x).is(x) === true', 'json', function (json) {
        var opt = Option.some(json);
        return Jsc.eq(true, opt.is(json));
      });

      Jsc.property('Checking some(x).isSome === true', arbOptionSome, function (opt) {
        return Jsc.eq(true, opt.isSome());
      });

      Jsc.property('Checking some(x).isNone === false', arbOptionSome, function (opt) {
        return Jsc.eq(false, opt.isNone());
      });

      Jsc.property('Checking some(x).getOr(v) === x', arbOptionSome, 'json', 'json', function (json1, json2) {
        return Jsc.eq(json1, Option.some(json1).getOr(json2));
      });

      Jsc.property('Checking some(x).getOrThunk(_ -> v) === x', 'json', Jsc.fun(Jsc.json), function (json1, thunk) {
        return Jsc.eq(json1, Option.some(json1).getOrThunk(thunk));
      });

      // Require non empty string of msg falsiness gets in the way.
      Jsc.property('Checking some.getOrDie() never throws', 'json', Jsc.nestring, function (json, s) {
        try {
          var opt = Option.some(json);
          opt.getOrDie(s);
          return Jsc.eq(json, opt.getOrDie(s));
        } catch (err) {
          return 'Should not throw error: ' + err;
        }
      });

      Jsc.property('Checking some(x).or(oSomeValue) === some(x)', 'json', arbOptionSome, function (json, other) {
        var output = Option.some(json).or(other);
        return Jsc.eq(true, output.is(json));
      });

      Jsc.property('Checking some(x).orThunk(_ -> oSomeValue) === some(x)', 'json', arbOptionSome, function (json, other) {
        var output = Option.some(json).orThunk(function () {
          return other;
        });
        return Jsc.eq(true, output.is(json));
      });

      Jsc.property('Checking some(x).map(f) === some(f(x))', 'json', 'json -> json', function (json, f) {
        var opt = Option.some(json);
        var actual = opt.map(f);
        return Jsc.eq(f(json), actual.getOrDie());
      });

      Jsc.property('Checking some(x).ap(Option.some(f) === some(f(x))', 'json', 'string -> json', function (json, f) {
        var opt = Option.some(json);
        var g = Option.some(f);
        var actual = opt.ap(g);
        return Jsc.eq(f(json), actual.getOrDie());
      });

      Jsc.property('Checking some(x).each(f) === undefined and f gets x', arbOptionSome, function (opt) {
        var hack = null;
        var actual = opt.each(function (x) {
          hack = x;
        });
        return Jsc.eq(undefined, actual) && hack == opt.getOrDie();
      });

      return;

      Jsc.property('Given f :: s -> some(b), checking none.bind(f) === none', arbOptionSome, Jsc.fn(arbOptionSome), function (opt, f) {
        var actual = opt.bind(f);
        return Jsc.eq(true, actual.isNone());
      });

      Jsc.property('Given f :: s -> none, checking none.bind(f) === none', arbOptionSome, Jsc.fn(arbOptionNone), function (opt, f) {
        var actual = opt.bind(f);
        return Jsc.eq(true, actual.isNone());
      });

      Jsc.property('Checking none.flatten === none', arbOptionSome, function (opt) {
        return Jsc.eq(true, opt.flatten().isNone());
      });

      Jsc.property('Checking none.exists === false', arbOptionSome, 'string -> bool', function (opt, f) {
        return Jsc.eq(false, opt.exists(f));
      });

      Jsc.property('Checking none.forall === true', arbOptionSome, 'string -> bool', function (opt, f) {
        return Jsc.eq(true, opt.forall(f));
      });

      Jsc.property('Checking none.filter(f) === none', arbOptionSome, Jsc.fun(Jsc.bool), function (opt, f) {
        return Jsc.eq(true, opt.filter(f).isNone());
      });

      Jsc.property('Checking none.equals(none) === true', arbOptionSome, arbOptionNone, function (opt1, opt2) {
        return Jsc.eq(true, opt1.equals(opt2));
      });

      Jsc.property('Checking none.equals_(none) === true', arbOptionSome, arbOptionNone, function (opt1, opt2) {
        return Jsc.eq(true, opt1.equals_(opt2));
      });

      Jsc.property('Checking none.toArray equals [ ]', arbOptionSome, function (opt) {
        return Jsc.eq([ ], opt.toArray());
      });

      Jsc.property('Checking none.toString equals "none()"', arbOptionSome, function (opt) {
        return Jsc.eq('none()', opt.toString());
      });
    };

    testSanity();
    testSpecs();
  }
);<commit_msg>VAN-29: exists tests<commit_after>test(
  'OptionSomeTest',

  [
    'ephox.katamari.api.Fun',
    'ephox.katamari.api.Option',
    'ephox.katamari.test.arb.ArbDataTypes',
    'ephox.wrap.Jsc',
    'global!Array',
    'global!Math'
  ],

  function (Fun, Option, ArbDataTypes, Jsc, Array, Math) {
    var testSanity = function () {
      var boom = function(f) { throw 'Should not be called'; };

      var s = Option.some(5);
      assert.eq(true, s.isSome());
      assert.eq(false, s.isNone());
      assert.eq(5, s.getOr(6));
      assert.eq(5, s.getOrThunk(function () { return 6; }));
      assert.eq(5, s.getOrDie('Died!'));
      assert.eq(5, s.or(Option.some(6)).getOrDie());
      assert.eq(5, s.orThunk(boom).getOrDie());

      assert.eq(11, s.fold(boom, function (v) {
        return v + 6;
      }));

      assert.eq(10, s.map(function (v) {
        return v * 2;
      }).getOrDie());

      assert.eq('test5', s.bind(function (v) {
        return Option.some('test' + v);
      }).getOrDie());

      assert.eq(5, Option.some(s).flatten().getOrDie());
      assert.eq(true, Option.some(Option.none()).flatten().isNone());
      assert.eq(5, s.filter(Fun.constant(true)).getOrDie());
      assert.eq(true, s.filter(Fun.constant(false)).flatten().isNone());

      assert.eq(true, Option.from(5).isSome());
      assert.eq(5, Option.from(5).getOrDie('Died!'));

      assert.eq(false, Option.some(4).equals(Option.none()));
      assert.eq(false, Option.some(2).equals(Option.some(4)));
      assert.eq(true, Option.some(5).equals(Option.some(5)));
      assert.eq(false, Option.some(5.1).equals(Option.some(5.3)));

      var comparator = function(a, b) { return Math.round(a) === Math.round(b); };

      assert.eq(true, Option.some(5.1).equals_(Option.some(5.3), comparator));
      assert.eq(false, Option.some(5.1).equals_(Option.some(5.9), comparator));
      assert.eq(true, Option.equals_(Option.some(5.1), Option.some(5.3), comparator));

      assert.eq([1], Option.some(1).toArray());
      assert.eq([{ cat: 'dog' }], Option.some({ cat: 'dog' }).toArray());
      assert.eq([[ 1 ]], Option.some([1]).toArray());

      var plus2 = function(a) { return a + 2; };
      assert.eq(true, Option.some(5).ap(Option.some(plus2)).equals(Option.some(7)));
      assert.eq(true, Option.some(5).ap(Option.none()).equals(Option.none()));

      var person = function (name) {
        return function (age) {
          return function (address) {
            return { name: name, age: age, address: address };
          };
        };
      };

      assert.eq({name:'bob', age:25, address:'the moon'}, Option.some('the moon').ap(Option.some(25).ap(Option.some('bob').map(person))).getOrDie());

      assert.eq(true, Option.some(6).or(Option.some(7)).equals(Option.some(6)));
      assert.eq(true, Option.some(3).or(Option.none()).equals(Option.some(3)));

      var assertOptionEq = function(expected, actual) {
        var same = expected.isNone() ? actual.isNone() : (actual.isSome() && expected.getOrDie() === actual.getOrDie());
        if (!same) {
          // assumes toString() works
          assert.fail('Expected: ' + expected.toString() + ' Actual: ' + actual.toString());
        }
      };

      assertOptionEq(Option.some(6), Option.some(6).filter(function(x) { return x === 6; }));
      assertOptionEq(Option.some(6), Option.some(6).filter(Fun.constant(true)));

      assert.eq('a', Option.some('a').fold(Fun.die('boom'), Fun.identity));
      assert.eq(['z'], Option.some('z').fold(Fun.die('boom'), function () { return Array.prototype.slice.call(arguments); }));
      assert.eq('az', Option.some('a').fold(Fun.die('boom'), function(x) { return x + 'z'; }));
    };

    var testSpecs = function () {
      var arbOptionSome = ArbDataTypes.optionSome;
      var arbOptionNone = ArbDataTypes.optionNone;

      Jsc.property('Checking some(x).fold(die, id) === x', 'json', function (json) {
        var opt = Option.some(json);
        var actual = opt.fold(Fun.die('Should not be none!'), Fun.identity);
        return Jsc.eq(json, actual);
      });

      Jsc.property('Checking some(x).is(x) === true', 'json', function (json) {
        var opt = Option.some(json);
        return Jsc.eq(true, opt.is(json));
      });

      Jsc.property('Checking some(x).isSome === true', arbOptionSome, function (opt) {
        return Jsc.eq(true, opt.isSome());
      });

      Jsc.property('Checking some(x).isNone === false', arbOptionSome, function (opt) {
        return Jsc.eq(false, opt.isNone());
      });

      Jsc.property('Checking some(x).getOr(v) === x', arbOptionSome, 'json', 'json', function (json1, json2) {
        return Jsc.eq(json1, Option.some(json1).getOr(json2));
      });

      Jsc.property('Checking some(x).getOrThunk(_ -> v) === x', 'json', Jsc.fun(Jsc.json), function (json1, thunk) {
        return Jsc.eq(json1, Option.some(json1).getOrThunk(thunk));
      });

      // Require non empty string of msg falsiness gets in the way.
      Jsc.property('Checking some.getOrDie() never throws', 'json', Jsc.nestring, function (json, s) {
        try {
          var opt = Option.some(json);
          opt.getOrDie(s);
          return Jsc.eq(json, opt.getOrDie(s));
        } catch (err) {
          return 'Should not throw error: ' + err;
        }
      });

      Jsc.property('Checking some(x).or(oSomeValue) === some(x)', 'json', arbOptionSome, function (json, other) {
        var output = Option.some(json).or(other);
        return Jsc.eq(true, output.is(json));
      });

      Jsc.property('Checking some(x).orThunk(_ -> oSomeValue) === some(x)', 'json', arbOptionSome, function (json, other) {
        var output = Option.some(json).orThunk(function () {
          return other;
        });
        return Jsc.eq(true, output.is(json));
      });

      Jsc.property('Checking some(x).map(f) === some(f(x))', 'json', 'json -> json', function (json, f) {
        var opt = Option.some(json);
        var actual = opt.map(f);
        return Jsc.eq(f(json), actual.getOrDie());
      });

      Jsc.property('Checking some(x).ap(Option.some(f) === some(f(x))', 'json', 'string -> json', function (json, f) {
        var opt = Option.some(json);
        var g = Option.some(f);
        var actual = opt.ap(g);
        return Jsc.eq(f(json), actual.getOrDie());
      });

      Jsc.property('Checking some(x).each(f) === undefined and f gets x', arbOptionSome, function (opt) {
        var hack = null;
        var actual = opt.each(function (x) {
          hack = x;
        });
        return Jsc.eq(undefined, actual) && hack == opt.getOrDie();
      });

      Jsc.property('Given f :: s -> some(b), checking some(x).bind(f) === some(b)', arbOptionSome, Jsc.fn(arbOptionSome), function (opt, f) {
        var actual = opt.bind(f);
        return actual.isSome() && Jsc.eq(true, actual.equals(f(opt.getOrDie())));
      });

      Jsc.property('Given f :: s -> none, checking some(x).bind(f) === none', arbOptionSome, Jsc.fn(arbOptionNone), function (opt, f) {
        var actual = opt.bind(f);
        return Jsc.eq(true, actual.isNone());
      });

      Jsc.property('Checking some(none).flatten === none', arbOptionNone, function (inside) {
        var opt = Option.some(inside);
        return Jsc.eq(true, opt.flatten().isNone());
      });

      Jsc.property('Checking some(some(y)).flatten === none', arbOptionSome, function (inside) {
        var opt = Option.some(inside);
        return Jsc.eq(inside.getOrDie(), opt.flatten().getOrDie());
      });

      Jsc.property('Checking some(x).exists(_ -> false) === false', arbOptionSome, function (opt) {
        return Jsc.eq(false, opt.exists(Fun.constant(false)));
      });

      Jsc.property('Checking some(x).exists(_ -> true) === true', arbOptionSome, function (opt) {
        return Jsc.eq(true, opt.exists(Fun.constant(true)));
      });

      Jsc.property('Checking some(x).exists(f) iff. f(x)', 'json', Jsc.fun(Jsc.bool), function (json, f) {
        var opt = Option.some(json);
        return f(json) === true ? Jsc.eq(true, opt.exists(f)) : Jsc.eq(false, opt.exists(f));
      });

      return;

      Jsc.property('Checking none.forall === true', arbOptionSome, 'string -> bool', function (opt, f) {
        return Jsc.eq(true, opt.forall(f));
      });

      Jsc.property('Checking none.filter(f) === none', arbOptionSome, Jsc.fun(Jsc.bool), function (opt, f) {
        return Jsc.eq(true, opt.filter(f).isNone());
      });

      Jsc.property('Checking none.equals(none) === true', arbOptionSome, arbOptionNone, function (opt1, opt2) {
        return Jsc.eq(true, opt1.equals(opt2));
      });

      Jsc.property('Checking none.equals_(none) === true', arbOptionSome, arbOptionNone, function (opt1, opt2) {
        return Jsc.eq(true, opt1.equals_(opt2));
      });

      Jsc.property('Checking none.toArray equals [ ]', arbOptionSome, function (opt) {
        return Jsc.eq([ ], opt.toArray());
      });

      Jsc.property('Checking none.toString equals "none()"', arbOptionSome, function (opt) {
        return Jsc.eq('none()', opt.toString());
      });
    };

    testSanity();
    testSpecs();
  }
);<|endoftext|>