<commit_before>import * as actions from './components/actions/';
import * as types from './components/constants/ActionTypes';
import reducer from './components/reducers';
import jsdom from 'jsdom';
import { assert } from 'chai';
//import { renderReact } from '..';

describe('[redux] counter actions', () => {
  it('should create an action to increment counter', () => {
    const expectedAction = {
      type: types.INCREMENT_COUNTER
    };
    assert.deepEqual(actions.incrementCounter(), expectedAction);
  });

  it('should create an action to decrement counter', () => {
    const expectedAction = {
      type: types.DECREMENT_COUNTER
    };
    assert.deepEqual(actions.decrementCounter(), expectedAction);
  });
});

describe('[redux] counter reducers', () => {
  it('should return the initial state', () => {
    assert.deepEqual(reducer(undefined, {}), { count: 0 })
  })

  it('should handle INCREMENT_COUNTER', () => {
    assert.deepEqual(
      reducer(undefined, { type: types.INCREMENT_COUNTER }),
      { count: 1 }
    )
  })

  it('should handle DECREMENT_COUNTER', () => {
    assert.deepEqual(
      reducer(undefined, { type: types.DECREMENT_COUNTER }),
      { count: -1 }
    )
  })
})
<commit_msg>change file path<commit_after>import * as actions from './components/Actions/Counter';
import * as types from './components/Constants/ActionTypes/Counter';
import reducer from './components/Reducers/Counter';
import jsdom from 'jsdom';
import { assert } from 'chai';
// import { renderReact } from '..';

describe('[redux] counter actions', () => {
  it('should create an action to increment counter', () => {
    const expectedAction = {
      type: types.INCREMENT_COUNTER,
    };
    assert.deepEqual(actions.incrementCounter(), expectedAction);
  });

  it('should create an action to decrement counter', () => {
    const expectedAction = {
      type: types.DECREMENT_COUNTER,
    };
    assert.deepEqual(actions.decrementCounter(), expectedAction);
  });
});

describe('[redux] counter reducers', () => {
  it('should return the initial state', () => {
    assert.deepEqual(reducer(undefined, {}), { count: 0 });
  });

  it('should handle INCREMENT_COUNTER', () => {
    assert.deepEqual(
      reducer(undefined, { type: types.INCREMENT_COUNTER }),
      { count: 1 }
    );
  });

  it('should handle DECREMENT_COUNTER', () => {
    assert.deepEqual(
      reducer(undefined, { type: types.DECREMENT_COUNTER }),
      { count: -1 }
    );
  });
});
<|endoftext|>


<commit_before>'use strict';

// This module pits a cluster of aggressive clients against a cluster of flaky
// servers.

var path = require('path');
var ClusterSupervisor = require('../cluster-supervisor');

var supervisor = new ClusterSupervisor({
    exec: path.join(__dirname, 'rock-or-hard-place.js'),
    logicalIds: ['rock', 'hard-place'],
    createEnvironment: function (logicalId) {
        return {
            NODE_DEBUG: 'clustermon',
            HODOR_PORT: 2020,
            ROLE: logicalId
        };
    },
    workerForceStopDelay: 5000
})

supervisor.start();

<commit_msg>Configure ad hoc test rig to force stop and restart<commit_after>'use strict';

// This module pits a cluster of aggressive clients against a cluster of flaky
// servers.

var path = require('path');
var ClusterSupervisor = require('../cluster-supervisor');

var supervisor = new ClusterSupervisor({
    exec: path.join(__dirname, 'rock-or-hard-place.js'),
    logicalIds: ['rock', 'hard-place'],
    createEnvironment: function (logicalId) {
        return {
            NODE_DEBUG: 'clustermon',
            HODOR_PORT: 2020,
            ROLE: logicalId
        };
    },
    workerForceStopDelay: 5000,
    workerRestartDelay: 1000
});

supervisor.start();

<|endoftext|>


<commit_before>var path = require('path'),
    mock = require('mock-fs'),
    walk = require('../../lib/index'),
    assert = require('../lib/assert'),
    opts = { scheme: 'nested' };

describe('nested scheme', function () {
    afterEach(function () {
        mock.restore();
    });

    it('must end if levels is empty', function (done) {
        assert([], opts, [], done);
    });

    it('must throw error if levels is not found', function (done) {
        var walker = walk(['not-existing-level']);

        walker.on('error', function (err) {
            err.must.throw();
            done();
        });
    });

    it('must ignore entity without ext', function (done) {
        mock({
            blocks: {
                block: {
                    block: ''
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must detect block', function (done) {
        mock({
            blocks: {
                block: {
                    'block.ext': ''
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', 'block.ext')
        }], done);
    });

    it('must detect bool mod', function (done) {
        mock({
            blocks: {
                block: {
                    '_bool-mod': {
                        'block_bool-mod.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            modName: 'bool-mod',
            modVal: true,
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '_bool-mod', 'block_bool-mod.ext')
        }], done);
    });

    it('must detect mod', function (done) {
        mock({
            blocks: {
                block: {
                    _mod: {
                        'block_mod_val.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            modName: 'mod',
            modVal: 'val',
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '_mod', 'block_mod_val.ext')
        }], done);
    });

    it('must detect elem', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        'block__elem.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            elem: 'elem',
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '__elem', 'block__elem.ext')
        }], done);
    });

    it('must detect bool mod of elem', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        '_bool-mod': {
                            'block__elem_bool-mod.ext': ''
                        }
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            elem: 'elem',
            modName: 'bool-mod',
            modVal: true,
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '__elem', '_bool-mod', 'block__elem_bool-mod.ext')
        }], done);
    });

    it('must detect elem mod', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        _mod: {
                            'block__elem_mod_val.ext': ''
                        }
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            elem: 'elem',
            modName: 'mod',
            modVal: 'val',
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '__elem', '_mod', 'block__elem_mod_val.ext')
        }], done);
    });

    it('must detect complex entities', function (done) {
        mock({
            blocks: {
                block: {
                    'block.ext': '',
                    '_bool-mod': {
                        'block_bool-mod.ext': ''
                    },
                    _mod: {
                        'block_mod_val.ext': ''
                    },
                    __elem: {
                        'block__elem.ext': '',
                        '_bool-mod': {
                            'block__elem_bool-mod.ext': ''
                        },
                        _mod: {
                            'block__elem_mod_val.ext': ''
                        }
                    }
                }
            }
        });

        assert(['blocks'], opts, [
            {
                block: 'block',
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', 'block.ext')
            },
            {
                block: 'block',
                elem: 'elem',
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '__elem', 'block__elem.ext')
            },
            {
                block: 'block',
                modName: 'bool-mod',
                modVal: true,
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '_bool-mod', 'block_bool-mod.ext')
            },
            {
                block: 'block',
                modName: 'mod',
                modVal: 'val',
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '_mod', 'block_mod_val.ext')
            },
            {
                block: 'block',
                elem: 'elem',
                modName: 'bool-mod',
                modVal: true,
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '__elem', '_bool-mod', 'block__elem_bool-mod.ext')
            },
            {
                block: 'block',
                elem: 'elem',
                modName: 'mod',
                modVal: 'val',
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '__elem', '_mod', 'block__elem_mod_val.ext')
            }
        ], done);
    });

    it('must detect block in few levels', function (done) {
        mock({
            'common.blocks': {
                block: {
                    'block.ext': ''
                }
            },
            'desktop.blocks': {
                block: {
                    'block.ext': ''
                }
            }
        });

        assert(['common.blocks', 'desktop.blocks'], opts, [
            {
                block: 'block',
                level: 'common.blocks',
                path: path.join('common.blocks', 'block', 'block.ext'),
                tech: 'ext'
            },
            {
                block: 'block',
                level: 'desktop.blocks',
                path: path.join('desktop.blocks', 'block', 'block.ext'),
                tech: 'ext'
            }
        ], done);
    });

    it('must not detect file in root of level', function (done) {
        mock({
            blocks: {
                'block.ext': ''
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must not detect block if filename not match with dirname', function (done) {
        mock({
            blocks: {
                block: {
                    'other-block.ext': ''
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must not detect elem if filename not match with dirname', function (done) {
        mock({
            blocks: {
                block: {
                    _mod: {
                        'block_other-mod.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must not detect mod if filename not match with dirname', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        'block__other-elem.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must not detect elem mod if filename not match with dirname', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        _mod: {
                            'block__elem_other-mod.ext': ''
                        }
                    }
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });
});
<commit_msg>Add test<commit_after>var path = require('path'),
    mock = require('mock-fs'),
    walk = require('../../lib/index'),
    assert = require('../lib/assert'),
    opts = { scheme: 'nested' };

describe('nested scheme', function () {
    afterEach(function () {
        mock.restore();
    });

    it('must end if levels is empty', function (done) {
        assert([], opts, [], done);
    });

    it('must throw error if levels is not found', function (done) {
        var walker = walk(['not-existing-level']);

        walker.on('error', function (err) {
            err.must.throw();
            done();
        });
    });

    it('must ignore entity without ext', function (done) {
        mock({
            blocks: {
                block: {
                    block: ''
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must detect block', function (done) {
        mock({
            blocks: {
                block: {
                    'block.ext': ''
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', 'block.ext')
        }], done);
    });

    it('must detect bool mod', function (done) {
        mock({
            blocks: {
                block: {
                    '_bool-mod': {
                        'block_bool-mod.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            modName: 'bool-mod',
            modVal: true,
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '_bool-mod', 'block_bool-mod.ext')
        }], done);
    });

    it('must detect mod', function (done) {
        mock({
            blocks: {
                block: {
                    _mod: {
                        'block_mod_val.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            modName: 'mod',
            modVal: 'val',
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '_mod', 'block_mod_val.ext')
        }], done);
    });

    it('must detect elem', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        'block__elem.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            elem: 'elem',
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '__elem', 'block__elem.ext')
        }], done);
    });

    it('must detect bool mod of elem', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        '_bool-mod': {
                            'block__elem_bool-mod.ext': ''
                        }
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            elem: 'elem',
            modName: 'bool-mod',
            modVal: true,
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '__elem', '_bool-mod', 'block__elem_bool-mod.ext')
        }], done);
    });

    it('must detect elem mod', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        _mod: {
                            'block__elem_mod_val.ext': ''
                        }
                    }
                }
            }
        });

        assert(['blocks'], opts, [{
            block: 'block',
            elem: 'elem',
            modName: 'mod',
            modVal: 'val',
            tech: 'ext',
            level: 'blocks',
            path: path.join('blocks', 'block', '__elem', '_mod', 'block__elem_mod_val.ext')
        }], done);
    });

    it('must detect complex entities', function (done) {
        mock({
            blocks: {
                block: {
                    'block.ext': '',
                    '_bool-mod': {
                        'block_bool-mod.ext': ''
                    },
                    _mod: {
                        'block_mod_val.ext': ''
                    },
                    __elem: {
                        'block__elem.ext': '',
                        '_bool-mod': {
                            'block__elem_bool-mod.ext': ''
                        },
                        _mod: {
                            'block__elem_mod_val.ext': ''
                        }
                    }
                }
            }
        });

        assert(['blocks'], opts, [
            {
                block: 'block',
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', 'block.ext')
            },
            {
                block: 'block',
                elem: 'elem',
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '__elem', 'block__elem.ext')
            },
            {
                block: 'block',
                modName: 'bool-mod',
                modVal: true,
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '_bool-mod', 'block_bool-mod.ext')
            },
            {
                block: 'block',
                modName: 'mod',
                modVal: 'val',
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '_mod', 'block_mod_val.ext')
            },
            {
                block: 'block',
                elem: 'elem',
                modName: 'bool-mod',
                modVal: true,
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '__elem', '_bool-mod', 'block__elem_bool-mod.ext')
            },
            {
                block: 'block',
                elem: 'elem',
                modName: 'mod',
                modVal: 'val',
                tech: 'ext',
                level: 'blocks',
                path: path.join('blocks', 'block', '__elem', '_mod', 'block__elem_mod_val.ext')
            }
        ], done);
    });

    it('must detect block in few levels', function (done) {
        mock({
            'common.blocks': {
                block: {
                    'block.ext': ''
                }
            },
            'desktop.blocks': {
                block: {
                    'block.ext': ''
                }
            }
        });

        assert(['common.blocks', 'desktop.blocks'], opts, [
            {
                block: 'block',
                level: 'common.blocks',
                path: path.join('common.blocks', 'block', 'block.ext'),
                tech: 'ext'
            },
            {
                block: 'block',
                level: 'desktop.blocks',
                path: path.join('desktop.blocks', 'block', 'block.ext'),
                tech: 'ext'
            }
        ], done);
    });

    it('must not detect file in root of level', function (done) {
        mock({
            blocks: {
                'block.ext': ''
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must not detect block if filename not match with dirname', function (done) {
        mock({
            blocks: {
                block: {
                    'other-block.ext': ''
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must not detect elem if filename not match with dirname', function (done) {
        mock({
            blocks: {
                block: {
                    _mod: {
                        'block_other-mod.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must not detect mod if filename not match with dirname', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        'block__other-elem.ext': ''
                    }
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must not detect elem mod if filename not match with dirname', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        _mod: {
                            'block__elem_other-mod.ext': ''
                        }
                    }
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });

    it('must handle invalid BEM-notation', function (done) {
        mock({
            blocks: {
                block: {
                    __elem: {
                        _mod: {
                            '^_^.ext': ''
                        },
                        '^_^.ext': ''
                    },
                    _mod: {
                        '^_^.ext': ''
                    },
                    '^_^.ext': ''
                }
            }
        });

        assert(['blocks'], opts, [], done);
    });
});
<|endoftext|>


<commit_before>/*eslint no-unused-expressions: "off"*/
/*eslint no-undef: "off"*/
describe("main-nav", function() {
    "use strict";

    // todo: clean up by creating page object pattern

    beforeEach(function() {
        browser.windowHandleSize({width: 800, height: 600});
    });

    // unexplicably fails because `browser.debug()` shows it is evident it is visibility in the viewport
    // isVisibleWithinViewport unrealiable as it does not understand `transform: translate3d()`
    // `browser.getCssProperty("#main-nav", "transform")` does not work due to vendor prefixes
    // (not-so-elegant) solution is to look for existence of classes `.scroll-down` (not visible) and `.scroll-up` (visible)
    // isVisible returns false if element is not found in the DOM so perfect for this use-case
    it("should show main-nav", function() {
        browser.url("/?loader=false");
        // initial load does not have neither class
        browser.isVisible("#main-nav").should.be.true;
        browser.isVisible("#main-nav.scroll-up").should.be.false;
        browser.isVisible("#main-nav.scroll-down").should.be.false;
    });

    it("should hide main-nav when scrolling down", function() {
        this.retries(4);
        browser.url("/?loader=false#writing");
        browser.pause(800);
        browser.isVisible("#main-nav.scroll-down").should.be.true;
        browser.isVisible("#main-nav.scroll-up").should.be.false;
    });

    it("should show main-nav when scrolling up", function() {
        this.retries(4);

        // scroll down
        browser.url("/?loader=false#writing");
        browser.pause(800);
        browser.isVisible("#main-nav.scroll-down").should.be.true;
        browser.isVisible("#main-nav.scroll-up").should.be.false;

        // scroll up
        browser.scroll(0, 500);
        browser.pause(1200);
        browser.isVisible("#main-nav.scroll-down").should.be.false;
        browser.isVisible("#main-nav.scroll-up").should.be.true;
    });

    it("should be responsive", function() {
        var height = 500;
        browser.url("/?loader=false");
        // small
        browser.windowHandleSize({width: 400, height: height});
        browser.isVisible("#main-nav ul li a .text")[0].should.be.false;
        browser.getCssProperty("#main-nav ul li", "float")[0].value.should.equal("left");

        // medium - 640 width
        browser.windowHandleSize({width: 640, height: height});
        browser.isVisible("#main-nav ul li a .text")[0].should.be.true;
        browser.getCssProperty("#main-nav ul li", "float")[0].value.should.equal("left");

        // xlarge - 1200 width
        browser.windowHandleSize({width: 1200, height: height});
        browser.getCssProperty("#main-nav ul", "float").value.should.equal("none");
        browser.getCssProperty("#main-nav ul li", "float")[0].value.should.equal("none");
        browser.getCssProperty("#main-nav", "background-color").parsed.hex.should.equal("#34495e");
    });

    it("should update active class for sections", function(){
        browser.windowHandleSize({width: 1200, height: 600});
        browser.url("/?loader=false");
        browser.click("#intro .scroll-down a");

        browser.waitForVisible("#main-nav li.developer.active", 2000);
    });
});
<commit_msg>Added tweaks to flaky tests<commit_after>/*eslint no-unused-expressions: "off"*/
/*eslint no-undef: "off"*/
describe("main-nav", function() {
    "use strict";

    // todo: clean up by creating page object pattern

    beforeEach(function() {
        browser.windowHandleSize({width: 800, height: 600});
    });

    // unexplicably fails because `browser.debug()` shows it is evident it is visibility in the viewport
    // isVisibleWithinViewport unrealiable as it does not understand `transform: translate3d()`
    // `browser.getCssProperty("#main-nav", "transform")` does not work due to vendor prefixes
    // (not-so-elegant) solution is to look for existence of classes `.scroll-down` (not visible) and `.scroll-up` (visible)
    // isVisible returns false if element is not found in the DOM so perfect for this use-case
    it("should show main-nav", function() {
        browser.url("/?loader=false");
        // initial load does not have neither class
        browser.isVisible("#main-nav").should.be.true;
        browser.isVisible("#main-nav.scroll-up").should.be.false;
        browser.isVisible("#main-nav.scroll-down").should.be.false;
    });

    it("should hide main-nav when scrolling down", function() {
        this.retries(4);
        browser.url("/?loader=false#writing");
        browser.pause(800);
        browser.isVisible("#main-nav.scroll-down").should.be.true;
        browser.isVisible("#main-nav.scroll-up").should.be.false;
    });

    it("should show main-nav when scrolling up", function() {
        this.retries(4);

        // scroll down
        browser.url("/?loader=false#writing");
        browser.pause(800);
        browser.isVisible("#main-nav.scroll-down").should.be.true;
        browser.isVisible("#main-nav.scroll-up").should.be.false;

        // scroll up
        browser.scroll(0, 500);
        browser.pause(1200);
        browser.isVisible("#main-nav.scroll-down").should.be.false;
        browser.isVisible("#main-nav.scroll-up").should.be.true;
    });

    it("should be responsive", function() {
        this.retries(4);
        var height = 500;
        browser.url("/?loader=false");
        // small
        browser.windowHandleSize({width: 400, height: height});
        browser.isVisible("#main-nav ul li a .text")[0].should.be.false;
        browser.getCssProperty("#main-nav ul li", "float")[0].value.should.equal("left");

        // medium - 640 width
        browser.windowHandleSize({width: 640, height: height});
        browser.isVisible("#main-nav ul li a .text")[0].should.be.true;
        browser.getCssProperty("#main-nav ul li", "float")[0].value.should.equal("left");

        // xlarge - 1200 width
        browser.windowHandleSize({width: 1200, height: height});
        browser.getCssProperty("#main-nav ul", "float").value.should.equal("none");
        browser.getCssProperty("#main-nav ul li", "float")[0].value.should.equal("none");
        browser.getCssProperty("#main-nav", "background-color").parsed.hex.should.equal("#34495e");
    });

    it("should update active class for sections", function(){
        this.retries(4);
        browser.windowHandleSize({width: 1200, height: 600});
        browser.url("/?loader=false");
        browser.click("#intro .scroll-down a");

        browser.waitForVisible("#main-nav li.developer.active", 2000);
    });
});
<|endoftext|>


<commit_before>
// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Test utilities:
	utils = require( './utils' ),

	// Module to be tested:
	vStream = require( './../lib/stats/variance' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'stats/variance', function tests() {
	'use strict';

	it( 'should export a factory function', function test() {
		expect( vStream ).to.be.a( 'function' );
	});

	it( 'should provide a method to get the initial accumulator value', function test() {
		var rStream = vStream();
		assert.strictEqual( rStream.value(), 0 );
	});

	it( 'should provide a method to get the initial accumulator value number', function test() {
		var rStream = vStream();
		assert.strictEqual( rStream.numValues(), 0 );
	});

	it( 'should provide a method to get the initial accumulator mean', function test() {
		var rStream = vStream();
		assert.strictEqual( rStream.mean(), 0 );
	});

	it( 'should provide a method to set the initial accumulator value', function test() {
		var rStream = vStream();
		rStream.value( 5 );
		assert.strictEqual( rStream.value(), 5 );
	});

	it( 'should provide a method to set the initial accumulator value number', function test() {
		var rStream = vStream();
		rStream.numValues( 5 );
		assert.strictEqual( rStream.numValues(), 5 );
	});

	it( 'should provide a method to set the initial accumulator mean', function test() {
		var rStream = vStream();
		rStream.mean( 5 );
		assert.strictEqual( rStream.mean(), 5 );
	});

	it( 'should calculate the variance of piped data', function test( done ) {
		var data, rStream,
			x2 = 0,
			VARIANCE;

		// Simulate some data...
		data = [ -1, 0, 1, -1, 0, 1, -1, 0, 1 ];

		// E[X^2] - (E[X])^2; Here, E[X] = 0.
		for ( var i = 0; i < data.length; i++ ) {
			x2 += data[ i ] * data[ i ];
		}
		VARIANCE = x2 / ( data.length - 1 );

		// Create a new variance stream:
		rStream = vStream().stream();

		// Mock reading from the stream:
		utils.readStream( rStream, onRead );

		// Mock piping a data to the stream:
		utils.writeStream( data, rStream );

		return;

		/**
		* FUNCTION: onRead( error, actual )
		*	Read event handler. Checks for errors and compares streamed data to expected data.
		*/
		function onRead( error, actual ) {
			expect( error ).to.not.exist;
			assert.deepEqual( actual[ 0 ], VARIANCE );
			done();
		} // end FUNCTION onRead()
	});

	it( 'should calculate the variance of piped data using arbitrary starting values', function test( done ) {
		var data, reducer, rStream,
			MEAN = 0,
			NUMVALUES = 100,
			SOS = 99; // 100-1 to adjust for sample variance, which is greater than population variance

		// Simulate some data...
		data = [ -1, 1, -1, 1, -1, 1, -1, 1, -1, 1 ];

		// Create a new variance stream generator:
		reducer = vStream();

		// Set the initial mean and create a new stream:
		rStream = reducer
			.value( SOS )
			.mean( MEAN )
			.numValues( NUMVALUES )
			.stream();

		// Mock reading from the stream:
		utils.readStream( rStream, onRead );

		// Mock piping a data to the stream:
		utils.writeStream( data, rStream );

		return;

		/**
		* FUNCTION: onRead( error, actual )
		*	Read event handler. Checks for errors and compares streamed data to expected data.
		*/
		function onRead( error, actual ) {
			expect( error ).to.not.exist;
			assert.closeTo( actual[ 0 ], 1 , 0.001 );
			done();
		} // end FUNCTION onRead()
	});

});<commit_msg>[UDPATE] additional variance stream tests.<commit_after>
// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Test utilities:
	utils = require( './utils' ),

	// Module to be tested:
	vStream = require( './../lib/stats/variance' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'stats/variance', function tests() {
	'use strict';

	it( 'should export a factory function', function test() {
		expect( vStream ).to.be.a( 'function' );
	});

	it( 'should provide a method to get the initial accumulator value', function test() {
		var rStream = vStream();
		assert.strictEqual( rStream.value(), 0 );
	});

	it( 'should provide a method to get the initial accumulator value number', function test() {
		var rStream = vStream();
		assert.strictEqual( rStream.numValues(), 0 );
	});

	it( 'should provide a method to get the initial accumulator mean', function test() {
		var rStream = vStream();
		assert.strictEqual( rStream.mean(), 0 );
	});

	it( 'should provide a method to set the initial accumulator value', function test() {
		var rStream = vStream();
		rStream.value( 5 );
		assert.strictEqual( rStream.value(), 5 );
	});

	it( 'should not allow a non-numeric initial accumulator value', function test() {
		var rStream = vStream();

		expect( badValue( '5' ) ).to.throw( Error );
		expect( badValue( [] ) ).to.throw( Error );
		expect( badValue( {} ) ).to.throw( Error );
		expect( badValue( null ) ).to.throw( Error );
		expect( badValue( undefined ) ).to.throw( Error );
		expect( badValue( NaN ) ).to.throw( Error );

		function badValue( value ) {
			return function() {
				rStream.value( value );
			};
		}
	});

	it( 'should provide a method to set the initial accumulator value number', function test() {
		var rStream = vStream();
		rStream.numValues( 5 );
		assert.strictEqual( rStream.numValues(), 5 );
	});

	it( 'should not allow a non-numeric initial accumulator value number', function test() {
		var rStream = vStream();

		expect( badValue( '5' ) ).to.throw( Error );
		expect( badValue( [] ) ).to.throw( Error );
		expect( badValue( {} ) ).to.throw( Error );
		expect( badValue( null ) ).to.throw( Error );
		expect( badValue( undefined ) ).to.throw( Error );
		expect( badValue( NaN ) ).to.throw( Error );

		function badValue( value ) {
			return function() {
				rStream.numValues( value );
			};
		}
	});

	it( 'should provide a method to set the initial accumulator mean', function test() {
		var rStream = vStream();
		rStream.mean( 5 );
		assert.strictEqual( rStream.mean(), 5 );
	});

	it( 'should not allow a non-numeric initial accumulator mean', function test() {
		var rStream = vStream();

		expect( badValue( '5' ) ).to.throw( Error );
		expect( badValue( [] ) ).to.throw( Error );
		expect( badValue( {} ) ).to.throw( Error );
		expect( badValue( null ) ).to.throw( Error );
		expect( badValue( undefined ) ).to.throw( Error );
		expect( badValue( NaN ) ).to.throw( Error );

		function badValue( value ) {
			return function() {
				rStream.mean( value );
			};
		}
	});

	it( 'should calculate the variance of piped data', function test( done ) {
		var data, rStream,
			x2 = 0,
			VARIANCE;

		// Simulate some data...
		data = [ -1, 0, 1, -1, 0, 1, -1, 0, 1 ];

		// E[X^2] - (E[X])^2; Here, E[X] = 0.
		for ( var i = 0; i < data.length; i++ ) {
			x2 += data[ i ] * data[ i ];
		}
		VARIANCE = x2 / ( data.length - 1 );

		// Create a new variance stream:
		rStream = vStream().stream();

		// Mock reading from the stream:
		utils.readStream( rStream, onRead );

		// Mock piping a data to the stream:
		utils.writeStream( data, rStream );

		return;

		/**
		* FUNCTION: onRead( error, actual )
		*	Read event handler. Checks for errors and compares streamed data to expected data.
		*/
		function onRead( error, actual ) {
			expect( error ).to.not.exist;
			assert.deepEqual( actual[ 0 ], VARIANCE );
			done();
		} // end FUNCTION onRead()
	});

	it( 'should calculate the variance of piped data using arbitrary starting values', function test( done ) {
		var data, reducer, rStream,
			MEAN = 0,
			NUMVALUES = 100,
			SOS = 99; // 100-1 to adjust for sample variance, which is greater than population variance

		// Simulate some data...
		data = [ -1, 1, -1, 1, -1, 1, -1, 1, -1, 1 ];

		// Create a new variance stream generator:
		reducer = vStream();

		// Set the initial mean and create a new stream:
		rStream = reducer
			.value( SOS )
			.mean( MEAN )
			.numValues( NUMVALUES )
			.stream();

		// Mock reading from the stream:
		utils.readStream( rStream, onRead );

		// Mock piping a data to the stream:
		utils.writeStream( data, rStream );

		return;

		/**
		* FUNCTION: onRead( error, actual )
		*	Read event handler. Checks for errors and compares streamed data to expected data.
		*/
		function onRead( error, actual ) {
			expect( error ).to.not.exist;
			assert.closeTo( actual[ 0 ], 1 , 0.001 );
			done();
		} // end FUNCTION onRead()
	});

});<|endoftext|>


<commit_before>import { FragmentOpcodeCompiler } from "htmlbars/compiler/fragment_opcode";
import { HydrationOpcodeCompiler } from "htmlbars/compiler/hydration_opcode";
import { FragmentCompiler } from "htmlbars/compiler/fragment";
import { HydrationCompiler } from "htmlbars/compiler/hydration";
import { domHelpers } from "htmlbars/runtime/dom_helpers";
import { Placeholder } from "htmlbars/runtime/placeholder";
import { preprocess } from "htmlbars/parser";

function equalHTML(fragment, html) {
  var div = document.createElement("div");
  div.appendChild(fragment.cloneNode(true));

  QUnit.push(div.innerHTML === html, div.innerHTML, html);
}

var dom = domHelpers();

function fragmentFor(ast) {
  /* jshint evil: true */
  var fragmentOpcodeCompiler = new FragmentOpcodeCompiler(),
      fragmentCompiler = new FragmentCompiler();

  var opcodes = fragmentOpcodeCompiler.compile(ast);
  var program = fragmentCompiler.compile(opcodes);

  var fn = new Function("dom", 'return ' + program)(dom);

  return fn( dom );
}

function hydrationFor(ast) {
  /* jshint evil: true */
  var hydrate = new HydrationOpcodeCompiler();
  var opcodes = hydrate.compile(ast);
  var hydrate2 = new HydrationCompiler();
  var program = hydrate2.compile(opcodes, []);
  return new Function("Placeholder", 'return '+program)(Placeholder);
}

module('fragment');

test('compiles a fragment', function () {
  var ast = preprocess("
{{foo}} bar {{baz}}
");
  var fragment = fragmentFor(ast);

  equalHTML(fragment, "
 bar
");
});

test('converts entities to their char/string equivalent', function () {
  var ast = preprocess("
lol < << < < ≧̸ &Borksnorlax;
");
  var fragment = fragmentFor(ast);

  equal(fragment.childNodes[0].getAttribute('title'), '"Foo & Bar"');
  equal(fragment.childNodes[0].textContent, "lol < << < < ≧̸ &Borksnorlax;");
});

test('hydrates a fragment with placeholder mustaches', function () {
  var ast = preprocess("
{{foo \"foo\" 3 blah bar=baz ack=\"syn\"}} bar {{baz}}
");
  var fragment = fragmentFor(ast).cloneNode(true);
  var hydrate = hydrationFor(ast);
  var mustaches = hydrate(fragment);

  equal(mustaches.length, 2);

  equal(mustaches[0][0], "foo");
  deepEqual(mustaches[0][1], ["foo",3,"blah"]);
  deepEqual(mustaches[0][2].types, ["string","number","id"]);
  deepEqual(mustaches[0][2].hash, {ack:"syn",bar:"baz"});
  deepEqual(mustaches[0][2].hashTypes, {ack:"string",bar:"id"});
  equal(mustaches[0][2].escaped, true);

  equal(mustaches[1][0], "baz");
  deepEqual(mustaches[1][1], []);
  equal(mustaches[1][2].escaped, true);

  mustaches[0][2].placeholder.appendChild(document.createTextNode('A'));
  mustaches[1][2].placeholder.appendChild(document.createTextNode('B'));

  equalHTML(fragment, "
A bar B
");
});

test('hydrates a fragment with placeholder mustaches (ATTRIBUTE)', function () {
  var ast = preprocess("

");
  var fragment = fragmentFor(ast).cloneNode(true);
  var hydrate = hydrationFor(ast);
  var mustaches = hydrate(fragment);

  equal(mustaches.length, 1);
  equal(mustaches[0][0], "foo");
  deepEqual(mustaches[0][1], []);
});

test('test auto insertion of text nodes for needed edges a fragment with placeholder mustaches', function () {
  var ast = preprocess("{{first}}
{{second}}
{{third}}");
  var fragment = fragmentFor(ast).cloneNode(true);
  var hydrate = hydrationFor(ast);
  var mustaches = hydrate(fragment);

  equal(mustaches.length, 3);
  equal(mustaches[0][0], "first");
  deepEqual(mustaches[0][1], []);
  equal(mustaches[1][0], "second");
  deepEqual(mustaches[1][1], []);
  equal(mustaches[2][0], "third");
  deepEqual(mustaches[2][1], []);

  mustaches[0][2].placeholder.appendText('A');
  mustaches[1][2].placeholder.appendText('B');
  mustaches[2][2].placeholder.appendText('C');

  equalHTML(fragment, "A
B
C");
});

// TODO move test to AST
test('test auto insertion of text nodes between blocks and mustaches', function () {
  var ast = preprocess("{{one}}{{two}}{{#three}}{{/three}}{{#four}}{{/four}}{{five}}");
  // "" {{one}} "" {{two}} "" {{#three}}{{/three}} "" {{#four}}{{/four}} "" {{five}} ""
  equal(ast.length, 11);
  equal(ast[0], '');
  equal(ast[2], '');
  equal(ast[4], '');
  equal(ast[6], '');
  equal(ast[8], '');
  equal(ast[10], '');
});
<commit_msg>cleanup<commit_after>import { FragmentOpcodeCompiler } from "htmlbars/compiler/fragment_opcode";
import { HydrationOpcodeCompiler } from "htmlbars/compiler/hydration_opcode";
import { FragmentCompiler } from "htmlbars/compiler/fragment";
import { HydrationCompiler } from "htmlbars/compiler/hydration";
import { domHelpers } from "htmlbars/runtime/dom_helpers";
import { Placeholder } from "htmlbars/runtime/placeholder";
import { preprocess } from "htmlbars/parser";

function equalHTML(fragment, html) {
  var div = document.createElement("div");
  div.appendChild(fragment.cloneNode(true));

  QUnit.push(div.innerHTML === html, div.innerHTML, html);
}

var dom = domHelpers();

function fragmentFor(ast) {
  /* jshint evil: true */
  var fragmentOpcodeCompiler = new FragmentOpcodeCompiler(),
      fragmentCompiler = new FragmentCompiler();

  var opcodes = fragmentOpcodeCompiler.compile(ast);
  var program = fragmentCompiler.compile(opcodes);

  var fn = new Function('return ' + program)();

  return fn( dom );
}

function hydrationFor(ast) {
  /* jshint evil: true */
  var hydrate = new HydrationOpcodeCompiler();
  var opcodes = hydrate.compile(ast);
  var hydrate2 = new HydrationCompiler();
  var program = hydrate2.compile(opcodes, []);
  return new Function("Placeholder", 'return '+program)(Placeholder);
}

module('fragment');

test('compiles a fragment', function () {
  var ast = preprocess("
{{foo}} bar {{baz}}
");
  var fragment = fragmentFor(ast);

  equalHTML(fragment, "
 bar
");
});

test('converts entities to their char/string equivalent', function () {
  var ast = preprocess("
lol < << < < ≧̸ &Borksnorlax;
");
  var fragment = fragmentFor(ast);

  equal(fragment.childNodes[0].getAttribute('title'), '"Foo & Bar"');
  equal(fragment.childNodes[0].textContent, "lol < << < < ≧̸ &Borksnorlax;");
});

test('hydrates a fragment with placeholder mustaches', function () {
  var ast = preprocess("
{{foo \"foo\" 3 blah bar=baz ack=\"syn\"}} bar {{baz}}
");
  var fragment = fragmentFor(ast).cloneNode(true);
  var hydrate = hydrationFor(ast);
  var mustaches = hydrate(fragment);

  equal(mustaches.length, 2);

  equal(mustaches[0][0], "foo");
  deepEqual(mustaches[0][1], ["foo",3,"blah"]);
  deepEqual(mustaches[0][2].types, ["string","number","id"]);
  deepEqual(mustaches[0][2].hash, {ack:"syn",bar:"baz"});
  deepEqual(mustaches[0][2].hashTypes, {ack:"string",bar:"id"});
  equal(mustaches[0][2].escaped, true);

  equal(mustaches[1][0], "baz");
  deepEqual(mustaches[1][1], []);
  equal(mustaches[1][2].escaped, true);

  mustaches[0][2].placeholder.appendChild(document.createTextNode('A'));
  mustaches[1][2].placeholder.appendChild(document.createTextNode('B'));

  equalHTML(fragment, "
A bar B
");
});

test('hydrates a fragment with placeholder mustaches (ATTRIBUTE)', function () {
  var ast = preprocess("

");
  var fragment = fragmentFor(ast).cloneNode(true);
  var hydrate = hydrationFor(ast);
  var mustaches = hydrate(fragment);

  equal(mustaches.length, 1);
  equal(mustaches[0][0], "foo");
  deepEqual(mustaches[0][1], []);
});

test('test auto insertion of text nodes for needed edges a fragment with placeholder mustaches', function () {
  var ast = preprocess("{{first}}
{{second}}
{{third}}");
  var fragment = fragmentFor(ast).cloneNode(true);
  var hydrate = hydrationFor(ast);
  var mustaches = hydrate(fragment);

  equal(mustaches.length, 3);
  equal(mustaches[0][0], "first");
  deepEqual(mustaches[0][1], []);
  equal(mustaches[1][0], "second");
  deepEqual(mustaches[1][1], []);
  equal(mustaches[2][0], "third");
  deepEqual(mustaches[2][1], []);

  mustaches[0][2].placeholder.appendText('A');
  mustaches[1][2].placeholder.appendText('B');
  mustaches[2][2].placeholder.appendText('C');

  equalHTML(fragment, "A
B
C");
});

// TODO move test to AST
test('test auto insertion of text nodes between blocks and mustaches', function () {
  var ast = preprocess("{{one}}{{two}}{{#three}}{{/three}}{{#four}}{{/four}}{{five}}");
  // "" {{one}} "" {{two}} "" {{#three}}{{/three}} "" {{#four}}{{/four}} "" {{five}} ""
  equal(ast.length, 11);
  equal(ast[0], '');
  equal(ast[2], '');
  equal(ast[4], '');
  equal(ast[6], '');
  equal(ast[8], '');
  equal(ast[10], '');
});
<|endoftext|>


<commit_before>import proxyquire from 'proxyquire';
import Q from 'q';

describe('ResourceAction', () => {
  let ResourceAction;
  let stubs;

  beforeEach(() => {
    var stubFunction = function () { return stubs.superagent; };
    stubs = {
      superagent: {
        get: stubFunction,
        put: stubFunction,
        set: stubFunction,
        accept: stubFunction,
        end: stubFunction,
        clearTimeout: stubFunction
      }
    };

    ResourceAction = proxyquire('../../src/ResourceAction', stubs);
  });

  describe('superagent request is made', () => {
    let result;
    let getSpy;
    let endSpy;

    const url = 'http://example.com/posts/';
    beforeEach(() => {
      spy(stubs.superagent, 'get');
      spy(stubs.superagent, 'end');
      let resource = new ResourceAction(url, {}, {method: 'GET'});
      result = resource.makeRequest();
    });

    it('should have called get with url', () => {
      expect(stubs.superagent.get.calledWith(url)).to.be.true;
    });
    it('should have called end', () => {
      expect(stubs.superagent.end.called).to.be.true;
    });
  });
});
<commit_msg>Another test<commit_after>import proxyquire from 'proxyquire';
import Q from 'q';

describe('ResourceAction', () => {
  let ResourceAction;
  let stubs;

  beforeEach(() => {
    var stubFunction = function () { return stubs.superagent; };
    stubs = {
      superagent: {
        get: stubFunction,
        put: stubFunction,
        set: stubFunction,
        send: stubFunction,
        query: stubFunction,
        accept: stubFunction,
        end: stubFunction,
        clearTimeout: stubFunction
      }
    };

    ResourceAction = proxyquire('../../src/ResourceAction', stubs);
  });

  describe('get request with no data', () => {
    let result;
    let getSpy;
    let endSpy;

    const url = 'http://example.com/posts/';
    beforeEach(() => {
      spy(stubs.superagent, 'get');
      spy(stubs.superagent, 'end');
      spy(stubs.superagent, 'query');
      spy(stubs.superagent, 'send');
      let resource = new ResourceAction(url, {}, {method: 'GET'});
      result = resource.makeRequest();
    });

    it('should have called get with url', () => {
      expect(stubs.superagent.get.calledWith(url)).to.be.true;
    });
    it('should have called end', () => {
      expect(stubs.superagent.end.called).to.be.true;
    });
    it('should not have called query or send', () => {
      expect(stubs.superagent.query.called).to.be.false;
      expect(stubs.superagent.send.called).to.be.false;
    });
  });
});
<|endoftext|>


<commit_before>describe('Marionette.Toolkit.Component', function() {
  beforeEach(function() {
    this.setFixtures('

');
    this.el = Backbone.$('#testRegion');
    this.myRegion = new Backbone.Marionette.Region({
      el: this.el
    });
  });

  // SHOWING A VIEW
  describe('when showing a component', function() {
    beforeEach(function() {
      this.beforeShowStub = this.sinon.stub();
      this.showStub = this.sinon.stub();
      this.MyViewClass = Marionette.View.extend({});
      this.MyComponent = Marionette.Toolkit.Component.extend({
        viewOptions: {
          template: _.template('

')
        },
        ViewClass: this.MyViewClass
      });
      this.myComponent = new this.MyComponent();
      this.myComponent.on('before:show', this.beforeShowStub, function() {});
      this.myComponent.on('show', this.showStub, function() {});
    });

    describe('in a specified region "showIn()"', function() {
      it('should show the component', function() {
        this.myComponent.showIn(this.myRegion);
        expect(this.myComponent._isShown).to.equal(true);
      });

      it('should fire the before:show methods', function() {
        this.myComponent.showIn(this.myRegion);
        expect(this.beforeShowStub).to.have.been.calledOnce;
      });

      it('should fire the show methods', function() {
        this.myComponent.showIn(this.myRegion);
        expect(this.showStub).to.have.been.calledOnce;
      });

      it('should throw a "no defined region" error when no region is defined', function() {
        expect(_.bind(function() {
          this.myComponent.showIn();
        }, this)).to.throw('Component has no defined region.');
      });

      it('should throw a "already been shown" error if component has been shown', function() {
        this.myComponent.showIn(this.myRegion);
        expect(_.bind(function() {
          this.myComponent.showIn(this.myRegion);
        }, this)).to.throw('Component has already been shown in a region.');
      });
    });

    describe('in a region on the component definition "show()"', function() {
      it('should show the component', function() {
        this.ShowComponent = this.MyComponent.extend({
          region: this.myRegion
        });
        this.showComponent = new this.ShowComponent();
        this.showComponent.show({
          className: 'my-component-class'
        });
        expect(this.showComponent._isShown).to.equal(true);
      });
    });
  });

  // RENDERING A VIEW WITH renderView()
  describe('when rendering a view', function() {
    beforeEach(function() {
      this.beforeRenderStub = this.sinon.stub();
      this.renderStub = this.sinon.stub();
      this.MyViewClass = Marionette.View;
      this.MyComponent = Marionette.Toolkit.Component.extend({
        region: this.myRegion,
        ViewClass: this.MyViewClass,
        viewOptions: {
          template: _.template('

')
        }
      });
      this.myComponent = new this.MyComponent();
      this.myComponent.on('before:render:view', this.beforeRenderStub, function() {});
      this.myComponent.on('render:view', this.renderStub, function() {});
    });

    it('should fire the before:render:view methods', function() {
      this.myComponent.renderView({
        className: 'other-component-class'
      });
      expect(this.beforeRenderStub).to.have.been.calledOnce;
    });

    it('should fire the render:view methods', function() {
      this.myComponent.renderView({
        className: 'other-component-class'
      });
      expect(this.renderStub).to.have.been.calledOnce;
    });

    describe('and checking the currentView', function() {
      it('should have the correct className on currentView', function() {
        this.myComponent.renderView({
          className: 'my-component-class'
        });
        expect(this.myComponent.currentView.className).to.equal('my-component-class');
      });
    });

    describe('with a defined ViewClass', function() {
      it('should return the correct ViewClass', function() {
        this.myComponent.renderView();
        const test = this.myComponent.currentView;
        expect(test).to.be.instanceof(this.MyViewClass);
      });
    });

    // The test for mixinOptions()
    describe('with additional options passed in', function() {
      it('should put the options on currentView', function() {
        this.myComponent.renderView({
          foo: 'bar'
        });
        expect(this.myComponent.currentView.options.foo).to.equal('bar');
      });
    });
  });

  // SETTING ViewClass
  describe('when defining ViewClass as a function that returns a view class', function() {
    beforeEach(function() {
      this.MyComponent = Marionette.Toolkit.Component.extend({
        region: this.myRegion,
        ViewClass: function(options) {
          if(options.foo) {
            return Marionette.View.extend({
              customViewOption: 'bar',
              template: _.template('

')
            });
          }
          return Marionette.View;
        }
      });
      this.myComponent = new this.MyComponent();

      this.myComponent.show({ foo: true });
    });

    it('should use the correct view class for passed options', function() {
      expect(this.myComponent.currentView.getOption('customViewOption')).to.equal('bar');
    });
  });

  describe('when defining ViewClass as neither a function or a class', function() {
    beforeEach(function() {
      this.MyComponent = Marionette.Toolkit.Component.extend({
        region: this.myRegion,
        ViewClass: 'Invalid View'
      });
      this.myComponent = new this.MyComponent();
    });

    it('should throw an error saying the ViewClass is invalid', function() {
      expect(_.bind(this.myComponent.show, this.myComponent)).to.throw('"ViewClass" must be a view class or a function that returns a view class');
    });
  });

  // INSTANTIATING A COMPONENT WITH OPTIONS
  describe('when instantiating a component', function() {
    describe('with state options', function() {
      it('should initialize stateModel with passed in state', function() {
        this.MyComponent = Marionette.Toolkit.Component.extend();

        this.myComponent = new this.MyComponent({
          state: {
            foo: 'bar'
          }
        });

        expect(this.myComponent.getState('foo')).to.equal('bar');
      });
    });

    describe('with a customized viewEventPrefix', function() {
      it('should trigger the correct action as defined', function() {
        this.MyComponent = Marionette.Toolkit.Component.extend({
          viewEventPrefix: 'some:prefix',
          viewOptions: {
            template: false
          },
          testRender: false
        });
        this.myComponent = new this.MyComponent({});

        this.myComponent.showIn(this.myRegion);
        this.myComponent.on('some:prefix:render', function() {
          this.testRender = true;
        });
        this.myComponent.currentView.render();

        expect(this.myComponent.testRender).to.equal(true);
      });
    });

    describe('with defined viewOptions', function() {
      beforeEach(function() {
        this.MyView = Marionette.View.extend({
          initialize: function(options) {
            this.test = options.foo;
          }
        });
      });

      describe('on the view instance', function() {
        it('should do what...', function() {
          this.MyComponent = Marionette.Toolkit.Component.extend({
            ViewClass: this.MyView,
            region: this.myRegion,
            viewOptions: {
              foo: 'bar1',
              template: false
            }
          });
          this.myComponent = new this.MyComponent();
          this.myComponent.renderView();
          expect(this.myComponent.currentView.test).to.equal('bar1');
        });
      });

      describe('as specified as a function', function() {
        it('should do what...', function() {
          this.MyComponent = Marionette.Toolkit.Component.extend({
            ViewClass: this.MyView,
            region: this.myRegion,
            viewOptions: {
              foo: 'bar2',
              template: false
            }
          });
          this.myComponent = new this.MyComponent();
          this.myComponent.renderView();
          expect(this.myComponent.currentView.test).to.equal('bar2');
        });
      });
    });
  });

  // DESTROYING COMPONENTS
  describe('when destroying a component', function() {
    describe('with a defined region', function() {
      it('should be destroyed and region emptied', function() {
        this.MyComponent = Marionette.Toolkit.Component.extend({
          region: this.myRegion
        });
        this.myComponent = new this.MyComponent();
        this.myComponent.destroy();
      });
    });

    describe('without a defined region', function() {
      it('should be destroyed', function() {
        this.myComponent = new Marionette.Toolkit.Component();
        this.myComponent.destroy();
      });
    });

    describe('by showing a new view in the region', function() {
      beforeEach(function() {
        this.destroyEvent = this.sinon.stub();
        this.MyComponent = Marionette.Toolkit.Component.extend({
          viewOptions: {
            template: false
          }
        });
        this.myComponent = new this.MyComponent();
        this.myComponent.on('destroy', this.destroyEvent);
        this.myComponent.showIn(this.myRegion);
      });

      it('should trigger a destroy event on the component', function() {
        this.myRegion.show(new Marionette.View({
          template: false
        }));
        expect(this.destroyEvent).to.have.been.calledOnce;
      });

      it('should not trigger a destroy event on rendering a view after show', function() {
        this.myComponent.renderView();
        expect(this.destroyEvent).to.have.not.been.called;
      });
    });
  });
});
<commit_msg>Add tests for `getRegion`<commit_after>describe('Marionette.Toolkit.Component', function() {
  beforeEach(function() {
    this.setFixtures('

');
    this.el = Backbone.$('#testRegion');
    this.myRegion = new Backbone.Marionette.Region({
      el: this.el
    });
  });

  // SHOWING A VIEW
  describe('when showing a component', function() {
    beforeEach(function() {
      this.beforeShowStub = this.sinon.stub();
      this.showStub = this.sinon.stub();
      this.MyViewClass = Marionette.View.extend({});
      this.MyComponent = Marionette.Toolkit.Component.extend({
        viewOptions: {
          template: _.template('

')
        },
        ViewClass: this.MyViewClass
      });
      this.myComponent = new this.MyComponent();
      this.myComponent.on('before:show', this.beforeShowStub, function() {});
      this.myComponent.on('show', this.showStub, function() {});
    });

    describe('in a specified region "showIn()"', function() {
      it('should show the component', function() {
        this.myComponent.showIn(this.myRegion);
        expect(this.myComponent._isShown).to.equal(true);
      });

      it('should fire the before:show methods', function() {
        this.myComponent.showIn(this.myRegion);
        expect(this.beforeShowStub).to.have.been.calledOnce;
      });

      it('should fire the show methods', function() {
        this.myComponent.showIn(this.myRegion);
        expect(this.showStub).to.have.been.calledOnce;
      });

      it('should throw a "no defined region" error when no region is defined', function() {
        expect(_.bind(function() {
          this.myComponent.showIn();
        }, this)).to.throw('Component has no defined region.');
      });

      it('should throw a "already been shown" error if component has been shown', function() {
        this.myComponent.showIn(this.myRegion);
        expect(_.bind(function() {
          this.myComponent.showIn(this.myRegion);
        }, this)).to.throw('Component has already been shown in a region.');
      });
    });

    describe('in a region on the component definition "show()"', function() {
      it('should show the component', function() {
        this.ShowComponent = this.MyComponent.extend({
          region: this.myRegion
        });
        this.showComponent = new this.ShowComponent();
        this.showComponent.show({
          className: 'my-component-class'
        });
        expect(this.showComponent._isShown).to.equal(true);
      });
    });
  });

  // RETRIVING A COMPONENT'S region
  describe('when retriving a component\'s region', function() {
    beforeEach(function() {
      this.renderStub = this.sinon.stub();
      this.MyViewClass = Marionette.View;
      this.MyComponent = Marionette.Toolkit.Component.extend({
        region: this.myRegion,
        ViewClass: this.MyViewClass,
        viewOptions: {
          template: _.template('

')
        }
      });
      this.myComponent = new this.MyComponent();
    });

    it('should return component region', function() {
      expect(this.myComponent.getRegion()).to.deep.eq(this.myRegion);
    });
  });

  // RENDERING A VIEW WITH renderView()
  describe('when rendering a view', function() {
    beforeEach(function() {
      this.beforeRenderStub = this.sinon.stub();
      this.renderStub = this.sinon.stub();
      this.MyViewClass = Marionette.View;
      this.MyComponent = Marionette.Toolkit.Component.extend({
        region: this.myRegion,
        ViewClass: this.MyViewClass,
        viewOptions: {
          template: _.template('

')
        }
      });
      this.myComponent = new this.MyComponent();
      this.myComponent.on('before:render:view', this.beforeRenderStub, function() {});
      this.myComponent.on('render:view', this.renderStub, function() {});
    });

    it('should fire the before:render:view methods', function() {
      this.myComponent.renderView({
        className: 'other-component-class'
      });
      expect(this.beforeRenderStub).to.have.been.calledOnce;
    });

    it('should fire the render:view methods', function() {
      this.myComponent.renderView({
        className: 'other-component-class'
      });
      expect(this.renderStub).to.have.been.calledOnce;
    });

    describe('and checking the currentView', function() {
      it('should have the correct className on currentView', function() {
        this.myComponent.renderView({
          className: 'my-component-class'
        });
        expect(this.myComponent.currentView.className).to.equal('my-component-class');
      });
    });

    describe('with a defined ViewClass', function() {
      it('should return the correct ViewClass', function() {
        this.myComponent.renderView();
        const test = this.myComponent.currentView;
        expect(test).to.be.instanceof(this.MyViewClass);
      });
    });

    // The test for mixinOptions()
    describe('with additional options passed in', function() {
      it('should put the options on currentView', function() {
        this.myComponent.renderView({
          foo: 'bar'
        });
        expect(this.myComponent.currentView.options.foo).to.equal('bar');
      });
    });
  });

  // SETTING ViewClass
  describe('when defining ViewClass as a function that returns a view class', function() {
    beforeEach(function() {
      this.MyComponent = Marionette.Toolkit.Component.extend({
        region: this.myRegion,
        ViewClass: function(options) {
          if(options.foo) {
            return Marionette.View.extend({
              customViewOption: 'bar',
              template: _.template('

')
            });
          }
          return Marionette.View;
        }
      });
      this.myComponent = new this.MyComponent();

      this.myComponent.show({ foo: true });
    });

    it('should use the correct view class for passed options', function() {
      expect(this.myComponent.currentView.getOption('customViewOption')).to.equal('bar');
    });
  });

  describe('when defining ViewClass as neither a function or a class', function() {
    beforeEach(function() {
      this.MyComponent = Marionette.Toolkit.Component.extend({
        region: this.myRegion,
        ViewClass: 'Invalid View'
      });
      this.myComponent = new this.MyComponent();
    });

    it('should throw an error saying the ViewClass is invalid', function() {
      expect(_.bind(this.myComponent.show, this.myComponent)).to.throw('"ViewClass" must be a view class or a function that returns a view class');
    });
  });

  // INSTANTIATING A COMPONENT WITH OPTIONS
  describe('when instantiating a component', function() {
    describe('with state options', function() {
      it('should initialize stateModel with passed in state', function() {
        this.MyComponent = Marionette.Toolkit.Component.extend();

        this.myComponent = new this.MyComponent({
          state: {
            foo: 'bar'
          }
        });

        expect(this.myComponent.getState('foo')).to.equal('bar');
      });
    });

    describe('with a customized viewEventPrefix', function() {
      it('should trigger the correct action as defined', function() {
        this.MyComponent = Marionette.Toolkit.Component.extend({
          viewEventPrefix: 'some:prefix',
          viewOptions: {
            template: false
          },
          testRender: false
        });
        this.myComponent = new this.MyComponent({});

        this.myComponent.showIn(this.myRegion);
        this.myComponent.on('some:prefix:render', function() {
          this.testRender = true;
        });
        this.myComponent.currentView.render();

        expect(this.myComponent.testRender).to.equal(true);
      });
    });

    describe('with defined viewOptions', function() {
      beforeEach(function() {
        this.MyView = Marionette.View.extend({
          initialize: function(options) {
            this.test = options.foo;
          }
        });
      });

      describe('on the view instance', function() {
        it('should do what...', function() {
          this.MyComponent = Marionette.Toolkit.Component.extend({
            ViewClass: this.MyView,
            region: this.myRegion,
            viewOptions: {
              foo: 'bar1',
              template: false
            }
          });
          this.myComponent = new this.MyComponent();
          this.myComponent.renderView();
          expect(this.myComponent.currentView.test).to.equal('bar1');
        });
      });

      describe('as specified as a function', function() {
        it('should do what...', function() {
          this.MyComponent = Marionette.Toolkit.Component.extend({
            ViewClass: this.MyView,
            region: this.myRegion,
            viewOptions: {
              foo: 'bar2',
              template: false
            }
          });
          this.myComponent = new this.MyComponent();
          this.myComponent.renderView();
          expect(this.myComponent.currentView.test).to.equal('bar2');
        });
      });
    });
  });

  // DESTROYING COMPONENTS
  describe('when destroying a component', function() {
    describe('with a defined region', function() {
      it('should be destroyed and region emptied', function() {
        this.MyComponent = Marionette.Toolkit.Component.extend({
          region: this.myRegion
        });
        this.myComponent = new this.MyComponent();
        this.myComponent.destroy();
      });
    });

    describe('without a defined region', function() {
      it('should be destroyed', function() {
        this.myComponent = new Marionette.Toolkit.Component();
        this.myComponent.destroy();
      });
    });

    describe('by showing a new view in the region', function() {
      beforeEach(function() {
        this.destroyEvent = this.sinon.stub();
        this.MyComponent = Marionette.Toolkit.Component.extend({
          viewOptions: {
            template: false
          }
        });
        this.myComponent = new this.MyComponent();
        this.myComponent.on('destroy', this.destroyEvent);
        this.myComponent.showIn(this.myRegion);
      });

      it('should trigger a destroy event on the component', function() {
        this.myRegion.show(new Marionette.View({
          template: false
        }));
        expect(this.destroyEvent).to.have.been.calledOnce;
      });

      it('should not trigger a destroy event on rendering a view after show', function() {
        this.myComponent.renderView();
        expect(this.destroyEvent).to.have.not.been.called;
      });
    });
  });
});
<|endoftext|>


<commit_before>import '../../../src/index';
import create from '../../lib/create';

describe('light/polyfill', function () {
  let host, light1, light2, root, slot, text;

  beforeEach(function () {
    slot = create('slot');
    host = create('div');
    root = host.attachShadow({ mode: 'closed' });

    root.appendChild(slot);

    light1 = create('light1');
    light2 = create('light2');
    text = document.createTextNode('text');

    host.appendChild(light1);
    host.appendChild(text);
    host.appendChild(light2);
  });

  it('assignedSlot', function () {
    expect(light1.assignedSlot).to.equal(slot);
  });

  it('parentElement', function () {
    expect(light1.parentElement).to.equal(host);
  });

  it('parentNode', function () {
    expect(light1.parentNode).to.equal(host);
  });

  it('nextSibling', function () {
    expect(light1.nextSibling).to.equal(text);
  });

  it('nextElementSibling', function () {
    expect(light1.nextElementSibling).to.equal(light2);
  });

  it('previousSibling', function () {
    expect(light2.previousSibling).to.equal(text);
  });

  it('previousElementSibling', function () {
    expect(light2.previousElementSibling).to.equal(light1);
  });

  describe('when removed', function () {
    let anotherHost, anotherNode, anotherRoot, anotherSlot;

    beforeEach(function () {
      anotherHost = create('div');
      anotherNode = create('div');
      anotherRoot = anotherHost.attachShadow({ mode: 'closed' });
      anotherSlot = create('slot');

      anotherRoot.appendChild(anotherSlot);
      host.removeChild(light1);
    });

    it('should null parentNode', function () {
      expect(light1.parentNode).to.equal(null);
    });

    it('should null assignedSlot', function () {
      expect(light1.assignedSlot).to.equal(null);
    });

    describe('and reparented to the same host', function () {
      beforeEach(function () {
        host.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(host);
      });

      it('should keep assignedSlot null', function () {
        expect(light1.assignedSlot).to.equal(slot);
      });
    });

    describe('and reparented to a different host', function () {
      beforeEach(function () {
        anotherHost.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(anotherHost);
      });

      it('should keep assignedSlot null', function () {
        expect(light1.assignedSlot).to.equal(anotherSlot);
      });
    });

    describe('and reparented to a different node', function () {
      beforeEach(function () {
        anotherNode.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(anotherNode);
      });

      it('should keep assignedSlot null', function () {
        expect(light1.assignedSlot).to.equal(null);
      });
    });
  });

  describe('when directly reparented', function () {
    let anotherHost, anotherNode, anotherRoot, anotherSlot;

    beforeEach(function () {
      anotherHost = create('div');
      anotherNode = create('div');
      anotherRoot = anotherHost.attachShadow({ mode: 'closed' });
      anotherSlot = create('slot');

      anotherRoot.appendChild(anotherSlot);
    });

    describe('to the same host', function () {
      beforeEach(function () {
        host.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(host);
      });

      it('should reset assignedSlot', function () {
        expect(light1.assignedSlot).to.equal(slot);
      });
    });

    describe('to a different host', function () {
      beforeEach(function () {
        anotherHost.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(anotherHost);
      });

      it('should reset assignedSlot', function () {
        expect(light1.assignedSlot).to.equal(anotherSlot);
      });
    });

    describe('to a different node', function () {
      beforeEach(function () {
        anotherNode.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(anotherNode);
      });

      it('should reset assignedSlot', function () {
        expect(anotherNode.assignedSlot).to.equal(null);
      });
    });
  });

  describe('when text nodes are projected to a different spot than element nodes', function () {
    let host, light1, light2, root, namedSlot, text;

    beforeEach(function () {
      namedSlot = create('slot', {name: 'mySlot'});
      unnamedSlot = create('slot');
      host = create('div');
      root = host.attachShadow({ mode: 'closed' });

      root.appendChild(namedSlot);
      root.appendChild(unnamedSlot);

      light1 = create('div', {slot: 'mySlot'});
      light2 = create('div', {slot: 'mySlot'});
      text = document.createTextNode('text');

      host.appendChild(light1);
      host.appendChild(text);
      host.appendChild(light2);
    });

    it('should polyfill previousSibling of textNode', function () {
      expect(text.previousSibling).to.equal(light1);
    });

    it('should polyfill nextSibling of textNode', function () {
      expect(text.nextSibling).to.equal(light2);
    });

    it('should NOT polyfill textContent of textNode', function () {
      expect(text.textContent).to.equal('text');
      expect(text.__proto__.hasOwnProperty('textContent')).to.be.false;
      expect(text.__proto__.hasOwnProperty('__textContent')).to.be.false;
    });
  });
});
<commit_msg>Added unnamedSlot variable declaration (picked up by linter)<commit_after>import '../../../src/index';
import create from '../../lib/create';

describe('light/polyfill', function () {
  let host, light1, light2, root, slot, text;

  beforeEach(function () {
    slot = create('slot');
    host = create('div');
    root = host.attachShadow({ mode: 'closed' });

    root.appendChild(slot);

    light1 = create('light1');
    light2 = create('light2');
    text = document.createTextNode('text');

    host.appendChild(light1);
    host.appendChild(text);
    host.appendChild(light2);
  });

  it('assignedSlot', function () {
    expect(light1.assignedSlot).to.equal(slot);
  });

  it('parentElement', function () {
    expect(light1.parentElement).to.equal(host);
  });

  it('parentNode', function () {
    expect(light1.parentNode).to.equal(host);
  });

  it('nextSibling', function () {
    expect(light1.nextSibling).to.equal(text);
  });

  it('nextElementSibling', function () {
    expect(light1.nextElementSibling).to.equal(light2);
  });

  it('previousSibling', function () {
    expect(light2.previousSibling).to.equal(text);
  });

  it('previousElementSibling', function () {
    expect(light2.previousElementSibling).to.equal(light1);
  });

  describe('when removed', function () {
    let anotherHost, anotherNode, anotherRoot, anotherSlot;

    beforeEach(function () {
      anotherHost = create('div');
      anotherNode = create('div');
      anotherRoot = anotherHost.attachShadow({ mode: 'closed' });
      anotherSlot = create('slot');

      anotherRoot.appendChild(anotherSlot);
      host.removeChild(light1);
    });

    it('should null parentNode', function () {
      expect(light1.parentNode).to.equal(null);
    });

    it('should null assignedSlot', function () {
      expect(light1.assignedSlot).to.equal(null);
    });

    describe('and reparented to the same host', function () {
      beforeEach(function () {
        host.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(host);
      });

      it('should keep assignedSlot null', function () {
        expect(light1.assignedSlot).to.equal(slot);
      });
    });

    describe('and reparented to a different host', function () {
      beforeEach(function () {
        anotherHost.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(anotherHost);
      });

      it('should keep assignedSlot null', function () {
        expect(light1.assignedSlot).to.equal(anotherSlot);
      });
    });

    describe('and reparented to a different node', function () {
      beforeEach(function () {
        anotherNode.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(anotherNode);
      });

      it('should keep assignedSlot null', function () {
        expect(light1.assignedSlot).to.equal(null);
      });
    });
  });

  describe('when directly reparented', function () {
    let anotherHost, anotherNode, anotherRoot, anotherSlot;

    beforeEach(function () {
      anotherHost = create('div');
      anotherNode = create('div');
      anotherRoot = anotherHost.attachShadow({ mode: 'closed' });
      anotherSlot = create('slot');

      anotherRoot.appendChild(anotherSlot);
    });

    describe('to the same host', function () {
      beforeEach(function () {
        host.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(host);
      });

      it('should reset assignedSlot', function () {
        expect(light1.assignedSlot).to.equal(slot);
      });
    });

    describe('to a different host', function () {
      beforeEach(function () {
        anotherHost.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(anotherHost);
      });

      it('should reset assignedSlot', function () {
        expect(light1.assignedSlot).to.equal(anotherSlot);
      });
    });

    describe('to a different node', function () {
      beforeEach(function () {
        anotherNode.appendChild(light1);
      });

      it('should reset parentNode', function () {
        expect(light1.parentNode).to.equal(anotherNode);
      });

      it('should reset assignedSlot', function () {
        expect(anotherNode.assignedSlot).to.equal(null);
      });
    });
  });

  describe('when text nodes are projected to a different spot than element nodes', function () {
    let host, light1, light2, root, namedSlot, unnamedSlot, text;

    beforeEach(function () {
      namedSlot = create('slot', {name: 'mySlot'});
      unnamedSlot = create('slot');
      host = create('div');
      root = host.attachShadow({ mode: 'closed' });

      root.appendChild(namedSlot);
      root.appendChild(unnamedSlot);

      light1 = create('div', {slot: 'mySlot'});
      light2 = create('div', {slot: 'mySlot'});
      text = document.createTextNode('text');

      host.appendChild(light1);
      host.appendChild(text);
      host.appendChild(light2);
    });

    it('should polyfill previousSibling of textNode', function () {
      expect(text.previousSibling).to.equal(light1);
    });

    it('should polyfill nextSibling of textNode', function () {
      expect(text.nextSibling).to.equal(light2);
    });

    it('should NOT polyfill textContent of textNode', function () {
      expect(text.textContent).to.equal('text');
      expect(text.__proto__.hasOwnProperty('textContent')).to.be.false;
      expect(text.__proto__.hasOwnProperty('__textContent')).to.be.false;
    });
  });
});
<|endoftext|>


<commit_before>import Ember from 'ember'
const {
  typeOf
} = Ember
import PropTypes, {validators} from '../utils/prop-types'
import config from 'ember-get-config'

const helpers = {
  /* eslint-disable complexity */
  validateProperty (ctx, name, def) {
    const value = ctx.get(name)

    if (value === undefined) {
      if (!def.required) {
        return
      }

      Ember.Logger.warn(`Missing required property ${name}`)

      return
    }

    if (def.type in validators) {
      validators[def.type](ctx, name, value, def, true)
    } else {
      Ember.Logger.warn(`Unknown propType ${def.type}`)
    }
  },
  /* eslint-enable complexity */

  validatePropTypes (ctx) {
    if (!config || config.environment === 'production') {
      return
    }

    const propTypes = ctx.get('propTypes')

    if (!propTypes) {
      return
    }

    Object.keys(propTypes).forEach(name => {
      const def = propTypes[name]

      if (def === undefined) {
        Ember.Logger.warn(`propType for ${name} is unknown`)
        return
      }

      helpers.validateProperty(ctx, name, def)
    })
  }
}

export default Ember.Mixin.create({
  init () {
    helpers.validatePropTypes(this)

    if (typeOf(this.getDefaultProps) === 'function') {
      const presentPropKeys = Object.keys(this)
      const defaultProps = this.getDefaultProps()

      const needsDefaultProp = Object.assign({}, ...(Object.keys(defaultProps).forEach((key) => {
        if (!presentPropKeys.hasOwnProperty(key)) {
          return {
            [key]: defaultProps[key]
          }
        }
      })))

      this.setProperties(needsDefaultProp)
    }

    this._super()
  }
})

export {helpers, PropTypes}
<commit_msg>Removing Object.assign<commit_after>import Ember from 'ember'
const {
  assign,
  typeOf
} = Ember
import PropTypes, {validators} from '../utils/prop-types'
import config from 'ember-get-config'

const helpers = {
  /* eslint-disable complexity */
  validateProperty (ctx, name, def) {
    const value = ctx.get(name)

    if (value === undefined) {
      if (!def.required) {
        return
      }

      Ember.Logger.warn(`Missing required property ${name}`)

      return
    }

    if (def.type in validators) {
      validators[def.type](ctx, name, value, def, true)
    } else {
      Ember.Logger.warn(`Unknown propType ${def.type}`)
    }
  },
  /* eslint-enable complexity */

  validatePropTypes (ctx) {
    if (!config || config.environment === 'production') {
      return
    }

    const propTypes = ctx.get('propTypes')

    if (!propTypes) {
      return
    }

    Object.keys(propTypes).forEach(name => {
      const def = propTypes[name]

      if (def === undefined) {
        Ember.Logger.warn(`propType for ${name} is unknown`)
        return
      }

      helpers.validateProperty(ctx, name, def)
    })
  }
}

export default Ember.Mixin.create({
  init () {
    helpers.validatePropTypes(this)

    if (typeOf(this.getDefaultProps) === 'function') {
      const presentPropKeys = Object.keys(this)
      const defaultProps = this.getDefaultProps()

      let needsDefaultProp = {}
      Object.keys(defaultProps).forEach((key) => {
        if (!presentPropKeys.hasOwnProperty(key)) {
          needsDefaultProp[key] = defaultProps[key]
        }
      })

      this.setProperties(needsDefaultProp)
    }

    this._super()
  }
})

export {helpers, PropTypes}
<|endoftext|>


<commit_before>/*
   Copyright 2013 Callan Bryant <callan.bryant@gmail.com>

   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.
*/

// article (circular) queue actors.
var crypto = require('crypto')

exports.internal = function(params) {return new internal(params)}
exports.redis    = function(params) {return new redis(params)}

// native, non-persistent, may be slow compared to redis
// relies on garbage collector, don't overuse
var internal = function (params) {
	if (typeof params == 'undefined')
		params = {}

	// max number or articles in this queue
	var max = params.max || 999;

	// current array index of article
	var index = 0;

	// array of articles
	var articles = []

	// add an Article to the queue, creating id: as hash if not there
	this.enqueue = function(article) {
		if (!article.id)
			article.id = articleHash(article)

		// check is unique
		for (var i in articles)
			if (articles[i].id == article.id)
				return false

		// stop next() from returning a dupe
		// index must correspond to the same article
		if (articles.length)
			index++

		// add new article to start of array
		articles.unshift(article)

		if (articles.length > max)
			articles.pop()

		return true
	}

	// return an article from the (circular) queue
	// undefined if no items
	this.next = function() {
		if (articles[++index])
			return articles[index]
		else
			return articles[index = 0]
	}

	// return the current article without advancing the index
	this.current = function() {
		return articles[index]
	}

	// remove an article from the queue, preserving the order
	this.discard = function(id){
		// look for the article index, given the ID
		// 'i' is set to invalid index if not found
		for (var i=0; i <= articles.length; i++)
			if (i==articles.length  || articles[i].id == id)
				break;

		// repair index if affected
		if (i < index)
			index--

		// remove the article, returning success
		return !!articles.splice(i,1)[0]
	}

	// read an article from the queue, leaving it there
	this.get = function(id) {
		// look for the article index, given the ID
		// 'i' is set to invalid index if not found
		for (var i=0; i <= articles.length; i++)
			if (i==articles.length  || articles[i].id == id)
				break;

		return articles[i]
	}

	// number of articles in queue
	this.pending = function(){
		return articles.length
	}
}

// returns hex. hash of article
var articleHash = exports.articleHash = function(article) {
	var hash = crypto.createHash('md5')
	hash.update(article.title+article.guid+article.link)
	return hash.digest('hex')
}

<commit_msg>article queue is now FIFO/circular<commit_after>/*
   Copyright 2013 Callan Bryant <callan.bryant@gmail.com>

   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.
*/

// article (circular FIFO) queue actors.
var crypto = require('crypto')

exports.internal = function(params) {return new internal(params)}
exports.redis    = function(params) {return new redis(params)}

// native, non-persistent, may be slow compared to redis
// relies on garbage collector, don't overuse
var internal = function (params) {
	if (typeof params == 'undefined')
		params = {}

	// max number or articles in this queue
	var max = params.max || 999;

	// current array index of article
	var index = 0;

	// array of articles
	var articles = []

	// add an Article to the queue, creating id: as hash if not there
	// must appear next in queue!
	this.enqueue = function(article) {
		if (!article.id)
			article.id = articleHash(article)

		// check is unique
		for (var i in articles)
			if (articles[i].id == article.id)
				return false

		// add new article to index + 1, so it appears next
		articles.splice(i+1,0,article)

		if (articles.length > max)
			articles.pop()

		return true
	}

	// return an article from the (circular) queue
	// undefined if no items
	this.next = function() {
		if (articles[++index])
			return articles[index]
		else
			return articles[index = 0]
	}

	// return the current article without advancing the index
	this.current = function() {
		return articles[index]
	}

	// remove an article from the queue, preserving the order
	this.discard = function(id){
		// look for the article index, given the ID
		// 'i' is set to invalid index if not found
		for (var i=0; i <= articles.length; i++)
			if (i==articles.length  || articles[i].id == id)
				break;

		// repair index if affected
		if (i < index)
			index--

		// remove the article, returning success
		return !!articles.splice(i,1)[0]
	}

	// read an article from the queue, leaving it there
	this.get = function(id) {
		// look for the article index, given the ID
		// 'i' is set to invalid index if not found
		for (var i=0; i <= articles.length; i++)
			if (i==articles.length  || articles[i].id == id)
				break;

		return articles[i]
	}

	// number of articles in queue
	this.pending = function(){
		return articles.length
	}
}

// returns hex. hash of article
var articleHash = exports.articleHash = function(article) {
	var hash = crypto.createHash('md5')
	hash.update(article.title+article.guid+article.link)
	return hash.digest('hex')
}

<|endoftext|>