<commit_before>'use strict';
var assert = require('assert');
var React = require('react');
var ReactDOMServer = require('react-dom/server');
var R = require('ramda');

var Parser = require('..').Parser;
var ProcessNodeDefinitions = require('..').ProcessNodeDefinitions;

describe('Html2React', function () {
  var parser = new Parser();

  describe('parse valid HTML', function () {
    it('should return a valid HTML string', function () {
      var htmlInput = '
Does this work?
';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with nested elements', function () {
      var htmlInput = '

Heading

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with inline styles', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with empty inline styles', function () {
      var htmlInput = '

';
      var htmlExpected = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });

    it('should return a valid HTML string with data attributes', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with aria attributes', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with a class attribute', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with a react camelCase attribute', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should handle dashed attributes', function () {
      var input = '<form accept-charset="en"><svg viewBox="0 0 10 10"><text text-anchor="left">' +
        '</text><circle stroke="black" stroke-width="42"></circle></svg></form>';
      var reactComponent = parser.parse(input);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, input);
    });

    // FIXME: See lib/process-node-definitions.js -> processDefaultNode()
    it.skip('should return a valid HTML string with comments', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    // FIXME: If / when React implements HTML comments, this test can be removed
    it('should return a valid HTML string without comments', function () {
      var htmlInput = '

';
      var htmlExpected = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });

    it('should parse br elements without warnings', function () {
      var htmlInput = '

Line one
Line two
Line three

';
      var htmlExpected = '

Line one
Line two
Line three

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });

    it('should not generate children for br tags', function () {
      var htmlInput = '
';

      var reactComponent = parser.parse(htmlInput);
      assert.strictEqual((reactComponent.props.children || []).length, 0);
    });

    it('should parse void elements with all attributes and no warnings', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    // Covers issue #9
    it('should parse textarea elements', function () {
      var htmlInput = '<textarea></textarea>';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should generate keys for sequence items', function () {
      var htmlInput = '

Item 1

Item 2
<
';

      var reactComponent = parser.parse(htmlInput);

      var children = R.filter(function (c) {
        return R.has('key', c);
      }, R.flatten(reactComponent.props.children));
      var keys = R.map(function (child) {
        return child.key;
      }, children);
      assert.deepStrictEqual(keys, ['0', '1', ]);
    });

    it('should parse br elements without warnings', function () {
      var htmlInput = '

Line one
Line two
Line three

';
      var htmlExpected = '

Line one
Line two
Line three

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });

    it('should parse src elements with all attributes but without warnings', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should decode character entities in text nodes', function () {
      var htmlInput = '
1 < 2
';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should not generate children for childless elements', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);

      assert.strictEqual((reactComponent.props.children || []).length, 0);
    });

    it('should fill in the key name with boolean attribute', function () {
      var htmlInput = '<input type="checkbox" disabled required/>';
      var htmlExpected = '<input type="checkbox" disabled="" required=""/>';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });
  });

  describe('parse invalid HTML', function () {
    it('should throw an error when trying parsing multiple root elements', function () {
      var htmlInput = '

';

      assert.throws(function () {
        parser.parse(htmlInput);
      }, Error);
    });

    it('should throw an error with a specific message when parsing multiple root elements',
    function () {
      var htmlInput = '

';

      assert.throws(function () {
        parser.parse(htmlInput);
      }, /contains 3 root elements/);
    });

    it('should fix missing closing tags', function () {
      var htmlInput = '

';
      var htmlExpected = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });
  });

  describe('with custom processing instructions', function () {
    var parser = new Parser();
    var processNodeDefinitions = new ProcessNodeDefinitions(React);

    describe('parse valid HTML', function () {
      it('should return nothing with only a single
 element', function () {
        var htmlInput = '
Does this work?
';
        var isValidNode = function () {
          return true;
        };
        var processingInstructions = [{
          shouldProcessNode: function (node) {
            return node.name && node.name !== 'p';
          },
          processNode: processNodeDefinitions.processDefaultNode,
        },];
        var reactComponent = parser.parseWithInstructions(htmlInput, isValidNode,
          processingInstructions);

          // With only 1
 element, nothing is rendered
          assert.equal(reactComponent, false);
      });

      it('should return a single
 element within a div of
 and
 as siblings',
          function () {
        var htmlInput = '

Title

Paragraph

';
        var htmlExpected = '

Title

';

        var isValidNode = function () {
          return true;
        };

        var processingInstructions = [{
          shouldProcessNode: function (node) {
            return node.type === 'text' || node.name !== 'p';
          },
          processNode: processNodeDefinitions.processDefaultNode,
        },];
        var reactComponent = parser.parseWithInstructions(htmlInput, isValidNode,
          processingInstructions);
        var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);
        assert.equal(reactHtml, htmlExpected);
      });

      it('should replace the children of an element', function () {
        var htmlInput = '

Text

Text

';
        var htmlExpected = '

Heading

';

        var isValidNode = function () {
          return true;
        };

        var processingInstructions = [
          {
            replaceChildren: true,
            shouldProcessNode: function (node) {
              return node.attribs && node.attribs['data-test'] === 'foo';
            },
            processNode: function (node, children, index) {
              return React.createElement('h1', {key: index,}, 'Heading');
            },
          },
          {
            // Anything else
            shouldProcessNode: function (node) {
              return true;
            },
            processNode: processNodeDefinitions.processDefaultNode,
          },
        ];

        var reactComponent = parser.parseWithInstructions(htmlInput, isValidNode,
          processingInstructions);
        var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);
        assert.equal(reactHtml, htmlExpected);
      });

      it('should return capitalized content for all
 elements', function () {
        var htmlInput = '

Title

Paragraph
' +
        '
Another title

';
        var htmlExpected = '

TITLE

Paragraph
' +
        '
ANOTHER TITLE

';

        var isValidNode = function () {
          return true;
        };

        var processingInstructions = [
          {
            // Custom
 processing
            shouldProcessNode: function (node) {
              return node.parent && node.parent.name &&
              node.parent.name === 'h1';
            },
            processNode: function (node, children) {
              return node.data.toUpperCase();
            },
          }, {
            // Anything else
            shouldProcessNode: function (node) {
              return true;
            },
            processNode: processNodeDefinitions.processDefaultNode,
          },
        ];
        var reactComponent = parser.parseWithInstructions(htmlInput, isValidNode,
          processingInstructions);
        var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);
        assert.equal(reactHtml, htmlExpected);
      });

      it('should return false in case of invalid node', function () {
        var htmlInput = '

';
        var processingInstructions = [{
          shouldProcessNode: function (node) { return true; },
          processNode: processNodeDefinitions.processDefaultNode,
        }, ];
        var reactComponent = parser.parseWithInstructions(htmlInput,
          function () { return false; }, processingInstructions);

        assert.equal(reactComponent, false);
      });

      it('should generate only valid children', function () {
        var htmlInput = '

';

        var processingInstructions = [{
          shouldProcessNode: function (node) { return true; },
          processNode: processNodeDefinitions.processDefaultNode,
        }, ];
        var reactComponent = parser.parseWithInstructions(htmlInput, function (node) {
          // skip whitespace text nodes to clean up children
          if (node.type === 'text') {
            return node.data.trim() !== '';
          }
          return true;
        }, processingInstructions);

        assert.equal(reactComponent.props.children.length, 2);
      });

      it('should not affect unhandled whitespace', function () {
        var htmlInput = '

';

        var reactComponent = parser.parse(htmlInput);

        assert.equal(reactComponent.props.children.length, 5);
      });
    });
  });

  describe('parse SVG', function () {
    it('should have correct attributes', function () {
      var svgInput = '<svg><image xlink:href="http://i.imgur.com/w7GCRPb.png" /></svg>';
      var reactComponent = parser.parse(svgInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert(/<image xlink:href="http:\/\/i.imgur.com\/w7GCRPb.png"/.test(reactHtml), reactHtml + ' has expected attributes');
    });
  });
});
<commit_msg>Make line shorter<commit_after>'use strict';
var assert = require('assert');
var React = require('react');
var ReactDOMServer = require('react-dom/server');
var R = require('ramda');

var Parser = require('..').Parser;
var ProcessNodeDefinitions = require('..').ProcessNodeDefinitions;

describe('Html2React', function () {
  var parser = new Parser();

  describe('parse valid HTML', function () {
    it('should return a valid HTML string', function () {
      var htmlInput = '
Does this work?
';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with nested elements', function () {
      var htmlInput = '

Heading

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with inline styles', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with empty inline styles', function () {
      var htmlInput = '

';
      var htmlExpected = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });

    it('should return a valid HTML string with data attributes', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with aria attributes', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with a class attribute', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should return a valid HTML string with a react camelCase attribute', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should handle dashed attributes', function () {
      var input = '<form accept-charset="en"><svg viewBox="0 0 10 10"><text text-anchor="left">' +
        '</text><circle stroke="black" stroke-width="42"></circle></svg></form>';
      var reactComponent = parser.parse(input);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, input);
    });

    // FIXME: See lib/process-node-definitions.js -> processDefaultNode()
    it.skip('should return a valid HTML string with comments', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    // FIXME: If / when React implements HTML comments, this test can be removed
    it('should return a valid HTML string without comments', function () {
      var htmlInput = '

';
      var htmlExpected = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });

    it('should parse br elements without warnings', function () {
      var htmlInput = '

Line one
Line two
Line three

';
      var htmlExpected = '

Line one
Line two
Line three

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });

    it('should not generate children for br tags', function () {
      var htmlInput = '
';

      var reactComponent = parser.parse(htmlInput);
      assert.strictEqual((reactComponent.props.children || []).length, 0);
    });

    it('should parse void elements with all attributes and no warnings', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    // Covers issue #9
    it('should parse textarea elements', function () {
      var htmlInput = '<textarea></textarea>';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should generate keys for sequence items', function () {
      var htmlInput = '

Item 1

Item 2
<
';

      var reactComponent = parser.parse(htmlInput);

      var children = R.filter(function (c) {
        return R.has('key', c);
      }, R.flatten(reactComponent.props.children));
      var keys = R.map(function (child) {
        return child.key;
      }, children);
      assert.deepStrictEqual(keys, ['0', '1', ]);
    });

    it('should parse br elements without warnings', function () {
      var htmlInput = '

Line one
Line two
Line three

';
      var htmlExpected = '

Line one
Line two
Line three

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });

    it('should parse src elements with all attributes but without warnings', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should decode character entities in text nodes', function () {
      var htmlInput = '
1 < 2
';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlInput);
    });

    it('should not generate children for childless elements', function () {
      var htmlInput = '

';

      var reactComponent = parser.parse(htmlInput);

      assert.strictEqual((reactComponent.props.children || []).length, 0);
    });

    it('should fill in the key name with boolean attribute', function () {
      var htmlInput = '<input type="checkbox" disabled required/>';
      var htmlExpected = '<input type="checkbox" disabled="" required=""/>';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });
  });

  describe('parse invalid HTML', function () {
    it('should throw an error when trying parsing multiple root elements', function () {
      var htmlInput = '

';

      assert.throws(function () {
        parser.parse(htmlInput);
      }, Error);
    });

    it('should throw an error with a specific message when parsing multiple root elements',
    function () {
      var htmlInput = '

';

      assert.throws(function () {
        parser.parse(htmlInput);
      }, /contains 3 root elements/);
    });

    it('should fix missing closing tags', function () {
      var htmlInput = '

';
      var htmlExpected = '

';

      var reactComponent = parser.parse(htmlInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert.equal(reactHtml, htmlExpected);
    });
  });

  describe('with custom processing instructions', function () {
    var parser = new Parser();
    var processNodeDefinitions = new ProcessNodeDefinitions(React);

    describe('parse valid HTML', function () {
      it('should return nothing with only a single
 element', function () {
        var htmlInput = '
Does this work?
';
        var isValidNode = function () {
          return true;
        };
        var processingInstructions = [{
          shouldProcessNode: function (node) {
            return node.name && node.name !== 'p';
          },
          processNode: processNodeDefinitions.processDefaultNode,
        },];
        var reactComponent = parser.parseWithInstructions(htmlInput, isValidNode,
          processingInstructions);

          // With only 1
 element, nothing is rendered
          assert.equal(reactComponent, false);
      });

      it('should return a single
 element within a div of
 and
 as siblings',
          function () {
        var htmlInput = '

Title

Paragraph

';
        var htmlExpected = '

Title

';

        var isValidNode = function () {
          return true;
        };

        var processingInstructions = [{
          shouldProcessNode: function (node) {
            return node.type === 'text' || node.name !== 'p';
          },
          processNode: processNodeDefinitions.processDefaultNode,
        },];
        var reactComponent = parser.parseWithInstructions(htmlInput, isValidNode,
          processingInstructions);
        var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);
        assert.equal(reactHtml, htmlExpected);
      });

      it('should replace the children of an element', function () {
        var htmlInput = '

Text

Text

';
        var htmlExpected = '

Heading

';

        var isValidNode = function () {
          return true;
        };

        var processingInstructions = [
          {
            replaceChildren: true,
            shouldProcessNode: function (node) {
              return node.attribs && node.attribs['data-test'] === 'foo';
            },
            processNode: function (node, children, index) {
              return React.createElement('h1', {key: index,}, 'Heading');
            },
          },
          {
            // Anything else
            shouldProcessNode: function (node) {
              return true;
            },
            processNode: processNodeDefinitions.processDefaultNode,
          },
        ];

        var reactComponent = parser.parseWithInstructions(htmlInput, isValidNode,
          processingInstructions);
        var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);
        assert.equal(reactHtml, htmlExpected);
      });

      it('should return capitalized content for all
 elements', function () {
        var htmlInput = '

Title

Paragraph
' +
        '
Another title

';
        var htmlExpected = '

TITLE

Paragraph
' +
        '
ANOTHER TITLE

';

        var isValidNode = function () {
          return true;
        };

        var processingInstructions = [
          {
            // Custom
 processing
            shouldProcessNode: function (node) {
              return node.parent && node.parent.name &&
              node.parent.name === 'h1';
            },
            processNode: function (node, children) {
              return node.data.toUpperCase();
            },
          }, {
            // Anything else
            shouldProcessNode: function (node) {
              return true;
            },
            processNode: processNodeDefinitions.processDefaultNode,
          },
        ];
        var reactComponent = parser.parseWithInstructions(htmlInput, isValidNode,
          processingInstructions);
        var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);
        assert.equal(reactHtml, htmlExpected);
      });

      it('should return false in case of invalid node', function () {
        var htmlInput = '

';
        var processingInstructions = [{
          shouldProcessNode: function (node) { return true; },
          processNode: processNodeDefinitions.processDefaultNode,
        }, ];
        var reactComponent = parser.parseWithInstructions(htmlInput,
          function () { return false; }, processingInstructions);

        assert.equal(reactComponent, false);
      });

      it('should generate only valid children', function () {
        var htmlInput = '

';

        var processingInstructions = [{
          shouldProcessNode: function (node) { return true; },
          processNode: processNodeDefinitions.processDefaultNode,
        }, ];
        var reactComponent = parser.parseWithInstructions(htmlInput, function (node) {
          // skip whitespace text nodes to clean up children
          if (node.type === 'text') {
            return node.data.trim() !== '';
          }
          return true;
        }, processingInstructions);

        assert.equal(reactComponent.props.children.length, 2);
      });

      it('should not affect unhandled whitespace', function () {
        var htmlInput = '

';

        var reactComponent = parser.parse(htmlInput);

        assert.equal(reactComponent.props.children.length, 5);
      });
    });
  });

  describe('parse SVG', function () {
    it('should have correct attributes', function () {
      var svgInput = '<svg><image xlink:href="http://i.imgur.com/w7GCRPb.png" /></svg>';
      var reactComponent = parser.parse(svgInput);
      var reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);

      assert(/<image xlink:href="http:\/\/i.imgur.com\/w7GCRPb.png"/.test(reactHtml), reactHtml +
        ' has expected attributes');
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var imageprocessor = require('../lib/imageprocessor.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['awesome'] = {
  setUp: function(done) {
    // setup here
    done();
  },
  'no args': function(test) {
    test.expect(1);
    // tests here
    test.equal(imageprocessor.awesome(), 'awesome', 'should be awesome.');
    test.done();
  },
};
<commit_msg>Deleted not needed test file<commit_after><|endoftext|>


<commit_before>import exec from '../../exec.js';

export const run = async () => {
    return exec('service proftpd status', {}, null, {
        SYSTEMD_PAGER: ''
    });
};
<commit_msg>output after ftp status call<commit_after>import exec from '../../exec.js';

export const run = async () => {
    try {
        await exec('service proftpd status', {}, null, {
            SYSTEMD_PAGER: ''
        });
        return 'Service is running';
    } catch (e) {
        throw new Error('Service is unavailable');
    }
};
<|endoftext|>


<commit_before>import Promise from 'bluebird';
import {
    remove,
    exists
} from '../../utils/file'
import fs from 'fs';
import exec from '../../exec.js';

export const run = async ({
    host,
    path,
    method,
    hostAndAliases
}) => {
    if (method === 'apache') {
        try {
            await exec(`letsencrypt certonly -d ${hostAndAliases} --apache --quiet`);
        } catch (err) {
            throw new Error('Failed to create certificates using Apache Method')
        }
    } else if (method === 'dns') {
        try {
            let hookScript = __dirname + '/../../scripts/dnsAcmeHook.js'
            await exec(`certbot certonly --manual-public-ip-logging-ok --preferred-challenge=dns  --manual-auth-hook ${hookScript} -d ${hostAndAliases} --manual --quiet`, null, null, {
                ...process.env
            });
        } catch (err) {
            throw new Error('Failed to create certificates using DNS Method')
        }

    }
    let lastmodifiedFolder = await getlastModifiedFolder(host)
    let letsEncryptCertsExist = await Promise.all([exists(`/etc/letsencrypt/live/${lastmodifiedFolder}/privkey.pem`), exists(`/etc/letsencrypt/live/${lastmodifiedFolder}/fullchain.pem`)])
    if (letsEncryptCertsExist.includes(false)) {
        throw new Error('CertBot Certs not created')
    } else {
        let fullchain = `/etc/letsencrypt/live/${lastmodifiedFolder}/fullchain.pem`
        let privkey = `/etc/letsencrypt/live/${lastmodifiedFolder}/privkey.pem`
        await deleteFile(path + '/certs/privkey.pem')
        await deleteFile(path + '/certs/fullchain.pem')
        return Promise.all(
            [
                exec('ln -s {{source}} {{destination}}', {
                    source: privkey,
                    destination: path + '/certs/privkey.pem'
                }),
                exec('ln -s {{source}} {{destination}}', {
                    source: fullchain,
                    destination: path + '/certs/fullchain.pem'
                }),
            ])
    }
};

async function getlastModifiedFolder(domain) {
    let path = '/etc/letsencrypt/live'
    return fs.readdirSync(path).filter(function(file) {
        return file.startsWith(domain) && fs.statSync(path + '/' + file).isDirectory()
    }).reduce((last, current) => {
        let currentFileDate = new Date(fs.statSync(path + '/' + current).mtime);
        let lastFileDate = new Date(fs.statSync(path + '/' + last).mtime);
        return (currentFileDate.getTime() > lastFileDate.getTime()) ? current : last;
    })
}

async function deleteFile (filePath) {
    return await remove(filePath)
}
<commit_msg>folder doesnt exists<commit_after>import Promise from 'bluebird';
import {
    remove,
    exists
} from '../../utils/file'
import fs from 'fs';
import exec from '../../exec.js';

export const run = async ({
    host,
    path,
    method,
    hostAndAliases
}) => {
    if (method === 'apache') {
        try {
            await exec(`letsencrypt certonly -d ${hostAndAliases} --apache --quiet`);
        } catch (err) {
            throw new Error('Failed to create certificates using Apache Method')
        }
    } else if (method === 'dns') {
        try {
            let hookScript = __dirname + '/../../scripts/dnsAcmeHook.js'
            await exec(`certbot certonly --manual-public-ip-logging-ok --preferred-challenge=dns  --manual-auth-hook ${hookScript} -d ${hostAndAliases} --manual --quiet`, null, null, {
                ...process.env
            });
        } catch (err) {
            throw new Error('Failed to create certificates using DNS Method')
        }

    }
    let lastmodifiedFolder = await getlastModifiedFolder(host)

    let letsEncryptCertsExist = await Promise.all([exists(`/etc/letsencrypt/live/${lastmodifiedFolder}/privkey.pem`), exists(`/etc/letsencrypt/live/${lastmodifiedFolder}/fullchain.pem`)])
    if (letsEncryptCertsExist.includes(false)) {
        throw new Error('CertBot Certs not created')
    } else {
        let fullchain = `/etc/letsencrypt/live/${lastmodifiedFolder}/fullchain.pem`
        let privkey = `/etc/letsencrypt/live/${lastmodifiedFolder}/privkey.pem`
        if (!fs.existsSync(path + '/certs')){
            fs.mkdirSync(path + '/certs');
        } else {
            await deleteFile(path + '/certs/privkey.pem')
            await deleteFile(path + '/certs/fullchain.pem')
        }
        return Promise.all(
            [
                exec('ln -s {{source}} {{destination}}', {
                    source: privkey,
                    destination: path + '/certs/privkey.pem'
                }),
                exec('ln -s {{source}} {{destination}}', {
                    source: fullchain,
                    destination: path + '/certs/fullchain.pem'
                }),
            ])
    }
};

async function getlastModifiedFolder(domain) {
    let path = '/etc/letsencrypt/live'
    return fs.readdirSync(path).filter(function(file) {
        return file.startsWith(domain) && fs.statSync(path + '/' + file).isDirectory()
    }).reduce((last, current) => {
        let currentFileDate = new Date(fs.statSync(path + '/' + current).mtime);
        let lastFileDate = new Date(fs.statSync(path + '/' + last).mtime);
        return (currentFileDate.getTime() > lastFileDate.getTime()) ? current : last;
    })
}

async function deleteFile (filePath) {
    return await remove(filePath)
}
<|endoftext|>


<commit_before>module.exports = function(config, Queue, logger, idGenerator, taskQName) {
  var m = {_taskQueues: {}};

  Queue = Queue || require('../queue/queue');

  idGenerator = idGenerator || global.random;
  m._logger = logger || global.logger;

  m.createTask = function(taskName, taskDef) {
    if(!m._taskQueues[taskName]) {
      m._taskQueues[taskName] = Queue(taskName+'-queue-'+config.env);
    }
    if (!taskDef.transactionId) {
      taskDef.transactionId = idGenerator.getGUID();
    }

    taskDef = _.cloneDeep(taskDef);

    delete taskDef.rawData;
    delete taskDef.receiptHandle;
    delete taskDef.err;

    taskDef.taskName = taskName;
    taskDef.taskId = idGenerator.getGUID();
    return m._taskQueues[taskName].sendMsg({body: taskDef})
        .then(function(msgId) {
          taskDef.msgId = msgId;
          m._logger.log('CREATE_TASK_SUCCESS', taskDef);
          return taskDef;
        }).then(null, function(err) {
          var newErr = new Error('Queue inaccessible error.');
          newErr.stack = err.stack;
          newErr.inner = err;
          throw newErr;
        }).then(null, function(err) {
          taskDef.err = err;
          m._logger.logError('CREATE_TASK_FAILED', taskDef);
          throw err;
        });
  };

  m.pullNextTask = function(taskName) {
    var taskQ;
    if (taskQName) {
      if (!m._taskQueues[taskQName]) {
        log('Initializing poison queue:',taskQName+'-queue-'+config.env);
        m._taskQueues[taskQName] = Queue(taskQName+'-queue-'+config.env);
      }
      taskQ = m._taskQueues[taskQName];
    }
    else if(!m._taskQueues[taskName]) {
      log('Initializing task queue:',taskName+'-queue-'+config.env);
      m._taskQueues[taskName] = Queue(taskName+'-queue-'+config.env);
    }
    if (!taskQ) taskQ = m._taskQueues[taskName];
    debug('pulling from task queue:',taskName+'-queue-'+config.env);

    // TODO: add option and support for guaranteed FIFO, since SQS doesnt support FIFO.
    return taskQ.receiveMsg().then(function(msgs) {
      if (!msgs) {
        throw 'QUEUE_EMPTY';
      }
      m._logger.log('TASK_STARTED', msgs[0]);
      return msgs[0];
    },function(err) {
      m._logger.logError("GET_TASK_FAILED", err);
      throw err;
    });
  };

  m.completeTask = function(taskName, taskDef) {
    if(!m._taskQueues[taskName]) {
      m._taskQueues[taskName] = Queue(taskName+'-queue-'+config.env);
    }
    return m._taskQueues[taskName].deleteMsg(taskDef.receiptHandle)
      .then(function() {
        m._logger.log('TASK_COMPLETED', {transactionId: taskDef.transactionId, taskId: taskDef.taskId});
        return true;
      });
  };

  return m;
};<commit_msg>update task runner to support pulling from poison queue.  Bugfix<commit_after>module.exports = function(config, Queue, logger, idGenerator, taskQName) {
  var m = {_taskQueues: {}};

  Queue = Queue || require('../queue/queue');

  idGenerator = idGenerator || global.random;
  m._logger = logger || global.logger;

  m.createTask = function(taskName, taskDef) {
    if(!m._taskQueues[taskName]) {
      m._taskQueues[taskName] = Queue(taskName+'-queue-'+config.env);
    }
    if (!taskDef.transactionId) {
      taskDef.transactionId = idGenerator.getGUID();
    }

    taskDef = _.cloneDeep(taskDef);

    delete taskDef.rawData;
    delete taskDef.receiptHandle;
    delete taskDef.err;

    taskDef.taskName = taskName;
    taskDef.taskId = idGenerator.getGUID();
    return m._taskQueues[taskName].sendMsg({body: taskDef})
        .then(function(msgId) {
          taskDef.msgId = msgId;
          m._logger.log('CREATE_TASK_SUCCESS', taskDef);
          return taskDef;
        }).then(null, function(err) {
          var newErr = new Error('Queue inaccessible error.');
          newErr.stack = err.stack;
          newErr.inner = err;
          throw newErr;
        }).then(null, function(err) {
          taskDef.err = err;
          m._logger.logError('CREATE_TASK_FAILED', taskDef);
          throw err;
        });
  };

  function getQueue(taskName) {
    var taskQ;
    if (taskQName) {
      if (!m._taskQueues[taskQName]) {
        log('Initializing poison queue:',taskQName+'-queue-'+config.env);
        m._taskQueues[taskQName] = Queue(taskQName+'-queue-'+config.env);
      }
      taskQ = m._taskQueues[taskQName];
    }
    else if(!m._taskQueues[taskName]) {
      log('Initializing task queue:',taskName+'-queue-'+config.env);
      m._taskQueues[taskName] = Queue(taskName+'-queue-'+config.env);
    }
    if (!taskQ) taskQ = m._taskQueues[taskName];
    return taskQ;
  }
  m.pullNextTask = function(taskName) {
    var taskQ = getQueue(taskName);
    debug('pulling from task queue:',taskName+'-queue-'+config.env);

    // TODO: add option and support for guaranteed FIFO, since SQS doesnt support FIFO.
    return taskQ.receiveMsg().then(function(msgs) {
      if (!msgs) {
        throw 'QUEUE_EMPTY';
      }
      m._logger.log('TASK_STARTED', msgs[0]);
      return msgs[0];
    },function(err) {
      m._logger.logError("GET_TASK_FAILED", err);
      throw err;
    });
  };

  m.completeTask = function(taskName, taskDef) {
    var taskQ = getQueue(taskName);
    return taskQ.deleteMsg(taskDef.receiptHandle)
      .then(function() {
        m._logger.log('TASK_COMPLETED', {transactionId: taskDef.transactionId, taskId: taskDef.taskId});
        return true;
      });
  };

  return m;
};<|endoftext|>


<commit_before>const test = require('tape');
const mockery = require('mockery');
const inspectHandle = {};

process.title = 'testbot';

function SocketMock() {
	this.bytesRead = 0;
	this.bytesWritten = 0;
}

SocketMock.prototype.write = function(s) {
	this.bytesWritten += s.length;
};

SocketMock.prototype.read = function(buf) {
	this.bytesRead += buf.length;
};

SocketMock.prototype.unref = function() {};

mockery.registerAllowable('../lib/serveReferences.js');
mockery.registerMock('net', {
	createServer: listener => {
		const server = {};
		const prototype = Object.getPrototypeOf(server);

		prototype.close = function() {};

		prototype.listen = function(options, callback) {
			server.address = {
				port: options.port,
				address: options.host,
				family: 'IPv4'
			};

			setImmediate(callback);
		};

		prototype.once = function(name, handle) {}; // eslint-disable-line no-unused-vars

		prototype.unref = function() {};

		setImmediate(() => listener(new SocketMock()));

		return server;
	}
});
mockery.registerMock('repl', {
	start: options => {
		const server = {
			context: {},
			prompt: options.prompt,
			useColors: options.useColors,
			ignoreUndefined: options.ignoreUndefined,
			input: options.input,
			output: options.output
		};
		const prototype = Object.getPrototypeOf(server);

		prototype.on = function(name, handle) {}; // eslint-disable-line no-unused-vars

		inspectHandle.repl = server;

		return server;
	}
});
mockery.enable();

const serveReferences = require('../lib/serveReferences.js');

mockery.disable();
mockery.deregisterAll();

test('serveReferences', t => {
	const refs = {
		foo: 'bar',
		baz: 1,
		hello: () => console.log('Hello!'),
		square: x => x * x
	};

	serveReferences(refs, (err, server) => {
		t.error(err, 'does not normally error');

		if (err) return t.end();

		t.equal(server.address.port, 8008, 'defaults to port 8008');

		t.equal(inspectHandle.repl.prompt, 'testbot> ', 'repl prompt uses process title');
		t.equal(inspectHandle.repl.useColors, true, 'repl uses colors');
		t.equal(inspectHandle.repl.ignoreUndefined, true, 'repl ignores undefined');
		t.ok(inspectHandle.repl.output instanceof SocketMock, 'repl output handle is a socket');
		t.ok(inspectHandle.repl.input instanceof SocketMock, 'repl input handle is a socket');

		t.equal(inspectHandle.repl.context.foo, 'bar', 'set foo reference in the context');
		t.equal(inspectHandle.repl.context.baz, 1, 'set baz reference in the context');
		t.equal(typeof inspectHandle.repl.context.hello, 'function', 'set hello reference in the context');
		t.equal(typeof inspectHandle.repl.context.square, 'function', 'set square reference in the context');

		t.end();
	});
});
<commit_msg>Prefer class pattern in serveReferences test.<commit_after>const test = require('tape');
const mockery = require('mockery');
const inspectHandle = {};

process.title = 'testbot';

class SocketMock {
	constructor() {
		this.bytesRead = 0;
		this.bytesWritten = 0;
	}

	write(s) {
		this.bytesWritten += s.length;
	}

	read(buf) {
		this.bytesRead += buf.length;
	}

	unref() { }
}

mockery.registerAllowable('../lib/serveReferences.js');
mockery.registerMock('net', {
	createServer: listener => {
		const server = {};
		const prototype = Object.getPrototypeOf(server);

		prototype.close = function() {};

		prototype.listen = function(options, callback) {
			server.address = {
				port: options.port,
				address: options.host,
				family: 'IPv4'
			};

			setImmediate(callback);
		};

		prototype.once = function(name, handle) {}; // eslint-disable-line no-unused-vars

		prototype.unref = function() {};

		setImmediate(() => listener(new SocketMock()));

		return server;
	}
});
mockery.registerMock('repl', {
	start: options => {
		const server = {
			context: {},
			prompt: options.prompt,
			useColors: options.useColors,
			ignoreUndefined: options.ignoreUndefined,
			input: options.input,
			output: options.output
		};
		const prototype = Object.getPrototypeOf(server);

		prototype.on = function(name, handle) {}; // eslint-disable-line no-unused-vars

		inspectHandle.repl = server;

		return server;
	}
});
mockery.enable();

const serveReferences = require('../lib/serveReferences.js');

mockery.disable();
mockery.deregisterAll();

test('serveReferences', t => {
	const refs = {
		foo: 'bar',
		baz: 1,
		hello: () => console.log('Hello!'),
		square: x => x * x
	};

	serveReferences(refs, (err, server) => {
		t.error(err, 'does not normally error');

		if (err) return t.end();

		t.equal(server.address.port, 8008, 'defaults to port 8008');

		t.equal(inspectHandle.repl.prompt, 'testbot> ', 'repl prompt uses process title');
		t.equal(inspectHandle.repl.useColors, true, 'repl uses colors');
		t.equal(inspectHandle.repl.ignoreUndefined, true, 'repl ignores undefined');
		t.ok(inspectHandle.repl.output instanceof SocketMock, 'repl output handle is a socket');
		t.ok(inspectHandle.repl.input instanceof SocketMock, 'repl input handle is a socket');

		t.equal(inspectHandle.repl.context.foo, 'bar', 'set foo reference in the context');
		t.equal(inspectHandle.repl.context.baz, 1, 'set baz reference in the context');
		t.equal(typeof inspectHandle.repl.context.hello, 'function', 'set hello reference in the context');
		t.equal(typeof inspectHandle.repl.context.square, 'function', 'set square reference in the context');

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


<commit_before>var App, targetController, pusherController, channelName, bindings;

var FakeController = Em.Controller.extend(EmberPusher.Bindings, {
  PUSHER_SUBSCRIPTIONS: {
    craycraychannel: ['event-one', 'event-two']
  },
  eventOne: function(){ return "event-one-fired"; },
  eventTwo: function(){ return "event-two-fired"; }
});

Ember.Application.initializer({
  name: "registerFakeController",
  initialize: function(container, application) {
    container.register('controller:fake', FakeController);
    targetController = container.lookup('controller:fake');
  }
});

App = Ember.Application.create({
  PUSHER_OPTS: { key: 'foo' }
});

describe("Controller", function() {

  before(function(){
    pusherController = App.__container__.lookup('controller:pusher');
    channelName = 'craycraychannel';
    bindings = pusherController.get('bindings');
  });

  describe("sanity", function(){
    it("exists", function() {
      assert.ok(EmberPusher.Controller, "Ember.PusherController exists");
      assert.ok(pusherController.get('connection'), "pusher connection initialized");
    });

    it("initializes the bindings object properly", function() {
      assert.ok(pusherController.get('bindings'));
    });
  });

  describe("wire", function() {
    it("initializes channelName in the bindings hash", function() {
      assert.ok(pusherController.get('bindings')[channelName], "Creates a channel name");
    });
    it("initializes eventBindings in the bindings hash", function() {
      var targetId = targetController._pusherEventsId();
      assert.ok(bindings[channelName].eventBindings[targetId].length == 2, "Knows about two bound events");
    });
  });

  describe("channelFor", function() {
    it("returns a channel object", function() {
      var channel = pusherController.channelFor(channelName);
      assert.ok(channel, "channel defined");
    });
  });

});
<commit_msg>Update controller test<commit_after>var App, targetController, pusherController, channelName, bindings;

var FakeController = Em.Controller.extend(EmberPusher.Bindings, {
  PUSHER_SUBSCRIPTIONS: {
    craycraychannel: ['event-one', 'event-two']
  },
  eventOne: function(){ return "event-one-fired"; },
  eventTwo: function(){ return "event-two-fired"; }
});

Ember.Application.initializer({
  name: "registerFakeController",
  initialize: function(container, application) {
    container.register('controller:fake', FakeController);
    targetController = container.lookup('controller:fake');
  }
});

App = Ember.Application.create({
  PUSHER_OPTS: { key: 'foo' }
});

describe("Controller", function() {

  before(function(){
    pusherController = App.__container__.lookup('controller:pusher');
    channelName = 'craycraychannel';
    bindings = pusherController.get('bindings');
  });

  describe("sanity", function(){
    it("exists", function() {
      assert.ok(EmberPusher.Controller, "Ember.PusherController exists");
      assert.ok(pusherController.get('connection'), "pusher connection initialized");
    });

    it("initializes the bindings object properly", function() {
      assert.ok(pusherController.get('bindings'));
    });
  });

  describe("wire", function() {
    it("initializes channelName in the bindings hash", function() {
      assert.ok(pusherController.get('bindings')[channelName], "Creates a channel name");
    });

    it("initializes eventBindings in the bindings hash", function() {
      var targetId = targetController._pusherEventsId();
      assert.ok(bindings[channelName].eventBindings[targetId].length == 2, "Knows about two bound events");
    });
  });

  describe("channelFor", function() {
    it("returns a channel object", function() {
      var channel = pusherController.channelFor(channelName);
      assert.ok(channel, "channel defined");
    });
  });

});
<|endoftext|>


<commit_before>import { expect } from 'chai';
import TestUtils from 'react/lib/ReactTestUtils';
import Yummies from '../../lib/yummies';

const dummyBlock = { block: 'block' };

describe('yummies', () => {
    it('exist', () => {
        expect(Yummies).to.exist;
    });

    it('renderToString()', () => {
        expect(
            Yummies.renderToString(dummyBlock)
        ).to.be.a('string');
    });

    it('renderToStaticMarkup()', () => {
        expect(
            Yummies.renderToStaticMarkup(dummyBlock)
        ).to.be.a('string');
    });

    it('createElement()', () => {
        expect(
            TestUtils.isElement(
                Yummies.createElement(dummyBlock)
            )
        ).to.be.true;
    });

    describe('createClass()', () => {
        it('json', () => {
            expect(
                Yummies.renderToString(
                    Yummies.createFactory(Yummies.createClass({
                        render() {
                            return dummyBlock;
                        }
                    }))()
                )
            ).to.be.a('string');
        });

        it('null', () => {
            expect(
                Yummies.renderToString(
                    Yummies.createFactory(Yummies.createClass({
                        render() {
                            return null;
                        }
                    }))()
                )
            ).to.be.a('string');
        });

        it('ReactElement', () => {
            expect(
                Yummies.renderToString(
                    Yummies.createFactory(Yummies.createClass({
                        render() {
                            return Yummies.createElement(dummyBlock);
                        }
                    }))()
                )
            ).to.be.a('string');
        });
    });

    it('_autoBind()', done => {
        let self;

        class DummyClass extends Yummies.Component {
            constructor() {
                super();

                self = this;
                Yummies._autoBind(this);
                setTimeout(this.test, 0);
            }

            test() {
                expect(this).to.deep.equal(self);
                done();
            }
        }

        new DummyClass();
    });

    describe('_prepareClass()', () => {
        it('json', () => {
            class DummyClass extends Yummies.Component {
                constructor(props) {
                    super(props);
                }

                render() {
                    return dummyBlock;
                }
            }

            const PreparedClass = Yummies._prepareClass(DummyClass);
            const preparedInstance = new PreparedClass();

            expect(
                Yummies.renderToString(
                    Yummies.createFactory(PreparedClass)()
                )
            ).to.be.a('string');

            expect(preparedInstance).to.be.an.instanceOf(DummyClass);
        });

        it('null', () => {
            class DummyClass extends Yummies.Component {
                constructor(props) {
                    super(props);
                }

                render() {
                    return null;
                }
            }

            const PreparedClass = Yummies._prepareClass(DummyClass);
            const preparedInstance = new PreparedClass();

            expect(
                Yummies.renderToString(
                    Yummies.createFactory(PreparedClass)()
                )
            ).to.be.a('string');

            expect(preparedInstance).to.be.an.instanceOf(DummyClass);
        });

        it('ReactElement', () => {
            class DummyClass extends Yummies.Component {
                constructor(props) {
                    super(props);
                }

                render() {
                    return Yummies.createElement(dummyBlock);
                }
            }

            const PreparedClass = Yummies._prepareClass(DummyClass);
            const preparedInstance = new PreparedClass();

            expect(
                Yummies.renderToString(
                    Yummies.createFactory(PreparedClass)()
                )
            ).to.be.a('string');

            expect(preparedInstance).to.be.an.instanceOf(DummyClass);
        });
    });

    it('_mixins()', () => {
        let MixinClass1;
        let MixinClass2;

        function Mixin1(Base) {
            MixinClass1 = class extends Base {
                test1() {}
            };

            return MixinClass1;
        }

        function Mixin2(Base) {
            MixinClass2 = class extends Base {
                test2() {}
            };

            return MixinClass2;
        }

        class DummyClass {
            static get mixins() {
                return [ Mixin1, Mixin2 ];
            }
        }

        const MixedClass = Yummies._mixins(DummyClass);
        const mixedInstance = new MixedClass();

        expect(mixedInstance).to.be.an.instanceOf(DummyClass);
        expect(mixedInstance).to.be.an.instanceOf(MixinClass1);
        expect(mixedInstance).to.be.an.instanceOf(MixinClass2);
        expect(mixedInstance).to.have.property('test1');
        expect(mixedInstance).to.have.property('test2');
    });
});
<commit_msg>:neckbeard: 100% tests coverage<commit_after>import { expect } from 'chai';
import TestUtils from 'react/lib/ReactTestUtils';
import Yummies from '../../lib/yummies';

const dummyBlock = { block: 'block' };

describe('yummies', () => {
    it('exist', () => {
        expect(Yummies).to.exist;
    });

    it('renderToString()', () => {
        expect(
            Yummies.renderToString(dummyBlock)
        ).to.be.a('string');
    });

    it('renderToStaticMarkup()', () => {
        expect(
            Yummies.renderToStaticMarkup(dummyBlock)
        ).to.be.a('string');
    });

    it('createElement()', () => {
        expect(
            TestUtils.isElement(
                Yummies.createElement(dummyBlock)
            )
        ).to.be.true;
    });

    describe('createClass()', () => {
        it('json', () => {
            expect(
                Yummies.renderToString(
                    Yummies.createFactory(Yummies.createClass({
                        render() {
                            return dummyBlock;
                        }
                    }))()
                )
            ).to.be.a('string');
        });

        it('null', () => {
            expect(
                Yummies.renderToString(
                    Yummies.createFactory(Yummies.createClass({
                        render() {
                            return null;
                        }
                    }))()
                )
            ).to.be.a('string');
        });

        it('ReactElement', () => {
            expect(
                Yummies.renderToString(
                    Yummies.createFactory(Yummies.createClass({
                        render() {
                            return Yummies.createElement(dummyBlock);
                        }
                    }))()
                )
            ).to.be.a('string');
        });
    });

    it('_autoBind()', done => {
        let self;

        class DummyClass extends Yummies.Component {
            constructor() {
                super();

                self = this;
                Yummies._autoBind(this);
                setTimeout(this.test, 0);
            }

            test() {
                expect(this).to.deep.equal(self);
                done();
            }
        }

        new DummyClass();
    });

    describe('_prepareClass()', () => {
        it('json', () => {
            class DummyClass extends Yummies.Component {
                constructor(props) {
                    super(props);
                }

                render() {
                    return dummyBlock;
                }
            }

            const PreparedClass = Yummies._prepareClass(DummyClass);
            const preparedInstance = new PreparedClass();

            expect(
                Yummies.renderToString(
                    Yummies.createFactory(PreparedClass)()
                )
            ).to.be.a('string');

            expect(preparedInstance).to.be.an.instanceOf(DummyClass);
        });

        it('null', () => {
            class DummyClass extends Yummies.Component {
                constructor(props) {
                    super(props);
                }

                render() {
                    return null;
                }
            }

            const PreparedClass = Yummies._prepareClass(DummyClass);
            const preparedInstance = new PreparedClass();

            expect(
                Yummies.renderToString(
                    Yummies.createFactory(PreparedClass)()
                )
            ).to.be.a('string');

            expect(preparedInstance).to.be.an.instanceOf(DummyClass);
        });

        it('ReactElement', () => {
            class DummyClass extends Yummies.Component {
                constructor(props) {
                    super(props);
                }

                render() {
                    return Yummies.createElement(dummyBlock);
                }
            }

            const PreparedClass = Yummies._prepareClass(DummyClass);
            const preparedInstance = new PreparedClass();

            expect(
                Yummies.renderToString(
                    Yummies.createFactory(PreparedClass)()
                )
            ).to.be.a('string');

            expect(preparedInstance).to.be.an.instanceOf(DummyClass);
        });
    });

    it('_mixins()', () => {
        let MixinClass1;
        let MixinClass2;

        function Mixin1(Base) {
            MixinClass1 = class extends Base {
                test1() {}
            };

            return MixinClass1;
        }

        function Mixin2(Base) {
            MixinClass2 = class extends Base {
                test2() {}
            };

            return MixinClass2;
        }

        class DummyClass {
            static get mixins() {
                return [ Mixin1, Mixin2 ];
            }
        }

        const MixedClass = Yummies._mixins(DummyClass);
        const mixedInstance = new MixedClass();

        expect(mixedInstance).to.be.an.instanceOf(DummyClass);
        expect(mixedInstance).to.be.an.instanceOf(MixinClass1);
        expect(mixedInstance).to.be.an.instanceOf(MixinClass2);
        expect(mixedInstance).to.have.property('test1');
        expect(mixedInstance).to.have.property('test2');
    });

    it('yummify()', () => {
        let DummyClass1;
        let DummyClass2;

        const ResultFactory = Yummies.yummify([
            {
                type: 'main',
                module: function(Base) {
                    DummyClass1 = class extends Base {
                        test1() {}
                    };

                    return DummyClass1;
                }
            },
            {
                type: 'main',
                module: function(Base) {
                    DummyClass2 = class extends Base {
                        test2() {}
                    };

                    return DummyClass2;
                }
            },
            {
                type: 'styles',
                module: true
            }
        ]);
        const ResultClass = ResultFactory().type;
        const ResultInstance = new ResultClass();

        expect(ResultInstance).to.be.an.instanceOf(Yummies.Component);
        expect(ResultInstance).to.be.an.instanceOf(DummyClass1);
        expect(ResultInstance).to.be.an.instanceOf(DummyClass2);
        expect(ResultInstance).to.have.property('test1');
        expect(ResultInstance).to.have.property('test2');
    });

    it('yummifyRaw()', () => {
        let DummyClass1;
        let DummyClass2;

        const ResultClassFactory = Yummies.yummifyRaw([
            {
                type: 'main',
                module: function(Base) {
                    DummyClass1 = class extends Base {
                        test1() {}
                    };

                    return DummyClass1;
                }
            },
            {
                type: 'main',
                module: function(Base) {
                    DummyClass2 = class extends Base {
                        test2() {}
                    };

                    return DummyClass2;
                }
            },
            {
                type: 'styles',
                module: true
            }
        ]);
        const ResultClass = ResultClassFactory(Yummies.Component);
        const ResultInstance = new ResultClass();

        expect(ResultInstance).to.be.an.instanceOf(Yummies.Component);
        expect(ResultInstance).to.be.an.instanceOf(DummyClass1);
        expect(ResultInstance).to.be.an.instanceOf(DummyClass2);
        expect(ResultInstance).to.have.property('test1');
        expect(ResultInstance).to.have.property('test2');
    });
});
<|endoftext|>


<commit_before>import { expect } from "chai";
import { randomInt } from "../../src/math/randomInt";

describe("math/randomInt", () => {
  it("returns the same number if mix and max are the same", () => {
    const a = randomInt(1, 1);
    const b = randomInt(1, 1);

    expect(a).not.to.equal(undefined);
    expect(a).not.to.equal(Infinity);
    expect(a).not.to.equal(NaN);
    expect(a).to.equal(b);
  });

  it("returns a random number inside range", () => {
    const a = randomInt(0, 999);
    const b = randomInt(0, 999);

    expect(a).to.be.lessThan(999.01);
    expect(a).to.be.greaterThan(-0.01);
    expect(b).to.be.lessThan(999.01);
    expect(b).to.be.greaterThan(-0.01);
    expect(a).to.not.equal(b);
  });
});
<commit_msg>Uopdates randomInt tests.<commit_after>import { expect } from "chai";
import { randomInt } from "../../src/math/randomInt";

describe("math/randomInt", () => {
  it("returns the same number if mix and max are the same", () => {
    const a = randomInt(1, 1);
    const b = randomInt(1, 1);

    expect(a).to.not.be.undefined;
    expect(a).to.not.be.Infinity;
    expect(a).to.not.be.NaN;
    expect(a).to.equal(b);
  });

  it("returns a random number inside range", () => {
    const a = randomInt(0, 999);
    const b = randomInt(0, 999);

    expect(a).to.be.lessThan(999.01);
    expect(a).to.be.greaterThan(-0.01);
    expect(b).to.be.lessThan(999.01);
    expect(b).to.be.greaterThan(-0.01);
    expect(a).to.not.equal(b);
  });
});
<|endoftext|>


<commit_before>// Copyright (c) 2015-2016 Yuya Ochiai
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
'use strict';

const fs = require('fs');
const path = require('path');

const Application = require('spectron').Application;
const chai = require('chai');
chai.should();

const sourceRootDir = path.join(__dirname, '../..');
const electronBinaryPath = (() => {
  if (process.platform === 'darwin') {
    return path.join(sourceRootDir, 'node_modules/electron/dist/Electron.app/Contents/MacOS/Electron');
  }
  const exeExtension = (process.platform === 'win32') ? '.exe' : '';
  return path.join(sourceRootDir, 'node_modules/electron/dist/electron' + exeExtension);
})();
const userDataDir = path.join(sourceRootDir, 'test/testUserData/');
const configFilePath = path.join(userDataDir, 'config.json');
const boundsInfoPath = path.join(userDataDir, 'bounds-info.json');
const mattermostURL = 'http://example.com/';

module.exports = {
  sourceRootDir,
  configFilePath,
  userDataDir,
  boundsInfoPath,
  mattermostURL,

  cleanTestConfig() {
    [configFilePath, boundsInfoPath].forEach((file) => {
      try {
        fs.unlinkSync(file);
      } catch (err) {
        if (err.code !== 'ENOENT') {
          console.error(err);
        }
      }
    });
  },

  createTestUserDataDir() {
    if (!fs.existsSync(userDataDir)) {
      fs.mkdirSync(userDataDir);
    }
  },

  getSpectronApp() {
    const options = {
      path: electronBinaryPath,
      args: [`${path.join(sourceRootDir, 'src')}`, `--data-dir=${userDataDir}`, '--disable-dev-mode'],

      // enable this if chromedriver hangs to see logs
      // chromeDriverLogPath: '../chromedriverlog.txt',
    };
    if (process.platform === 'darwin') {
      // on a mac, debbuging port might conflict with other apps
      // this changes the default debugging port so chromedriver can run without issues.
      options.chromeDriverArgs.push('remote-debugging-port=9222');
    }
    return new Application(options);
  },

  addClientCommands(client) {
    client.addCommand('loadSettingsPage', function async() {
      return this.url('file://' + path.join(sourceRootDir, 'src/browser/settings.html')).waitUntilWindowLoaded();
    });
    client.addCommand('isNodeEnabled', function async() {
      return this.execute(() => {
        try {
          if (require('child_process')) {
            return true;
          }
          return false;
        } catch (e) {
          return false;
        }
      }).then((requireResult) => {
        return requireResult.value;
      });
    });
    client.addCommand('waitForAppOptionsAutoSaved', function async() {
      const ID_APP_OPTIONS_SAVE_INDICATOR = '#appOptionsSaveIndicator';
      const TIMEOUT = 5000;
      return this.
        waitForVisible(ID_APP_OPTIONS_SAVE_INDICATOR, TIMEOUT).
        waitForVisible(ID_APP_OPTIONS_SAVE_INDICATOR, TIMEOUT, true);
    });
  },

  // execute the test only when `condition` is true
  shouldTest(it, condition) {
    return condition ? it : it.skip;
  },
  isOneOf(platforms) {
    return (platforms.indexOf(process.platform) !== -1);
  },
};
<commit_msg>bugfix: initialize chromeDriverArgs arg (#1032)<commit_after>// Copyright (c) 2015-2016 Yuya Ochiai
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
'use strict';

const fs = require('fs');
const path = require('path');

const Application = require('spectron').Application;
const chai = require('chai');
chai.should();

const sourceRootDir = path.join(__dirname, '../..');
const electronBinaryPath = (() => {
  if (process.platform === 'darwin') {
    return path.join(sourceRootDir, 'node_modules/electron/dist/Electron.app/Contents/MacOS/Electron');
  }
  const exeExtension = (process.platform === 'win32') ? '.exe' : '';
  return path.join(sourceRootDir, 'node_modules/electron/dist/electron' + exeExtension);
})();
const userDataDir = path.join(sourceRootDir, 'test/testUserData/');
const configFilePath = path.join(userDataDir, 'config.json');
const boundsInfoPath = path.join(userDataDir, 'bounds-info.json');
const mattermostURL = 'http://example.com/';

module.exports = {
  sourceRootDir,
  configFilePath,
  userDataDir,
  boundsInfoPath,
  mattermostURL,

  cleanTestConfig() {
    [configFilePath, boundsInfoPath].forEach((file) => {
      try {
        fs.unlinkSync(file);
      } catch (err) {
        if (err.code !== 'ENOENT') {
          console.error(err);
        }
      }
    });
  },

  createTestUserDataDir() {
    if (!fs.existsSync(userDataDir)) {
      fs.mkdirSync(userDataDir);
    }
  },

  getSpectronApp() {
    const options = {
      path: electronBinaryPath,
      args: [`${path.join(sourceRootDir, 'src')}`, `--data-dir=${userDataDir}`, '--disable-dev-mode'],
      chromeDriverArgs: [],

      // enable this if chromedriver hangs to see logs
      // chromeDriverLogPath: '../chromedriverlog.txt',
    };
    if (process.platform === 'darwin') {
      // on a mac, debbuging port might conflict with other apps
      // this changes the default debugging port so chromedriver can run without issues.
      options.chromeDriverArgs.push('remote-debugging-port=9222');
    }
    return new Application(options);
  },

  addClientCommands(client) {
    client.addCommand('loadSettingsPage', function async() {
      return this.url('file://' + path.join(sourceRootDir, 'src/browser/settings.html')).waitUntilWindowLoaded();
    });
    client.addCommand('isNodeEnabled', function async() {
      return this.execute(() => {
        try {
          if (require('child_process')) {
            return true;
          }
          return false;
        } catch (e) {
          return false;
        }
      }).then((requireResult) => {
        return requireResult.value;
      });
    });
    client.addCommand('waitForAppOptionsAutoSaved', function async() {
      const ID_APP_OPTIONS_SAVE_INDICATOR = '#appOptionsSaveIndicator';
      const TIMEOUT = 5000;
      return this.
        waitForVisible(ID_APP_OPTIONS_SAVE_INDICATOR, TIMEOUT).
        waitForVisible(ID_APP_OPTIONS_SAVE_INDICATOR, TIMEOUT, true);
    });
  },

  // execute the test only when `condition` is true
  shouldTest(it, condition) {
    return condition ? it : it.skip;
  },
  isOneOf(platforms) {
    return (platforms.indexOf(process.platform) !== -1);
  },
};
<|endoftext|>


<commit_before>define('lyria/template/string', ['objectify'], function(objectify) {
  var templateString = {
    key: {
      start: '{{',
      end: '}}'
    },
    process: function(value, parameter) {
      if (value == null) {
        return;
      }

      if (parameter == null) {
        return value;
      }

      // Array or object
      if ( typeof parameter === 'object') {
        var templateObject = objectify(parameter);

        var keys = Object.keys(templateObject);

        for (var i = 0, j = keys.length; i < j; i++) {
          (function(num, item) {
            value = value.replace(new RegExp(templateString.key.start + num + templateString.key.end, 'g'), item);
          })(keys[i], templateObject[keys[i]]);
        }

      }

      return value;
    }
  };

  return templateString;
});
<commit_msg>Fixes #39: Corrected output when using numbered identifiers<commit_after>define('lyria/template/string', ['objectify'], function(objectify) {
  var templateString = {
    key: {
      start: '\\{{',
      end: '\\}}'
    },
    process: function(value, parameter) {
      if (value == null) {
        return;
      }

      if (parameter == null) {
        return value;
      }

      // Array or object
      if ( typeof parameter === 'object') {
        var templateObject = objectify(parameter);

        var keys = Object.keys(templateObject);

        for (var i = 0, j = keys.length; i < j; i++) {
          (function(num, item) {
            value = value.replace(new RegExp(templateString.key.start + num + templateString.key.end, 'g'), item);
          })(keys[i], templateObject[keys[i]]);
        }

      }

      return value;
    }
  };

  return templateString;
});
<|endoftext|>


<commit_before>(function($) {
	function changeMultiple(method, arg) {
		// Apply the same method and arg to multiple objects
		return function() {
			var args = arguments;
			if(!args.length) return false; // no args
			for(var i = 0; i < args.length; i++) {
				if(args[i] && args[i][method]) args[i][method](arg);
			}
			return true;
		}
	}
	var show = changeMultiple("removeClass", "jshidden");
	var hide = changeMultiple("addClass", "jshidden");
	var toggle = changeMultiple("toggleClass", "jshidden");
	function visible(el) {
		return (el ? !el.hasClass("jshidden") : null);
	}
	function RichSelect(el) {
		// Object for rich menu functionality
		var name, showmenu, menubox, menutext, richopt, menu, valstore;
		var showMenu = function() {
			var el = menu ? menu : menubox;
			show(el);
			if(menu) {
				menu.focus();
			}
		}
		var hideMenu = function() {
			var el = menu ? menu : menubox;
			hide(el);
			var inputs = richopt.find("input");
			// Select form element for added usability
			if(inputs.size()) {
				inputs.first().select();
			}
		}
		var getVal = function() {
			var val;
			if(valstore) {
				val = valstore.val();
			}
			else {
				var option = menu.children("option:selected");
				if(option.size()) val = option.val();
			}
			return val;
		}
		var updateMenubox = function(option) {
			// Shows selected option. If option is a richopt show that element.
			showmenu.addColon();
			option = option || menu.children("option:selected");
			if(option.hasClass("richopt")) {
				menutext.text("");
				show(richopt, menubox);
			}
			else {
				if(!richopt.hasClass("jshidden")) hide(richopt);
				menutext.text(option.text());
				show(menubox);
			}
		}
		var updateMenu = function() {
			// Update selected menu option from valstore value
			if(!menu) return;
			var option;
			var found = false;
			if(valstore) {
				menu.children().each(function(i, el) {
					option = $(el);
					if(option.val() === valstore.val()) {
						option.attr("selected", "selected");
						found = true;
						return false;
					}
				});
			}
			else {
				option = menu.children("option:selected");
				if(option.size()) found = true;
			}
			if(found) updateMenubox(option);
		}
		var updateValstore = function() {
			// Update valstore from selected menu option
			var option = menu.children("option:selected");
			if(option.size()) {
				updateMenubox(option);
				if(valstore) valstore.val(option.val());
			}
		}
		var removeVal = function() {
			// Remove value and collapse menu button to initial form
			showmenu.removeColon();
			hide(menubox);
			menutext.text("");
			if(valstore) valstore.val("");
			if(menu) {
				menu.get(0).selectedIndex = -1;
				hide(menu);
			}
		}
		showmenu = (function() {
			// Object for manipulating showmenu
			var label = el.find(".showmenu");
			label.click(function(e) {
				e.preventDefault();
			});
			var labeltext;
			function init() {
				labeltext = label.contents().get(0).nodeValue;
			}
			return {
				addColon : function() {
					// Show colon in label when expanded
					init();
					if(labeltext.indexOf(":") == -1) {
						label.contents().get(0).nodeValue = $.trim(labeltext) + ":";
					}
				},
				removeColon : function() {
					// Remove colon in label when collapsed
					init();
					label.contents().get(0).nodeValue = labeltext.replace(":", "");
				}
			}
		})();
		showmenu.removeColon();
		menubox = el.find(".menubox");
		// Add empty element for holding option text
		menubox.prepend("<span />");
		menutext = menubox.children().first();
		richopt = menubox.find(".richopt");
		menu = el.find(".menu");
		menu = menu.size() ? menu : null; // Check for existence of menu
		hide(menubox, richopt, menu);
		valstore = menubox.find(".valstore");
		valstore = valstore.size() ? valstore : null; // Check for existence of valstore
		name = (valstore ? valstore.attr("name") : menu.attr("name"));
		// Event handlers for menu button
		el.click(function(e) {
			var target = $(e.target);
			if(target.is(".menubox label") || target.is("input") || target.is(".removeval")) {
				return;
			}
			if(visible(menu))
				hideMenu();
			else
				showMenu();
			e.stopPropagation(); // Don't let the document close the menu again
		});
		el.jkey('space', function() {
			showMenu();
		});
		// Make into multiline select
		menu.attr("size", menu.children().size());
		// Event handlers keep menu and valstore in sync
		menu.click(function(e) {
			updateValstore();
			// The richselect click handler hides the menu
		});
		menu.change(function(e) {
			updateValstore();
		});
		menu.jkey('enter', function() {
			updateValstore();
			hideMenu();
		});
		// Prevent pressing enter in the menu from submitting the form
		menu.keypress(function(e) {
			if(e.which == 13) e.preventDefault();
		});
		valstore.change(function() {
			updateMenu();
		});
		// Add remove button
		menubox.append($("<img />", {
			src : "remove.png",
			alt : "remove",
			"class" : "removeval",
			click : function() {
				removeVal();
			}
		}));
		// Add dropdown image
		el.append($("<img />", {
			src : "dropdown.png",
			alt : "dropdown"
		}));
		// Public object properties and methods (pretty much everything by now)
		return {
			menu : menu,
			menubox : menubox,
			menutext : menutext,
			valstore : valstore,
			name : name,
			showMenu : showMenu,
			hideMenu : hideMenu,
			getVal : getVal,
			updateMenubox : updateMenubox,
			updateMenu : updateMenu,
			updateValstore : updateValstore,
			removeVal : removeVal
		}
	}
	$(function() {
		// Reset form
		$("form").get(0).reset();
		// Close any open menu
		$(document).click(function() {
			for(var i = 0; i < selects.length; i++) {
				if(visible(selects[i].menu)) selects[i].hideMenu();
			}
		});
	});
	// Array holding all rich menus
	var selects = [];
	// jQuery plugin
	$.richselect = $.richselect || function(selector, callback) {
		var a = [];
		$(selector).each(function(i, el) {
			var select = RichSelect($(el));
			a[a.length] = select;
			selects[select.length] = select;
			if(typeof callback === "function") callback(select);
		});
		return a;
	}
	$.richselect.selects = $.richselect.selects || selects;
})(jQuery);<commit_msg>Set position of menu to below button. Fixed typo.<commit_after>(function($) {
	function changeMultiple(method, arg) {
		// Apply the same method and arg to multiple objects
		return function() {
			var args = arguments;
			if(!args.length) return false; // no args
			for(var i = 0; i < args.length; i++) {
				if(args[i] && args[i][method]) args[i][method](arg);
			}
			return true;
		}
	}
	var show = changeMultiple("removeClass", "jshidden");
	var hide = changeMultiple("addClass", "jshidden");
	var toggle = changeMultiple("toggleClass", "jshidden");
	function visible(el) {
		return (el ? !el.hasClass("jshidden") : null);
	}
	function RichSelect(el) {
		// Object for rich menu functionality
		var name, showmenu, menubox, menutext, richopt, menu, valstore;
		var showMenu = function() {
			var el = menu ? menu : menubox;
			show(el);
			if(menu) {
				menu.focus();
			}
		}
		var hideMenu = function() {
			var el = menu ? menu : menubox;
			hide(el);
			var inputs = richopt.find("input");
			// Select form element for added usability
			if(inputs.size()) {
				inputs.first().select();
			}
		}
		var getVal = function() {
			var val;
			if(valstore) {
				val = valstore.val();
			}
			else {
				var option = menu.children("option:selected");
				if(option.size()) val = option.val();
			}
			return val;
		}
		var updateMenubox = function(option) {
			// Shows selected option. If option is a richopt show that element.
			showmenu.addColon();
			option = option || menu.children("option:selected");
			if(option.hasClass("richopt")) {
				menutext.text("");
				show(richopt, menubox);
			}
			else {
				if(!richopt.hasClass("jshidden")) hide(richopt);
				menutext.text(option.text());
				show(menubox);
			}
		}
		var updateMenu = function() {
			// Update selected menu option from valstore value
			if(!menu) return;
			var option;
			var found = false;
			if(valstore) {
				menu.children().each(function(i, el) {
					option = $(el);
					if(option.val() === valstore.val()) {
						option.attr("selected", "selected");
						found = true;
						return false;
					}
				});
			}
			else {
				option = menu.children("option:selected");
				if(option.size()) found = true;
			}
			if(found) updateMenubox(option);
		}
		var updateValstore = function() {
			// Update valstore from selected menu option
			var option = menu.children("option:selected");
			if(option.size()) {
				updateMenubox(option);
				if(valstore) valstore.val(option.val());
			}
		}
		var removeVal = function() {
			// Remove value and collapse menu button to initial form
			showmenu.removeColon();
			hide(menubox);
			menutext.text("");
			if(valstore) valstore.val("");
			if(menu) {
				menu.get(0).selectedIndex = -1;
				hide(menu);
			}
		}
		showmenu = (function() {
			// Object for manipulating showmenu
			var label = el.find(".showmenu");
			label.click(function(e) {
				e.preventDefault();
			});
			var labeltext;
			function init() {
				labeltext = label.contents().get(0).nodeValue;
			}
			return {
				obj : label,
				addColon : function() {
					// Show colon in label when expanded
					init();
					if(labeltext.indexOf(":") == -1) {
						label.contents().get(0).nodeValue = $.trim(labeltext) + ":";
					}
				},
				removeColon : function() {
					// Remove colon in label when collapsed
					init();
					label.contents().get(0).nodeValue = labeltext.replace(":", "");
				}
			}
		})();
		showmenu.removeColon();
		menubox = el.find(".menubox");
		// Add empty element for holding option text
		menubox.prepend("<span />");
		menutext = menubox.children().first();
		richopt = menubox.find(".richopt");
		menu = el.find(".menu");
		menu = menu.size() ? menu : null; // Check for existence of menu
		// Make into multiline select
		menu.attr("size", menu.children().size());
		hide(menubox, richopt, menu);
		// Set menu to show below button
		menu.css("top", el.innerHeight() - 2);
		valstore = menubox.find(".valstore");
		valstore = valstore.size() ? valstore : null; // Check for existence of valstore
		name = (valstore ? valstore.attr("name") : menu.attr("name"));
		// Event handlers for menu button
		el.click(function(e) {
			var target = $(e.target);
			if(target.is(".menubox label") || target.is("input") || target.is(".removeval")) {
				return;
			}
			if(visible(menu))
				hideMenu();
			else
				showMenu();
			e.stopPropagation(); // Don't let the document close the menu again
		});
		el.jkey('space', function() {
			showMenu();
		});
		// Event handlers keep menu and valstore in sync
		menu.click(function(e) {
			updateValstore();
			// The richselect click handler hides the menu
		});
		menu.change(function(e) {
			updateValstore();
		});
		menu.jkey('enter', function() {
			updateValstore();
			hideMenu();
		});
		// Prevent pressing enter in the menu from submitting the form
		menu.keypress(function(e) {
			if(e.which == 13) e.preventDefault();
		});
		valstore.change(function() {
			updateMenu();
		});
		// Add remove button
		menubox.append($("<img />", {
			src : "remove.png",
			alt : "remove",
			"class" : "removeval",
			click : function() {
				removeVal();
			}
		}));
		// Add dropdown image
		el.append($("<img />", {
			src : "dropdown.png",
			alt : "dropdown"
		}));
		// Public object properties and methods (pretty much everything by now)
		return {
			menu : menu,
			menubox : menubox,
			menutext : menutext,
			valstore : valstore,
			name : name,
			showMenu : showMenu,
			hideMenu : hideMenu,
			getVal : getVal,
			updateMenubox : updateMenubox,
			updateMenu : updateMenu,
			updateValstore : updateValstore,
			removeVal : removeVal
		}
	}
	// Array holding all rich menus
	var selects = [];
	$(function() {
		// Reset form
		$("form").get(0).reset();
		// Close any open menu
		$(document).click(function() {
			for(var i = 0; i < selects.length; i++) {
				if(visible(selects[i].menu)) selects[i].hideMenu();
			}
		});
	});
	// jQuery plugin
	$.richselect = $.richselect || function(selector, callback) {
		var a = [];
		$(selector).each(function(i, el) {
			var select = RichSelect($(el));
			a[a.length] = select;
			selects[selects.length] = select;
			if(typeof callback === "function") callback(select);
		});
		return a;
	}
	$.richselect.selects = $.richselect.selects || selects;
})(jQuery);<|endoftext|>


<commit_before>import test from 'ava';
import { addTodo, toggleTodo } from '../../app/action_creators';
import todos from '../../app/reducers/todos';

// Declare test data
const oneTodo = [{ text: 'first todo', id: 'uuid1', completed: false }];

const twoTodos = [
  { text: 'first todo', id: 'uuid1', completed: false },
  { text: 'second todo', id: 'uuid2', completed: false },
];

// Freeze data to ensure that todos function doesn't mutate input data
Object.freeze(oneTodo);
Object.freeze(twoTodos);

// Prove mutating input data should throw errors
test('mutating frozen data throws error', t => {
  t.throws(() => oneTodo.push({}));
  t.throws(() => twoTodos.push({}));
});

test('addTodo action adds a new todo to list', t => {
  const todoAction = addTodo('first todo');
  const actual = todos([], todoAction);
  t.deepEqual(actual, [{ text: todoAction.text, id: todoAction.id, completed: false }]);
});

test('addTodo action adds a new todo to end of list', t => {
  const todoAction = addTodo('second todo');
  const actual = todos(oneTodo, todoAction);
  const expected = [
    ...oneTodo,
    { text: todoAction.text, id: todoAction.id, completed: false },
  ];

  t.deepEqual(actual, expected);
});

test('toggleTodo action flips completed status of todo with given id', t => {
  const actual = todos(twoTodos, toggleTodo('uuid1'));
  const expected = [
    { text: 'first todo', id: 'uuid1', completed: true },
    { text: 'second todo', id: 'uuid2', completed: false },
  ];

  t.deepEqual(actual, expected);
});
<commit_msg>update tests to fully test action creator logic<commit_after>import test from 'ava';
import { addTodo, toggleTodo } from '../../app/action_creators';
import todos from '../../app/reducers/todos';

// Declare test data
const oneTodo = [{ text: 'first todo', id: 'uuid1', completed: false }];

const twoTodos = [
  { text: 'first todo', id: 'uuid1', completed: false },
  { text: 'second todo', id: 'uuid2', completed: false },
];

// Freeze data to ensure that todos function doesn't mutate input data
Object.freeze(oneTodo);
Object.freeze(twoTodos);

// Prove mutating input data should throw errors
test('mutating frozen data throws error', t => {
  t.throws(() => oneTodo.push({}));
  t.throws(() => twoTodos.push({}));
});

test('addTodo action adds a new todo to list', t => {
  const todoAction = addTodo('first todo');
  const actual = todos([], todoAction);
  t.deepEqual(actual, [{ text: 'first todo', id: todoAction.id, completed: false }]);
});

test('addTodo action adds a new todo to end of list', t => {
  const todoAction = addTodo('second todo');
  const actual = todos(oneTodo, todoAction);
  const expected = [
    ...oneTodo,
    { text: 'second todo', id: todoAction.id, completed: false },
  ];

  t.deepEqual(actual, expected);
});

test('toggleTodo action flips completed status of todo with given id', t => {
  const actual = todos(twoTodos, toggleTodo('uuid1'));
  const expected = [
    { text: 'first todo', id: 'uuid1', completed: true },
    { text: 'second todo', id: 'uuid2', completed: false },
  ];

  t.deepEqual(actual, expected);
});
<|endoftext|>


<commit_before>// was uninspired by the offerings
var grow = (function() {
  var spawn = require("child_process").spawn
      , sys = require('sys')

      , clients = []
      , v8_memory = function() { return sys.inspect(process.memoryUsage()) };

    while (true) {
      clients.push((function() {
        var http = require("http")
          , server = http.createClient("8124");

        return server.request("GET", "/").on("response", function(response) { response.on("end"), function() { request() } });
      })());

      var count = clients.length
        ,  count_output = function() { console.log(v8_memory.heapUsed + " / " + v8_memory.heapTotal + " heap; " + count + " clients ") };

      if (count < 500 && count % 10 == 0) count_output();
      else if (count < 5000 && count % 100 == 0) count_output();
      else if (count < 50000 && count % 1000 == 0) count_output(); // surely 50000 is high
      else count_output();
    }
})();
<commit_msg>fixed major problems with concurrency test, now blowing up around 1000<commit_after>// was uninspired by the offerings
(function() {
  var http = require("http")

    , clients = [];

  while (true) {
    clients.push((function() {
      var request
        , localhost = http.createClient(8124)

      function req() {
        request = localhost.request("GET", "/");
        request.end();

        res();
      }
      function res() {
        request.on("response", function(response) {
          response.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
          });
          console.log(response.statusCode);

          response.on("end", function() {
           req();
          });
        });
      }

      req();
    })());

    var count = clients.length
      , count_output = function() { console.log(count + " clients ") };

    if (count < 500 && count % 10 == 0) count_output();
    else if (count < 5000 && count % 100 == 0) count_output();
    else if (count < 50000 && count % 1000 == 0) count_output(); // surely 50000 is high
    else if (count > 50000) count_output();
  }
})();
<|endoftext|>


<commit_before>exports.tests = [
	{
		css: '.foo body > h2 {}',
		metrics: {
			redundantBodySelectors: 1
		}
	},
	{
		css: 'body ul li a {}',
		metrics: {
			redundantBodySelectors: 1
		}
	},
	{
		css: 'body#foo ul li a {}',
		metrics: {
			redundantBodySelectors: 1
		}
	},
	{
		css: 'body > h1 {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'html > body #foo .bar {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'body {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'body.mainpage {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'body.foo ul li a {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'html.modal-popup-mode body {}',
		metrics: {
			redundantBodySelectors: 0
		}
	}
];
<commit_msg>Add a test case for #49<commit_after>exports.tests = [
	{
		css: '.foo body > h2 {}',
		metrics: {
			redundantBodySelectors: 1
		}
	},
	{
		css: 'body ul li a {}',
		metrics: {
			redundantBodySelectors: 1
		}
	},
	{
		css: 'body#foo ul li a {}',
		metrics: {
			redundantBodySelectors: 1
		}
	},
	{
		css: 'body > h1 {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'html > body #foo .bar {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'body {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'body.mainpage {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'body.foo ul li a {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: 'html.modal-popup-mode body {}',
		metrics: {
			redundantBodySelectors: 0
		}
	},
	{
		css: '.has-modal > body {}',
		metrics: {
			redundantBodySelectors: 0
		}
	}
];
<|endoftext|>


<commit_before>'use strict';

const Promise = require('bluebird');
const request = require('supertest')(TEST.N.config.bind.default.mount);
const assert  = require('assert');
const JSZip   = require('jszip');
const path    = require('path');
const fs      = require('fs');

function binaryParser(res, callback) {
  res.setEncoding('binary');
  res.data = '';
  res.on('data', chunk => {
    res.data += chunk;
  });
  res.on('end', () => {
    callback(null, new Buffer(res.data, 'binary'));
  });
}

describe('API.download', function () {

  it('with custom icon', function () {
    return Promise.resolve()
      .then(() => Promise.fromCallback(cb => request
        .post('/')
        .attach('config', path.join(__dirname, 'fixtures', 'config_custom.json'))
        .set('Accept', 'application/json')
        .expect(200)
        .end(cb)))
      .then(res => Promise.fromCallback(cb => request
        .get(`/${res.text}/get`)
        .expect(200)
        .parse(binaryParser)
        .end(cb)))
      .then(res => {
        let fixture = fs.readFileSync(path.join(__dirname, 'fixtures', 'result_custom.zip'));

        return Promise.all([
          JSZip.loadAsync(res.body)
            .then(zip => zip.file(/fontello-[0-9a-f]+\/font\/fontello\.svg/)[0].async('string')),
          JSZip.loadAsync(fixture)
            .then(zip => zip.file(/fontello-[0-9a-f]+\/font\/fontello\.svg/)[0].async('string'))
        ]);
      })
      .then(values => assert.strictEqual(values[0], values[1]));
  });

  it('with fontelico icon', function () {
    return Promise.resolve()
      .then(() => Promise.fromCallback(cb => request
        .post('/')
        .attach('config', path.join(__dirname, 'fixtures', 'config_fontelico.json'))
        .set('Accept', 'application/json')
        .expect(200)
        .end(cb)))
      .then(res => Promise.fromCallback(cb => request
        .get(`/${res.text}/get`)
        .expect(200)
        .parse(binaryParser)
        .end(cb)))
      .then(res => {
        let fixture = fs.readFileSync(path.join(__dirname, 'fixtures', 'result_fontelico.zip'));

        return Promise.all([
          JSZip.loadAsync(res.body)
            .then(zip => zip.file(/fontello-[0-9a-f]+\/font\/fontello\.svg/)[0].async('string')),
          JSZip.loadAsync(fixture)
            .then(zip => zip.file(/fontello-[0-9a-f]+\/font\/fontello\.svg/)[0].async('string'))
        ]);
      })
      .then(values => assert.strictEqual(values[0], values[1]));
  });
});
<commit_msg>relax api tests - remove copyright year before svg compare<commit_after>'use strict';

const Promise = require('bluebird');
const request = require('supertest')(TEST.N.config.bind.default.mount);
const assert  = require('assert');
const JSZip   = require('jszip');
const path    = require('path');
const fs      = require('fs');

function binaryParser(res, callback) {
  res.setEncoding('binary');
  res.data = '';
  res.on('data', chunk => {
    res.data += chunk;
  });
  res.on('end', () => {
    callback(null, new Buffer(res.data, 'binary'));
  });
}

describe('API.download', function () {

  it('with custom icon', function () {
    return Promise.resolve()
      .then(() => Promise.fromCallback(cb => request
        .post('/')
        .attach('config', path.join(__dirname, 'fixtures', 'config_custom.json'))
        .set('Accept', 'application/json')
        .expect(200)
        .end(cb)))
      .then(res => Promise.fromCallback(cb => request
        .get(`/${res.text}/get`)
        .expect(200)
        .parse(binaryParser)
        .end(cb)))
      .then(res => {
        let fixture = fs.readFileSync(path.join(__dirname, 'fixtures', 'result_custom.zip'));

        return Promise.all([
          JSZip.loadAsync(res.body)
            .then(zip => zip.file(/fontello-[0-9a-f]+\/font\/fontello\.svg/)[0].async('string')),
          JSZip.loadAsync(fixture)
            .then(zip => zip.file(/fontello-[0-9a-f]+\/font\/fontello\.svg/)[0].async('string'))
        ]);
      })
      // copyright year can change, strip it
      .then(values => assert.strictEqual(
        values[0].replace(/<metadata>.+<\/metadata>/, ''),
        values[1].replace(/<metadata>.+<\/metadata>/, ''))
      );
  });

  it('with fontelico icon', function () {
    return Promise.resolve()
      .then(() => Promise.fromCallback(cb => request
        .post('/')
        .attach('config', path.join(__dirname, 'fixtures', 'config_fontelico.json'))
        .set('Accept', 'application/json')
        .expect(200)
        .end(cb)))
      .then(res => Promise.fromCallback(cb => request
        .get(`/${res.text}/get`)
        .expect(200)
        .parse(binaryParser)
        .end(cb)))
      .then(res => {
        let fixture = fs.readFileSync(path.join(__dirname, 'fixtures', 'result_fontelico.zip'));

        return Promise.all([
          JSZip.loadAsync(res.body)
            .then(zip => zip.file(/fontello-[0-9a-f]+\/font\/fontello\.svg/)[0].async('string')),
          JSZip.loadAsync(fixture)
            .then(zip => zip.file(/fontello-[0-9a-f]+\/font\/fontello\.svg/)[0].async('string'))
        ]);
      })
      // copyright year can change, strip it
      .then(values => assert.strictEqual(
        values[0].replace(/<metadata>.+<\/metadata>/, ''),
        values[1].replace(/<metadata>.+<\/metadata>/, ''))
      );
  });
});
<|endoftext|>


<commit_before><commit_msg>Update server.js<commit_after><|endoftext|>