<commit_before>const assert = require('assert');
const helpers = require('./helpers/helpers.js');

const closeAll = helpers.closeAll;
const testTypes = helpers.testTypes;
const createServer = helpers.createServer;
const createHotShotsClient = helpers.createHotShotsClient;

describe('#statsFunctions', () => {
  let server;
  let statsd;

  afterEach(done => {
    closeAll(server, statsd, false, done);
  });

  testTypes().forEach(([description, serverType, clientType, metricsEnd]) => {
    describe(description, () => {
      [{ name: 'timing', unit: 'ms', bytes: 14 },
      { name: 'histogram', unit: 'h', bytes: 12 },
      { name: 'distribution', unit: 'd', bytes: 12 },
      { name: 'gauge', unit: 'g', bytes: 12 },
      { name: 'set', unit: 's', bytes: 12 },
      ].forEach(statFunction => {

        describe(`#${statFunction.name}`, () => {
          it(`should send proper ${statFunction.name} format without prefix, suffix, sampling and callback`, done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(opts, clientType);
              statsd[statFunction.name]('test', 42);
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test:42|${statFunction.unit}${metricsEnd}`);
              done();
            });
          });

          it(`should send proper ${statFunction.name} format with tags`, done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(opts, clientType);
              statsd[statFunction.name]('test', 42, ['foo', 'bar']);
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test:42|${statFunction.unit}|#foo,bar${metricsEnd}`);
              done();
            });
          });

          it(`should send proper ${statFunction.name} format with cacheDns`, done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(Object.assign(opts, {
                cacheDns: true
              }), clientType);
              statsd[statFunction.name]('test', 42, ['foo', 'bar']);
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test:42|${statFunction.unit}|#foo,bar${metricsEnd}`);
              done();
            });
          });

          it(`should send proper ${statFunction.name} format with prefix, suffix, sampling and callback`, done => {
            let called = false;
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(Object.assign(opts, {
                prefix: 'foo.',
                suffix: '.bar',
              }), clientType);
              statsd[statFunction.name]('test', 42, 0.5, () => {
                called = true;
              });
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `foo.test.bar:42|${statFunction.unit}|@0.5${metricsEnd}`);
              assert.equal(called, true);
              done();
            });
          });

          it('should properly send a and b with the same value', done => {
            let called = 0;
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(Object.assign(opts, {
                maxBufferSize: 1000,
                bufferFlushInterval: 5
              }), clientType);
              statsd[statFunction.name](['a', 'b'], 42, null, (error) => {
                called += 1;
                assert.ok(called === 1); // Ensure it only gets called once
                assert.equal(error, null);
              });
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `a:42|${statFunction.unit}\nb:42|${statFunction.unit}\n`);
              done();
            });
          });

          it('should format tags to datadog format by default', done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(opts, clientType);
              statsd[statFunction.name]('test', 42, { foo: 'bar' });
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test:42|${statFunction.unit}|#foo:bar${metricsEnd}`);
              done();
            });
          });

          it('should format tags when using telegraf format', done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(Object.assign(opts, {
                telegraf: true,
              }), clientType);
              statsd[statFunction.name]('test', 42, { foo: 'bar' });
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test,foo=bar:42|${statFunction.unit}${metricsEnd}`);
              done();
            });
          });
        });
      });

      describe('#timing', () => {
        it('should send when no dates are specified', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.timing('test', 1592198027348);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:1592198027348|ms${metricsEnd}`);
            done();
          });
        });
        it('should send when dates are specified', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.timing('test', new Date(Date.now() - 10));
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:10|ms${metricsEnd}`);
            done();
          });
        });
      })

      describe('#increment', () => {
        it('should send count by 1 when no params are specified', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test');
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:1|c${metricsEnd}`);
            done();
          });
        });

        it('should use when increment is 0', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test', 0);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:0|c${metricsEnd}`);
            done();
          });
        });

        it('should send proper count format with tags', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test', 42, ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:42|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send default count 1 with tags', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test', ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:1|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send tags when sampleRate is omitted', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test', 23, ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:23|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send proper count format with prefix, suffix, sampling and callback', done => {
          let called = false;
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(Object.assign(opts, {
              prefix: 'foo.',
              suffix: '.bar',
            }), clientType);
            statsd.increment('test', 42, 0.5, () => {
              called = true;
            });
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `foo.test.bar:42|c|@0.5${metricsEnd}`);
            assert.equal(called, true);
            done();
          });
        });

        it('should properly send a and b with the same value', done => {
          let called = 0;
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(Object.assign(opts, {
              maxBufferSize: 1000,
              bufferFlushInterval: 5
            }), clientType);
            statsd.increment(['a', 'b'], 42, null, (error, bytes) => {
              called += 1;
              assert.ok(called === 1); // Ensure it only gets called once
              assert.equal(error, null);
              assert.equal(bytes, 0);
            });
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, 'a:42|c\nb:42|c\n');
            done();
          });
        });
      });

      describe('#decrement', () => {
        it('should send count by -1 when no params are specified', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.decrement('test');
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:-1|c${metricsEnd}`);
            done();
          });
        });

        it('should send default count -1 with tags', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.decrement('test', ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:-1|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send tags when sampleRate is omitted', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.decrement('test', 23, ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:-23|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send proper count format with tags', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.decrement('test', 42, ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:-42|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send proper count format with prefix, suffix, sampling and callback', done => {
          let called = false;
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(Object.assign(opts, {
              prefix: 'foo.',
              suffix: '.bar',
            }), clientType);
            statsd.decrement('test', 42, 0.5, () => {
              called = true;
            });
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `foo.test.bar:-42|c|@0.5${metricsEnd}`);
            assert.equal(called, true);
            done();
          });
        });

        it('should properly send a and b with the same value', done => {
          let called = 0;
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(Object.assign(opts, {
              maxBufferSize: 1000,
              bufferFlushInterval: 5
            }), clientType);
            statsd.decrement(['a', 'b'], 42, null, (error, bytes) => {
              called += 1;
              assert.ok(called === 1); // Ensure it only gets called once
              assert.equal(error, null);
              assert.equal(bytes, 0);
            });
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, 'a:-42|c\nb:-42|c\n');
            done();
          });
        });
      });
    });
  });
});
<commit_msg>fixed failing tests on windows<commit_after>const assert = require('assert');
const helpers = require('./helpers/helpers.js');

const closeAll = helpers.closeAll;
const testTypes = helpers.testTypes;
const createServer = helpers.createServer;
const createHotShotsClient = helpers.createHotShotsClient;

describe('#statsFunctions', () => {
  let server;
  let statsd;

  afterEach(done => {
    closeAll(server, statsd, false, done);
  });

  testTypes().forEach(([description, serverType, clientType, metricsEnd]) => {
    describe(description, () => {
      [{ name: 'timing', unit: 'ms', bytes: 14 },
      { name: 'histogram', unit: 'h', bytes: 12 },
      { name: 'distribution', unit: 'd', bytes: 12 },
      { name: 'gauge', unit: 'g', bytes: 12 },
      { name: 'set', unit: 's', bytes: 12 },
      ].forEach(statFunction => {

        describe(`#${statFunction.name}`, () => {
          it(`should send proper ${statFunction.name} format without prefix, suffix, sampling and callback`, done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(opts, clientType);
              statsd[statFunction.name]('test', 42);
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test:42|${statFunction.unit}${metricsEnd}`);
              done();
            });
          });

          it(`should send proper ${statFunction.name} format with tags`, done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(opts, clientType);
              statsd[statFunction.name]('test', 42, ['foo', 'bar']);
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test:42|${statFunction.unit}|#foo,bar${metricsEnd}`);
              done();
            });
          });

          it(`should send proper ${statFunction.name} format with cacheDns`, done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(Object.assign(opts, {
                cacheDns: true
              }), clientType);
              statsd[statFunction.name]('test', 42, ['foo', 'bar']);
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test:42|${statFunction.unit}|#foo,bar${metricsEnd}`);
              done();
            });
          });

          it(`should send proper ${statFunction.name} format with prefix, suffix, sampling and callback`, done => {
            let called = false;
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(Object.assign(opts, {
                prefix: 'foo.',
                suffix: '.bar',
              }), clientType);
              statsd[statFunction.name]('test', 42, 0.5, () => {
                called = true;
              });
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `foo.test.bar:42|${statFunction.unit}|@0.5${metricsEnd}`);
              assert.equal(called, true);
              done();
            });
          });

          it('should properly send a and b with the same value', done => {
            let called = 0;
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(Object.assign(opts, {
                maxBufferSize: 1000,
                bufferFlushInterval: 5
              }), clientType);
              statsd[statFunction.name](['a', 'b'], 42, null, (error) => {
                called += 1;
                assert.ok(called === 1); // Ensure it only gets called once
                assert.equal(error, null);
              });
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `a:42|${statFunction.unit}\nb:42|${statFunction.unit}\n`);
              done();
            });
          });

          it('should format tags to datadog format by default', done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(opts, clientType);
              statsd[statFunction.name]('test', 42, { foo: 'bar' });
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test:42|${statFunction.unit}|#foo:bar${metricsEnd}`);
              done();
            });
          });

          it('should format tags when using telegraf format', done => {
            server = createServer(serverType, opts => {
              statsd = createHotShotsClient(Object.assign(opts, {
                telegraf: true,
              }), clientType);
              statsd[statFunction.name]('test', 42, { foo: 'bar' });
            });
            server.on('metrics', metrics => {
              assert.equal(metrics, `test,foo=bar:42|${statFunction.unit}${metricsEnd}`);
              done();
            });
          });
        });
      });

      describe('#timing', () => {
        it('should send when no dates are specified', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.timing('test', 1592198027348);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:1592198027348|ms${metricsEnd}`);
            done();
          });
        });
        it('should send when dates are specified', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.timing('test', new Date(Date.now() - 10));
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:10|ms${metricsEnd}`);
            done();
          });
        });
      });

      describe('#increment', () => {
        it('should send count by 1 when no params are specified', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test');
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:1|c${metricsEnd}`);
            done();
          });
        });

        it('should use when increment is 0', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test', 0);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:0|c${metricsEnd}`);
            done();
          });
        });

        it('should send proper count format with tags', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test', 42, ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:42|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send default count 1 with tags', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test', ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:1|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send tags when sampleRate is omitted', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.increment('test', 23, ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:23|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send proper count format with prefix, suffix, sampling and callback', done => {
          let called = false;
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(Object.assign(opts, {
              prefix: 'foo.',
              suffix: '.bar',
            }), clientType);
            statsd.increment('test', 42, 0.5, () => {
              called = true;
            });
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `foo.test.bar:42|c|@0.5${metricsEnd}`);
            assert.equal(called, true);
            done();
          });
        });

        it('should properly send a and b with the same value', done => {
          let called = 0;
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(Object.assign(opts, {
              maxBufferSize: 1000,
              bufferFlushInterval: 5
            }), clientType);
            statsd.increment(['a', 'b'], 42, null, (error, bytes) => {
              called += 1;
              assert.ok(called === 1); // Ensure it only gets called once
              assert.equal(error, null);
              assert.equal(bytes, 0);
            });
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, 'a:42|c\nb:42|c\n');
            done();
          });
        });
      });

      describe('#decrement', () => {
        it('should send count by -1 when no params are specified', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.decrement('test');
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:-1|c${metricsEnd}`);
            done();
          });
        });

        it('should send default count -1 with tags', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.decrement('test', ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:-1|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send tags when sampleRate is omitted', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.decrement('test', 23, ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:-23|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send proper count format with tags', done => {
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(opts, clientType);
            statsd.decrement('test', 42, ['foo', 'bar']);
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `test:-42|c|#foo,bar${metricsEnd}`);
            done();
          });
        });

        it('should send proper count format with prefix, suffix, sampling and callback', done => {
          let called = false;
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(Object.assign(opts, {
              prefix: 'foo.',
              suffix: '.bar',
            }), clientType);
            statsd.decrement('test', 42, 0.5, () => {
              called = true;
            });
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, `foo.test.bar:-42|c|@0.5${metricsEnd}`);
            assert.equal(called, true);
            done();
          });
        });

        it('should properly send a and b with the same value', done => {
          let called = 0;
          server = createServer(serverType, opts => {
            statsd = createHotShotsClient(Object.assign(opts, {
              maxBufferSize: 1000,
              bufferFlushInterval: 5
            }), clientType);
            statsd.decrement(['a', 'b'], 42, null, (error, bytes) => {
              called += 1;
              assert.ok(called === 1); // Ensure it only gets called once
              assert.equal(error, null);
              assert.equal(bytes, 0);
            });
          });
          server.on('metrics', metrics => {
            assert.equal(metrics, 'a:-42|c\nb:-42|c\n');
            done();
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>// Cribbed from the ever prolific Konstantin Kaefer
// https://github.com/mapbox/tilelive-mapnik/blob/master/test/support/assert.js

var exec = require('child_process').exec,
    fs = require('fs'),
    http = require('http'),
    path = require('path'),
    util = require('util');

var assert = module.exports = exports = require('assert');

/**
 * Takes an image data as an input and an image path and compare them using ImageMagick fuzz algorithm, if case the
 * similarity is not within the tolerance limit it will callback with an error.
 *
 * @param buffer The image data to compare from
 * @param {string} referenceImageRelativeFilePath The relative file to compare against
 * @param {number} tolerance tolerated mean color distance, as a per mil (‰)
 * @param {function} callback Will call to home with null in case there is no error, otherwise with the error itself
 * @see FUZZY in http://www.imagemagick.org/script/command-line-options.php#metric
 */
assert.imageEqualsFile = function(buffer, referenceImageRelativeFilePath, tolerance, callback) {
    if (!callback) callback = function(err) { if (err) throw err; };
    var referenceImageFilePath = path.resolve(referenceImageRelativeFilePath),
        testImageFilePath = createImageFromBuffer(buffer, 'test');

    imageFilesAreEqual(testImageFilePath, referenceImageFilePath, tolerance, function(err) {
        fs.unlinkSync(testImageFilePath);
        callback(err);
    });
};

assert.imageBuffersAreEqual = function(bufferA, bufferB, tolerance, callback) {
    var randStr = (Math.random() * 1e16).toString().substring(0, 8);
    var imageFilePathA = createImageFromBuffer(bufferA, randStr + '-a'),
        imageFilePathB = createImageFromBuffer(bufferB, randStr + '-b');

    imageFilesAreEqual(imageFilePathA, imageFilePathB, tolerance, function(err, similarity) {
        callback(err, [imageFilePathA, imageFilePathB], similarity);
    });
};

function createImageFromBuffer(buffer, nameHint) {
    var imageFilePath = path.resolve('test/results/png/image-' + nameHint + '-' + Date.now() + '.png');
    var err = fs.writeFileSync(imageFilePath, buffer, 'binary');
    if (err) throw err;
    return imageFilePath;
}

function imageFilesAreEqual(testImageFilePath, referenceImageFilePath, tolerance, callback) {
    var resultFilePath = path.resolve(util.format('/tmp/windshaft-result-%s-diff.png', Date.now()));
    var imageMagickCmd = util.format(
        'compare -metric fuzz "%s" "%s" "%s"',
        testImageFilePath, referenceImageFilePath, resultFilePath
    );

    exec(imageMagickCmd, function(err, stdout, stderr) {
        if (err) {
            fs.unlinkSync(testImageFilePath);
            callback(err);
        } else {
            stderr = stderr.trim();
            var metrics = stderr.match(/([0-9]*) \((.*)\)/);
            if ( ! metrics ) {
              callback(new Error("No match for " + stderr));
              return;
            }
            var similarity = parseFloat(metrics[2]),
                tolerancePerMil = (tolerance / 1000);
            if (similarity > tolerancePerMil) {
                err = new Error(util.format(
                    'Images %s and %s are not equal (got %d similarity, expected %d). Result %s',
                    testImageFilePath, referenceImageFilePath, similarity, tolerancePerMil, resultFilePath)
                );
                err.similarity = similarity;
                callback(err, similarity);
            } else {
                fs.unlinkSync(resultFilePath);
                callback(null, similarity);
            }
        }
    });
}

/**
 * Assert response from `server` with
 * the given `req` object and `res` assertions object.
 *
 * @param {Server} server
 * @param {Object} req
 * @param {Object|Function} res
 * @param {String|Function} msg
 */
assert.response = function(server, req, res, msg){
    var port = 5555;
    function check(){
        try {
            server.__port = server.address().port;
            server.__listening = true;
        } catch (err) {
            process.nextTick(check);
            return;
        }
        if (server.__deferred) {
            server.__deferred.forEach(function(args){
                assert.response.apply(assert, args);
            });
            server.__deferred = null;
        }
    }

    // Check that the server is ready or defer
    if (!server.fd) {
        server.__deferred = server.__deferred || [];
        server.listen(server.__port = port++, '127.0.0.1', check);
    } else if (!server.__port) {
        server.__deferred = server.__deferred || [];
        process.nextTick(check);
    }

    // The socket was created but is not yet listening, so keep deferring
    if (!server.__listening) {
        server.__deferred.push(arguments);
        return;
    }

    // Callback as third or fourth arg
    var callback = typeof res === 'function'
        ? res
        : typeof msg === 'function'
            ? msg
            : function(){};

    // Default messate to test title
    if (typeof msg === 'function') msg = null;
    msg = msg || assert.testTitle;
    msg += '. ';

    // Pending responses
    server.__pending = server.__pending || 0;
    server.__pending++;

    // Create client
    if (!server.fd) {
        server.listen(server.__port = port++, '127.0.0.1', issue);
    } else {
        issue();
    }

    function issue(){

        // Issue request
        var timer,
            method = req.method || 'GET',
            status = res.status || res.statusCode,
            data = req.data || req.body,
            requestTimeout = req.timeout || 0,
            encoding = req.encoding || 'utf8';

        var request = http.request({
            host: '127.0.0.1',
            port: server.__port,
            path: req.url,
            method: method,
            headers: req.headers
        });

        var check = function() {
            if (--server.__pending === 0) {
                server.close();
                server.__listening = false;
            }
        };

        // Timeout
        if (requestTimeout) {
            timer = setTimeout(function(){
                check();
                delete req.timeout;
                assert.fail(msg + 'Request timed out after ' + requestTimeout + 'ms.');
            }, requestTimeout);
        }

        if (data) request.write(data);

        request.on('response', function(response){
            response.body = '';
            response.setEncoding(encoding);
            response.on('data', function(chunk){ response.body += chunk; });
            response.on('end', function(){
                if (timer) clearTimeout(timer);

                check();

                // Assert response body
                if (res.body !== undefined) {
                    var eql = res.body instanceof RegExp
                      ? res.body.test(response.body)
                      : res.body === response.body;
                    assert.ok(
                        eql,
                        msg + 'Invalid response body.\n'
                            + '    Expected: ' + res.body + '\n'
                            + '    Got: ' + response.body
                    );
                }

                // Assert response status
                if (typeof status === 'number') {
                    assert.equal(
                        response.statusCode,
                        status,
                        msg + 'Invalid response status code.\n'
                            + '    Expected: [green]{' + status + '}\n'
                            + '    Got: [red]{' + response.statusCode + '}'
                    );
                }

                // Assert response headers
                if (res.headers) {
                    var keys = Object.keys(res.headers);
                    for (var i = 0, len = keys.length; i < len; ++i) {
                        var name = keys[i],
                            actual = response.headers[name.toLowerCase()],
                            expected = res.headers[name],
                            eql = expected instanceof RegExp
                              ? expected.test(actual)
                              : expected == actual;
                        assert.ok(
                            eql,
                            msg + 'Invalid response header [bold]{' + name + '}.\n'
                                + '    Expected: [green]{' + expected + '}\n'
                                + '    Got: [red]{' + actual + '}'
                        );
                    }
                }

                // Callback
                callback(response);
            });
        });

        request.end();
      }
};

// @param tolerance number of tolerated grid cell differences
assert.utfgridEqualsFile = function(buffer, file_b, tolerance, callback) {
    fs.writeFileSync('/tmp/grid.json', buffer, 'binary'); // <-- to debug/update
    var expected_json = JSON.parse(fs.readFileSync(file_b, 'utf8'));

    var err = null;

    var Celldiff = function(x, y, ev, ov) {
      this.x = x;
      this.y = y;
      this.ev = ev;
      this.ov = ov;
    };

    Celldiff.prototype.toString = function() {
      return '(' + this.x + ',' + this.y + ')["' + this.ev + '" != "' + this.ov + '"]';
    };

    try {
      var obtained_json = JSON.parse(buffer);

      // compare grid
      var obtained_grid = obtained_json.grid;
      var expected_grid = expected_json.grid;
      var nrows = obtained_grid.length
      if (nrows != expected_grid.length) {
        throw new Error( "Obtained grid rows (" + nrows +
                    ") != expected grid rows (" + expected_grid.length + ")" );
      }
      var celldiff = [];
      for (var i=0; i<nrows; ++i) {
        var ocols = obtained_grid[i];
        var ecols = expected_grid[i];
        var ncols = ocols.length;
        if ( ncols != ecols.length ) {
          throw new Error( "Obtained grid cols (" + ncols +
                   ") != expected grid cols (" + ecols.length +
                   ") on row " + i );
        }
        for (var j=0; j<ncols; ++j) {
          var ocell = ocols[j];
          var ecell = ecols[j];
          if ( ocell !== ecell ) {
            celldiff.push(new Celldiff(i, j, ecell, ocell));
          }
        }
      }

      if ( celldiff.length > tolerance ) {
        throw new Error( celldiff.length + " cell differences: " + celldiff );
      }

      assert.deepEqual(obtained_json.keys, expected_json.keys);
    } catch (e) { err = e; }

    callback(err);
};

<commit_msg>Improve feedback in tests<commit_after>// Cribbed from the ever prolific Konstantin Kaefer
// https://github.com/mapbox/tilelive-mapnik/blob/master/test/support/assert.js

var exec = require('child_process').exec,
    fs = require('fs'),
    http = require('http'),
    path = require('path'),
    util = require('util');

var assert = module.exports = exports = require('assert');

/**
 * Takes an image data as an input and an image path and compare them using ImageMagick fuzz algorithm, if case the
 * similarity is not within the tolerance limit it will callback with an error.
 *
 * @param buffer The image data to compare from
 * @param {string} referenceImageRelativeFilePath The relative file to compare against
 * @param {number} tolerance tolerated mean color distance, as a per mil (‰)
 * @param {function} callback Will call to home with null in case there is no error, otherwise with the error itself
 * @see FUZZY in http://www.imagemagick.org/script/command-line-options.php#metric
 */
assert.imageEqualsFile = function(buffer, referenceImageRelativeFilePath, tolerance, callback) {
    if (!callback) callback = function(err) { if (err) throw err; };
    var referenceImageFilePath = path.resolve(referenceImageRelativeFilePath),
        testImageFilePath = createImageFromBuffer(buffer, 'test');

    imageFilesAreEqual(testImageFilePath, referenceImageFilePath, tolerance, function(err) {
        fs.unlinkSync(testImageFilePath);
        callback(err);
    });
};

assert.imageBuffersAreEqual = function(bufferA, bufferB, tolerance, callback) {
    var randStr = (Math.random() * 1e16).toString().substring(0, 8);
    var imageFilePathA = createImageFromBuffer(bufferA, randStr + '-a'),
        imageFilePathB = createImageFromBuffer(bufferB, randStr + '-b');

    imageFilesAreEqual(imageFilePathA, imageFilePathB, tolerance, function(err, similarity) {
        callback(err, [imageFilePathA, imageFilePathB], similarity);
    });
};

function createImageFromBuffer(buffer, nameHint) {
    var imageFilePath = path.resolve('test/results/png/image-' + nameHint + '-' + Date.now() + '.png');
    var err = fs.writeFileSync(imageFilePath, buffer, 'binary');
    if (err) throw err;
    return imageFilePath;
}

function imageFilesAreEqual(testImageFilePath, referenceImageFilePath, tolerance, callback) {
    var resultFilePath = path.resolve(util.format('/tmp/windshaft-result-%s-diff.png', Date.now()));
    var imageMagickCmd = util.format(
        'compare -metric fuzz "%s" "%s" "%s"',
        testImageFilePath, referenceImageFilePath, resultFilePath
    );

    exec(imageMagickCmd, function(err, stdout, stderr) {
        if (err) {
            fs.unlinkSync(testImageFilePath);
            callback(err);
        } else {
            stderr = stderr.trim();
            var metrics = stderr.match(/([0-9]*) \((.*)\)/);
            if ( ! metrics ) {
              callback(new Error("No match for " + stderr));
              return;
            }
            var similarity = parseFloat(metrics[2]),
                tolerancePerMil = (tolerance / 1000);
            if (similarity > tolerancePerMil) {
                err = new Error(util.format(
                    'Images %s and %s are not equal (got %d similarity, expected %d). Result %s',
                    testImageFilePath, referenceImageFilePath, similarity, tolerancePerMil, resultFilePath)
                );
                err.similarity = similarity;
                callback(err, similarity);
            } else {
                fs.unlinkSync(resultFilePath);
                callback(null, similarity);
            }
        }
    });
}

/**
 * Assert response from `server` with
 * the given `req` object and `res` assertions object.
 *
 * @param {Server} server
 * @param {Object} req
 * @param {Object|Function} res
 * @param {String|Function} msg
 */
assert.response = function(server, req, res, msg){
    var port = 5555;
    function check(){
        try {
            server.__port = server.address().port;
            server.__listening = true;
        } catch (err) {
            process.nextTick(check);
            return;
        }
        if (server.__deferred) {
            server.__deferred.forEach(function(args){
                assert.response.apply(assert, args);
            });
            server.__deferred = null;
        }
    }

    // Check that the server is ready or defer
    if (!server.fd) {
        server.__deferred = server.__deferred || [];
        server.listen(server.__port = port++, '127.0.0.1', check);
    } else if (!server.__port) {
        server.__deferred = server.__deferred || [];
        process.nextTick(check);
    }

    // The socket was created but is not yet listening, so keep deferring
    if (!server.__listening) {
        server.__deferred.push(arguments);
        return;
    }

    // Callback as third or fourth arg
    var callback = typeof res === 'function'
        ? res
        : typeof msg === 'function'
            ? msg
            : function(){};

    // Default messate to test title
    if (typeof msg === 'function') msg = null;
    msg = msg || assert.testTitle;
    msg += '. ';

    // Pending responses
    server.__pending = server.__pending || 0;
    server.__pending++;

    // Create client
    if (!server.fd) {
        server.listen(server.__port = port++, '127.0.0.1', issue);
    } else {
        issue();
    }

    function issue(){

        // Issue request
        var timer,
            method = req.method || 'GET',
            status = res.status || res.statusCode,
            data = req.data || req.body,
            requestTimeout = req.timeout || 0,
            encoding = req.encoding || 'utf8';

        var request = http.request({
            host: '127.0.0.1',
            port: server.__port,
            path: req.url,
            method: method,
            headers: req.headers
        });

        var check = function() {
            if (--server.__pending === 0) {
                server.close();
                server.__listening = false;
            }
        };

        // Timeout
        if (requestTimeout) {
            timer = setTimeout(function(){
                check();
                delete req.timeout;
                assert.fail(msg + 'Request timed out after ' + requestTimeout + 'ms.');
            }, requestTimeout);
        }

        if (data) request.write(data);

        request.on('response', function(response){
            response.body = '';
            response.setEncoding(encoding);
            response.on('data', function(chunk){ response.body += chunk; });
            response.on('end', function(){
                if (timer) clearTimeout(timer);

                check();

                // Assert response body
                if (res.body !== undefined) {
                    var eql = res.body instanceof RegExp
                      ? res.body.test(response.body)
                      : res.body === response.body;
                    assert.ok(
                        eql,
                        msg + colorize('[red]{Invalid response body.}\n'
                            + '    Expected: [green]{' + res.body + '}\n'
                            + '    Got: [red]{' + response.body + '}')
                    );
                }

                // Assert response status
                if (typeof status === 'number') {
                    assert.equal(
                        response.statusCode,
                        status,
                        msg + colorize('[red]{Invalid response status code.}\n'
                            + '    Expected: [green]{' + status + '}\n'
                            + '    Got: [red]{' + response.statusCode + '}')
                    );
                }

                // Assert response headers
                if (res.headers) {
                    var keys = Object.keys(res.headers);
                    for (var i = 0, len = keys.length; i < len; ++i) {
                        var name = keys[i],
                            actual = response.headers[name.toLowerCase()],
                            expected = res.headers[name],
                            eql = expected instanceof RegExp
                              ? expected.test(actual)
                              : expected == actual;
                        assert.ok(
                            eql,
                            msg + colorize('Invalid response header [bold]{' + name + '}.\n'
                                + '    Expected: [green]{' + expected + '}\n'
                                + '    Got: [red]{' + actual + '}')
                        );
                    }
                }

                // Callback
                callback(response);
            });
        });

        request.end();
      }
};

// @param tolerance number of tolerated grid cell differences
assert.utfgridEqualsFile = function(buffer, file_b, tolerance, callback) {
    fs.writeFileSync('/tmp/grid.json', buffer, 'binary'); // <-- to debug/update
    var expected_json = JSON.parse(fs.readFileSync(file_b, 'utf8'));

    var err = null;

    var Celldiff = function(x, y, ev, ov) {
      this.x = x;
      this.y = y;
      this.ev = ev;
      this.ov = ov;
    };

    Celldiff.prototype.toString = function() {
      return '(' + this.x + ',' + this.y + ')["' + this.ev + '" != "' + this.ov + '"]';
    };

    try {
      var obtained_json = JSON.parse(buffer);

      // compare grid
      var obtained_grid = obtained_json.grid;
      var expected_grid = expected_json.grid;
      var nrows = obtained_grid.length
      if (nrows != expected_grid.length) {
        throw new Error( "Obtained grid rows (" + nrows +
                    ") != expected grid rows (" + expected_grid.length + ")" );
      }
      var celldiff = [];
      for (var i=0; i<nrows; ++i) {
        var ocols = obtained_grid[i];
        var ecols = expected_grid[i];
        var ncols = ocols.length;
        if ( ncols != ecols.length ) {
          throw new Error( "Obtained grid cols (" + ncols +
                   ") != expected grid cols (" + ecols.length +
                   ") on row " + i );
        }
        for (var j=0; j<ncols; ++j) {
          var ocell = ocols[j];
          var ecell = ecols[j];
          if ( ocell !== ecell ) {
            celldiff.push(new Celldiff(i, j, ecell, ocell));
          }
        }
      }

      if ( celldiff.length > tolerance ) {
        throw new Error( celldiff.length + " cell differences: " + celldiff );
      }

      assert.deepEqual(obtained_json.keys, expected_json.keys);
    } catch (e) { err = e; }

    callback(err);
};

/**
 * Colorize the given string using ansi-escape sequences.
 * Disabled when --boring is set.
 *
 * @param {String} str
 * @return {String}
 */
function colorize(str) {
    var colors = { bold: 1, red: 31, green: 32, yellow: 33 };
    return str.replace(/\[(\w+)\]\{([^]*?)\}/g, function(_, color, str) {
        return '\x1B[' + colors[color] + 'm' + str + '\x1B[0m';
    });
}
<|endoftext|>


<commit_before>var assert = module.exports = exports = require('assert');
var request = require('request');
var debug = require('debug')('assert-response');

assert.response = function(server, req, res, callback) {
    if (!callback) {
        callback = res;
        res = {};
    }

    var port = 5555,
        host = '127.0.0.1';

    var listeningAttempts = 0;
    var listener;
    function listen() {
        if (listeningAttempts > 25) {
            var message = 'Tried too many ports';
            debug(message);
            return callback(new Error(message));
        }
        listener = server.listen(port, host);
        listener.on('error', function() {
            port++;
            listeningAttempts++;
            listen();
        });
        listener.on('listening', onServerListening);
    }

    listen();

    debug('Request definition', req);

    // jshint maxcomplexity:10
    function onServerListening() {
        debug('Server listening on port = %d', port);
        var status = res.status || res.statusCode;
        var requestParams = {
            url: 'http://' + host + ':' + port + req.url,
            method: req.method || 'GET',
            headers: req.headers || {},
            timeout: req.timeout || 5000,
            encoding: req.encoding || 'utf8'
        };

        if (req.body || req.data) {
            requestParams.body = req.body || req.data;
        }

        debug('Request params', requestParams);
        request(requestParams, function assert$response$requestHandler(error, response, body) {
            debug('Request response', error);
            listener.close(function() {
                debug('Server closed');
                if (error) {
                    return callback(error);
                }

                response = response || {};
                response.body = response.body || body;
                debug('Response status', response.statusCode)

                // Assert response body
                if (res.body) {
                    var eql = res.body instanceof RegExp ? res.body.test(response.body) : res.body === response.body;
                    assert.ok(
                        eql,
                        colorize('[red]{Invalid response body.}\n' +
                            '     Expected: [green]{' + res.body + '}\n' +
                            '     Got: [red]{' + response.body + '}')
                    );
                }

                // Assert response status
                if (typeof status === 'number') {
                    assert.equal(response.statusCode, status,
                        colorize('[red]{Invalid response status code.}\n' +
                            '     Expected: [green]{' + status + '}\n' +
                            '     Got: [red]{' + response.statusCode + '}\n' +
                            '     Body: ' + response.body)
                    );
                }

                // Assert response headers
                if (res.headers) {
                    var keys = Object.keys(res.headers);
                    for (var i = 0, len = keys.length; i < len; ++i) {
                        var name = keys[i],
                            actual = response.headers[name.toLowerCase()],
                            expected = res.headers[name],
                            headerEql = expected instanceof RegExp ? expected.test(actual) : expected === actual;
                        assert.ok(headerEql,
                            colorize('Invalid response header [bold]{' + name + '}.\n' +
                                '     Expected: [green]{' + expected + '}\n' +
                                '     Got: [red]{' + actual + '}')
                        );
                    }
                }

                // Callback
                return callback(null, response);
            });
        });

    }
};

/**
 * Colorize the given string using ansi-escape sequences.
 * Disabled when --boring is set.
 *
 * @param {String} str
 * @return {String}
 */
function colorize(str) {
    var colors = { bold: 1, red: 31, green: 32, yellow: 33 };
    return str.replace(/\[(\w+)\]\{([^]*?)\}/g, function(_, color, str) {
        return '\x1B[' + colors[color] + 'm' + str + '\x1B[0m';
    });
}
<commit_msg>supporting multipart requests<commit_after>var assert = module.exports = exports = require('assert');
var request = require('request');
var debug = require('debug')('assert-response');

assert.response = function(server, req, res, callback) {
    if (!callback) {
        callback = res;
        res = {};
    }

    var port = 5555,
        host = '127.0.0.1';

    var listeningAttempts = 0;
    var listener;
    function listen() {
        if (listeningAttempts > 25) {
            var message = 'Tried too many ports';
            debug(message);
            return callback(new Error(message));
        }
        listener = server.listen(port, host);
        listener.on('error', function() {
            port++;
            listeningAttempts++;
            listen();
        });
        listener.on('listening', onServerListening);
    }

    listen();

    debug('Request definition', req);

    // jshint maxcomplexity:10
    function onServerListening() {
        debug('Server listening on port = %d', port);
        var status = res.status || res.statusCode;
        var requestParams = {
            url: 'http://' + host + ':' + port + req.url,
            method: req.method || 'GET',
            headers: req.headers || {},
            timeout: req.timeout || 5000,
            encoding: req.encoding || 'utf8'
        };

        if (req.body || req.data) {
            requestParams.body = req.body || req.data;
        }

        if (req.formData) {
            requestParams.formData = req.formData;
        }

        debug('Request params', requestParams);
        request(requestParams, function assert$response$requestHandler(error, response, body) {
            debug('Request response', error);
            listener.close(function() {
                debug('Server closed');
                if (error) {
                    return callback(error);
                }

                response = response || {};
                response.body = response.body || body;
                debug('Response status', response.statusCode)

                // Assert response body
                if (res.body) {
                    var eql = res.body instanceof RegExp ? res.body.test(response.body) : res.body === response.body;
                    assert.ok(
                        eql,
                        colorize('[red]{Invalid response body.}\n' +
                            '     Expected: [green]{' + res.body + '}\n' +
                            '     Got: [red]{' + response.body + '}')
                    );
                }

                // Assert response status
                if (typeof status === 'number') {
                    assert.equal(response.statusCode, status,
                        colorize('[red]{Invalid response status code.}\n' +
                            '     Expected: [green]{' + status + '}\n' +
                            '     Got: [red]{' + response.statusCode + '}\n' +
                            '     Body: ' + response.body)
                    );
                }

                // Assert response headers
                if (res.headers) {
                    var keys = Object.keys(res.headers);
                    for (var i = 0, len = keys.length; i < len; ++i) {
                        var name = keys[i],
                            actual = response.headers[name.toLowerCase()],
                            expected = res.headers[name],
                            headerEql = expected instanceof RegExp ? expected.test(actual) : expected === actual;
                        assert.ok(headerEql,
                            colorize('Invalid response header [bold]{' + name + '}.\n' +
                                '     Expected: [green]{' + expected + '}\n' +
                                '     Got: [red]{' + actual + '}')
                        );
                    }
                }

                // Callback
                return callback(null, response);
            });
        });

    }
};

/**
 * Colorize the given string using ansi-escape sequences.
 * Disabled when --boring is set.
 *
 * @param {String} str
 * @return {String}
 */
function colorize(str) {
    var colors = { bold: 1, red: 31, green: 32, yellow: 33 };
    return str.replace(/\[(\w+)\]\{([^]*?)\}/g, function(_, color, str) {
        return '\x1B[' + colors[color] + 'm' + str + '\x1B[0m';
    });
}
<|endoftext|>


<commit_before>var helper = require('./test-helper')
  , Taggifier = helper.Taggifier

describe('Taggifier', function() {
  describe('#process', function() {
    var taggifier

    beforeEach(function() {
      taggifier = new Taggifier({ className: 'a', idPrefix: 'b', tag: 'div' })
    })

    afterEach(function() {
      taggifier.end()
    })

    it('should surround text and white space with tags', function() {
      var htmlPromise = taggifier.process('This is cool')

      return htmlPromise.should.become('
This

is

cool
')
    })

    it('should traverse elements surrounded by text', function() {
      var htmlPromise = taggifier.process('This is so cool')

      return htmlPromise.should.become('
This

is

so

cool
')
    })

    it('should not mess with non body nodes', function() {
      var htmlPromise = taggifier.process('<title>Hello</title>')

      return htmlPromise.should.become("<title>Hello</title>")
    })

    it('should process inner tags with class names', function() {
      var htmlPromise = taggifier.process('
42
')

      return htmlPromise.should.become('

42

')
    })

    it('should allow the index to be overridden to 1', function() {
      var htmlPromise = new Taggifier({ className: 'a', idPrefix: 'b', tag: 'div', start: 1 }).process('Hi')

      return htmlPromise.should.become('
Hi
')
    })

    it('should retain the order of elements', function() {
      var htmlPromise = taggifier.process('
Hi

There

God
')

      return htmlPromise.should.become('

Hi

There

God

')
    })

    it('should retain the order of elements under other elements', function() {
      var htmlPromise = taggifier.process('

Hi

God

')

      return htmlPromise.should.become('

Hi

God

')
    })

    it('should handle non breaking space', function() {
      var htmlPromise = taggifier.process(' 42  ')

      return htmlPromise.should.become('

42

')
    })

    it('should handle new lines', function() {
      var htmlPromise = taggifier.process('42\r\n42')

      return htmlPromise.should.become('
42

42
')
    })

    it('should handle multiple spaces at the start', function() {
      var htmlPromise = taggifier.process('  42')

      return htmlPromise.should.become('

42
')
    })

    it('should handle multiple spaces between words', function() {
      var htmlPromise = taggifier.process('42  42')

      return htmlPromise.should.become('
42

42
')
    })

    it('should handle multiple spaces at the end', function() {
      var htmlPromise = taggifier.process('42  ')

      return htmlPromise.should.become('
42

')
    })

    it('should handle  ', function() {
      var htmlPromise = taggifier.process('  42')

      return htmlPromise.should.become('

42
')
    })

    it('should handle html escape sequences', function() {
      var htmlPromise = taggifier.process('This < and that >')

      return htmlPromise.should.become('
This

<

and

that

>
')
    })

    it('should handle a text node with only white space', function() {
      var htmlPromise = taggifier.process('
Hello

World
')

      return htmlPromise.should.become('

Hello

World

')
    })
  })
})
<commit_msg>taggifier-test.js: Reorder tests<commit_after>var helper = require('./test-helper')
  , Taggifier = helper.Taggifier

describe('Taggifier', function() {
  describe('#process', function() {
    var taggifier

    beforeEach(function() {
      taggifier = new Taggifier({ className: 'a', idPrefix: 'b', tag: 'div' })
    })

    afterEach(function() {
      taggifier.end()
    })

    it('should surround text and white space with tags', function() {
      var htmlPromise = taggifier.process('This is cool')

      return htmlPromise.should.become('
This

is

cool
')
    })

    it('should traverse elements surrounded by text', function() {
      var htmlPromise = taggifier.process('This is so cool')

      return htmlPromise.should.become('
This

is

so

cool
')
    })

    it('should not mess with non body nodes', function() {
      var htmlPromise = taggifier.process('<title>Hello</title>')

      return htmlPromise.should.become("<title>Hello</title>")
    })

    it('should process inner tags with class names', function() {
      var htmlPromise = taggifier.process('
42
')

      return htmlPromise.should.become('

42

')
    })

    it('should allow the index to be overridden to 1', function() {
      var htmlPromise = new Taggifier({ className: 'a', idPrefix: 'b', tag: 'div', start: 1 }).process('Hi')

      return htmlPromise.should.become('
Hi
')
    })

    it('should retain the order of elements', function() {
      var htmlPromise = taggifier.process('
Hi

There

God
')

      return htmlPromise.should.become('

Hi

There

God

')
    })

    it('should retain the order of elements under other elements', function() {
      var htmlPromise = taggifier.process('

Hi

God

')

      return htmlPromise.should.become('

Hi

God

')
    })

    it('should handle new lines', function() {
      var htmlPromise = taggifier.process('42\r\n42')

      return htmlPromise.should.become('
42

42
')
    })

    it('should handle html escape sequences', function() {
      var htmlPromise = taggifier.process('This < and that >')

      return htmlPromise.should.become('
This

<

and

that

>
')
    })

    it('should handle multiple spaces at the start', function() {
      var htmlPromise = taggifier.process('  42')

      return htmlPromise.should.become('

42
')
    })

    it('should handle multiple spaces between words', function() {
      var htmlPromise = taggifier.process('42  42')

      return htmlPromise.should.become('
42

42
')
    })

    it('should handle non breaking space', function() {
      var htmlPromise = taggifier.process(' 42  ')

      return htmlPromise.should.become('

42

')
    })

    it('should handle  ', function() {
      var htmlPromise = taggifier.process('  42')

      return htmlPromise.should.become('

42
')
    })

    it('should handle multiple spaces at the end', function() {
      var htmlPromise = taggifier.process('42  ')

      return htmlPromise.should.become('
42

')
    })

    it('should handle a text node with only white space', function() {
      var htmlPromise = taggifier.process(' ')

      return htmlPromise.should.become('

')
    })

    it('should handle a text node with only  ', function() {
      var htmlPromise = taggifier.process(' ')

      return htmlPromise.should.become('

')
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');

describe('javascript:app', function () {

    before(function (done) {
        helpers.run(path.join(__dirname, '../app'))
            .withOptions({ skipInstall: true })
            .on('end', done);
    });

    it('creates files', function () {
        assert.file([
            '.editorconfig',
            'Gemfile'
        ]);
    });

});
<commit_msg>test: fixed deprecation warnings<commit_after>'use strict';

var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('javascript:app', function () {

    before(function (done) {
        helpers.run(path.join(__dirname, '../app'))
            .withOptions({ skipInstall: true })
            .on('end', done);
    });

    it('creates files', function () {
        assert.file([
            '.editorconfig',
            'Gemfile'
        ]);
    });

});
<|endoftext|>


<commit_before>var hoodiedb = require('../lib/hoodie-db'),
    MultiCouch = require('multicouch'),
    request = require('request'),
    mkdirp = require('mkdirp'),
    rimraf = require('rimraf'),
    async = require('async');

exports['validate options'] = function (test) {
    var options = {
        url: 'http://foo',
        user: 'bar',
        pass: 'baz',
        app_id: 'id1234',
        admin_db: '_users',
        queue: {}
    };
    // no errors on complete options object
    test.doesNotThrow(function () {
        hoodiedb(options);
    });
    // missing any one options causes an error
    function testWithout(prop) {
        var opt = JSON.parse(JSON.stringify(options));
        delete opt[prop];
        test.throws(function () { hoodiedb(opt); }, new RegExp(prop));
    }
    for (var k in options) {
        testWithout(k);
    }
    // passing no options causes error
    test.throws(function () { hoodiedb(); });
    test.done();
};

var ignored_queue = {
    publish: function (name, body, callback) {
        return callback();
    }
};

var COUCH_PORT = 8985;
var COUCH_URL = 'http://localhost:' + COUCH_PORT;
var USER = 'admin';
var PASS = 'password';

var COUCH_STARTED = false;
var couch = null;

function withCouch(callback) {
    if (COUCH_STARTED) {
        return callback(null, couch);
    }
    else {
        var data_dir = __dirname + '/data';
        var that = this;

        async.series([
            async.apply(rimraf, data_dir),
            async.apply(mkdirp, data_dir),
            async.apply(startCouch, data_dir),
            async.apply(createAdmin, USER, PASS)
        ],
        function (err) {
            process.on('exit', function (code) {
                couch.once('stop', function () {
                    process.exit(code);
                });
                couch.stop();
            });
            return callback(err, couch);
        });
    }
}

function startCouch(data_dir, callback) {
    // MultiCouch config object
    var couch_cfg = {
        port: COUCH_PORT,
        prefix: data_dir,
        couchdb_path: '/usr/bin/couchdb',
        default_sys_ini: '/etc/couchdb/default.ini',
        respawn: false // otherwise causes problems shutting down
    };
    // starts a local couchdb server using the Hoodie app's data dir
    var couchdb = new MultiCouch(couch_cfg);
    // local couchdb has started
    couchdb.on('start', function () {
        // give it time to be ready for requests
        pollCouch(couchdb, function (err) {
            if (err) {
                return callback(err);
            }
            COUCH_STARTED = true;
            couch = couchdb
            return callback();
        });
    });
    couchdb.on('error', callback);
    couchdb.start();
}

function createAdmin(name, pass, callback) {
    request({
        url: COUCH_URL + '/_config/admins/' + name,
        method: 'PUT',
        body: JSON.stringify(pass)
    }, callback);
}

function pollCouch(couchdb, callback) {
    function _poll() {
        request(COUCH_URL, function (err, res, body) {
            if (res && res.statusCode === 200) {
                return callback(null, couchdb);
            }
            else {
                // wait and try again
                return setTimeout(_poll, 100);
            }
        });
    }
    // start polling
    _poll();
};

exports['createDatabase'] = function (test) {
    withCouch(function (err, couchdb) {
        var hdb = hoodiedb({
            url: COUCH_URL,
            user: USER,
            pass: PASS,
            app_id: 'id1234',
            admin_db: '_users',
            queue: ignored_queue
        });
        hdb.createDatabase('foo', function (err) {
            if (err) {
                return test.done(err);
            }
            var dburl = COUCH_URL + '/' + encodeURIComponent('id1234/foo');
            request(dburl, {json: true}, function (err, res, body) {
                if (err) {
                    return test.done(err);
                }
                test.equals(res.statusCode, 200);
                test.done();
            });
        });
    });
};

exports['deleteDatabase'] = function (test) {
    withCouch(function (err, couchdb) {
        test.expect(2);

        var hdb = hoodiedb({
            url: COUCH_URL,
            user: USER,
            pass: PASS,
            app_id: 'id1234',
            admin_db: '_users',
            queue: ignored_queue
        });

        var dburl = COUCH_URL + '/' + encodeURIComponent('id1234/foo');

        async.series([
            async.apply(hdb.createDatabase, 'foo'),
            function (cb) {
                request(dburl, {json: true}, function (err, res, body) {
                    if (err) {
                        return cb(err);
                    }
                    test.equals(res.statusCode, 200);
                    cb();
                });
            },
            async.apply(hdb.deleteDatabase, 'foo'),
            function (cb) {
                request(dburl, {json: true}, function (err, res, body) {
                    if (err) {
                        return cb(err);
                    }
                    test.equals(res.statusCode, 404);
                    cb();
                });
            }
        ], test.done);
    });
};

exports['createDatabase - db_updates queue'] = function (test) {
    withCouch(function (err, couchdb) {
        test.expect(2);

        var q = {
            publish: function (queue, body, callback) {
                test.equal(queue, 'id1234/_db_updates');
                test.same(body, {
                    dbname: 'id1234/foo',
                    type: 'created'
                });
                return callback();
            }
        };

        var hdb = hoodiedb({
            url: COUCH_URL,
            user: USER,
            pass: PASS,
            app_id: 'id1234',
            admin_db: '_users',
            queue: q
        });

        hdb.createDatabase('foo', test.done);
    });
};

exports['deleteDatabase - db_updates queue'] = function (test) {
    withCouch(function (err, couchdb) {
        test.expect(2);

        var q = {
            publish: function (queue, body, callback) {
                test.equal(queue, 'id1234/_db_updates');
                test.same(body, {
                    dbname: 'id1234/foo',
                    type: 'deleted'
                });
                return callback();
            }
        };

        var hdb = hoodiedb({
            url: COUCH_URL,
            user: USER,
            pass: PASS,
            app_id: 'id1234',
            admin_db: '_users',
            queue: q
        });

        hdb.deleteDatabase('foo', test.done);
    });
};
<commit_msg>further simplify tests<commit_after>var hoodiedb = require('../lib/hoodie-db'),
    MultiCouch = require('multicouch'),
    request = require('request'),
    mkdirp = require('mkdirp'),
    rimraf = require('rimraf'),
    async = require('async');

exports['validate options'] = function (test) {
    var options = {
        url: 'http://foo',
        user: 'bar',
        pass: 'baz',
        app_id: 'id1234',
        admin_db: '_users',
        queue: {}
    };
    // no errors on complete options object
    test.doesNotThrow(function () {
        hoodiedb(options);
    });
    // missing any one options causes an error
    function testWithout(prop) {
        var opt = JSON.parse(JSON.stringify(options));
        delete opt[prop];
        test.throws(function () { hoodiedb(opt); }, new RegExp(prop));
    }
    for (var k in options) {
        testWithout(k);
    }
    // passing no options causes error
    test.throws(function () { hoodiedb(); });
    test.done();
};

var ignored_queue = {
    publish: function (name, body, callback) {
        return callback();
    }
};

var COUCH_PORT = 8985;
var COUCH_URL = 'http://localhost:' + COUCH_PORT;
var USER = 'admin';
var PASS = 'password';

var COUCH_STARTED = false;
var couch = null;

function withCouch(callback) {
    if (COUCH_STARTED) {
        return callback(null, couch);
    }
    else {
        var data_dir = __dirname + '/data';
        var that = this;

        async.series([
            async.apply(rimraf, data_dir),
            async.apply(mkdirp, data_dir),
            async.apply(startCouch, data_dir),
            async.apply(createAdmin, USER, PASS)
        ],
        function (err) {
            process.on('exit', function (code) {
                couch.once('stop', function () {
                    process.exit(code);
                });
                couch.stop();
            });
            return callback(err, couch);
        });
    }
}

function startCouch(data_dir, callback) {
    // MultiCouch config object
    var couch_cfg = {
        port: COUCH_PORT,
        prefix: data_dir,
        couchdb_path: '/usr/bin/couchdb',
        default_sys_ini: '/etc/couchdb/default.ini',
        respawn: false // otherwise causes problems shutting down
    };
    // starts a local couchdb server using the Hoodie app's data dir
    var couchdb = new MultiCouch(couch_cfg);
    // local couchdb has started
    couchdb.on('start', function () {
        // give it time to be ready for requests
        pollCouch(couchdb, function (err) {
            if (err) {
                return callback(err);
            }
            COUCH_STARTED = true;
            couch = couchdb
            return callback();
        });
    });
    couchdb.on('error', callback);
    couchdb.start();
}

function createAdmin(name, pass, callback) {
    request({
        url: COUCH_URL + '/_config/admins/' + name,
        method: 'PUT',
        body: JSON.stringify(pass)
    }, callback);
}

function pollCouch(couchdb, callback) {
    function _poll() {
        request(COUCH_URL, function (err, res, body) {
            if (res && res.statusCode === 200) {
                return callback(null, couchdb);
            }
            else {
                // wait and try again
                return setTimeout(_poll, 100);
            }
        });
    }
    // start polling
    _poll();
};

exports['createDatabase'] = function (test) {
    withCouch(function (err, couchdb) {
        test.expect(3);

        var q = {
            publish: function (queue, body, callback) {
                test.equal(queue, 'id1234/_db_updates');
                test.same(body, {
                    dbname: 'id1234/foo',
                    type: 'created'
                });
                return callback();
            }
        };

        var hdb = hoodiedb({
            url: COUCH_URL,
            user: USER,
            pass: PASS,
            app_id: 'id1234',
            admin_db: '_users',
            queue: q
        });

        hdb.createDatabase('foo', function (err) {
            if (err) {
                return test.done(err);
            }
            var dburl = COUCH_URL + '/' + encodeURIComponent('id1234/foo');
            request(dburl, {json: true}, function (err, res, body) {
                if (err) {
                    return test.done(err);
                }
                test.equals(res.statusCode, 200);
                test.done();
            });
        });

    });
};

exports['deleteDatabase'] = function (test) {
    withCouch(function (err, couchdb) {
        test.expect(3);

        var q = {
            publish: function (queue, body, callback) {
                test.equal(queue, 'id1234/_db_updates');
                test.same(body, {
                    dbname: 'id1234/foo',
                    type: 'deleted'
                });
                return callback();
            }
        };

        var hdb = hoodiedb({
            url: COUCH_URL,
            user: USER,
            pass: PASS,
            app_id: 'id1234',
            admin_db: '_users',
            queue: q
        });

        hdb.deleteDatabase('foo', function (err) {
            if (err) {
                return test.done(err);
            }
            var dburl = COUCH_URL + '/' + encodeURIComponent('id1234/foo');
            request(dburl, {json: true}, function (err, res, body) {
                if (err) {
                    return test.done(err);
                }
                test.equals(res.statusCode, 404);
                test.done();
            });
        });

    });
};
<|endoftext|>


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

'use strict';

const assert = require('assert');
const rclnodejs = require('../index.js');
const {message} = rclnodejs;

describe('rclnodejs publisher test suite', function() {
  this.timeout(60 * 1000);

  before(function() {
    return rclnodejs.init();
  });

  after(function() {
    rclnodejs.shutdown();
  });

  it('Try creating a publisher', function() {
    const node = rclnodejs.createNode('publisher_node');
    const String = 'std_msgs/msg/String';
    const publisher = node.createPublisher(String, 'topic');
    rclnodejs.spin(node);
  });

  it('Try publish a message', function() {
    const node = rclnodejs.createNode('publisher_node');
    const String = 'std_msgs/msg/String';
    const publisher = node.createPublisher(String, 'topic');
    const msg = 'Hello ROS 2.0 Publisher!';
    publisher.publish(msg);
    rclnodejs.spin(node);
  });
});
<commit_msg>shutdown rclnodejs after each case.<commit_after>// Copyright (c) 2017 Intel Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const assert = require('assert');
const rclnodejs = require('../index.js');
const {message} = rclnodejs;

describe('rclnodejs publisher test suite', function() {
  this.timeout(60 * 1000);

  beforeEach(function() {
    return rclnodejs.init();
  });

  afterEach(function() {
    rclnodejs.shutdown();
  });

  it('Try creating a publisher', function() {
    const node = rclnodejs.createNode('publisher_node');
    const String = 'std_msgs/msg/String';
    const publisher = node.createPublisher(String, 'topic');
    rclnodejs.spin(node);
  });

  it('Try publish a message', function() {
    const node = rclnodejs.createNode('publisher_node');
    const String = 'std_msgs/msg/String';
    const publisher = node.createPublisher(String, 'topic');
    const msg = 'Hello ROS 2.0 Publisher!';
    publisher.publish(msg);
    rclnodejs.spin(node);
  });
});
<|endoftext|>


<commit_before>/*globals require, exports */

var
  Backbone = require('backbone'),
  validator = require('../index'),

  MyModel = Backbone.Model.extend({
    validate: validator.create({
      type: { equal: 'user' },
      ctime: { type: 'date' },
      firstname: { type: 'string' },
      lastname: { type: 'string', minLength: 2, maxLength: 24 },
      organisation: { type: 'string', maxLength: 24 },
      email: { type: 'email', required: true },
      url: { type: 'url' },
      an_array: { type: 'array' },
      a_non_empty_array: { type: 'array', minLength: 1 }
    })
  });

exports.validateAllGood = function (t) {
  var m = new MyModel({
    type: 'user',
    firstname: 'Lupo',
    lastname: 'Montero',
    email: 'lupo@e-noise.com'
  }, { validate: true });

  t.equal(m.get('type'), 'user');
  t.equal(m.get('firstname'), 'Lupo');
  t.equal(m.get('lastname'), 'Montero');
  t.equal(m.get('email'), 'lupo@e-noise.com');
  t.done();
};

exports.validateBadEmail = function (t) {
  var m = new MyModel();

  m.on('invalid', function (m, err) {
    t.equal(m.get('email'), undefined);
    t.equal(err, 'Attribute "email" must be of type email and got value "not an email".');
    t.done();
  });

  m.set({ email: 'not an email' }, { validate: true });
};

exports.validateStringMaxLengthFailure = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/maximum length/.test(err));
    t.equal(m.get('organisation'), undefined);
    t.done();
  });

  m.set({
    organisation: 'Some very long string that won\'nt fit here!'
  }, { validate: true });
};

exports.stringMinLengthFailureWithBothMinAndMaxLength = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/minimum length/.test(err));
    t.equal(m.get('lastname'), undefined);
    t.done();
  });
  m.set({ lastname: 'S' }, { validate: true });
};

exports.stringMaxLengthFailureWithBothMinAndMaxLength = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/maximum length/.test(err));
    t.equal(m.get('lastname'), undefined);
    t.done();
  });
  m.set({ lastname: 'A super long lastname or what' }, { validate: true });
};

exports.validateStringMinAndMaxLengthTogetherSuccess = function (t) {
  var m = new MyModel();
  m.on('change', function () {
    t.equal(m.get('lastname'), 'A good lastname');
    t.done();
  });
  m.set({ lastname: 'A good lastname' }, { validate: true });
};

exports.tryToSetRequiredFieldToEmptyString = function (t) {
  var m = new MyModel({ email: 'someone@somewhere.com' });
  m.on('invalid', function (m, err) {
    t.equal(err, 'Attribute "email" is required.');
    t.equal(m.get('email'), 'someone@somewhere.com');
    t.done();
  });
  m.set({ email: '' }, { validate: true });
};

exports.allowToSetEmptyStringWhenNotRequired = function (t) {
  var m = new MyModel({ firstname: 'hahaha' });
  m.on('change', function () {
    t.equal(m.get('firstname'), '');
    t.done();
  });
  m.set({ firstname: '' }, { validate: true });
};

exports.allowToSetDateFieldToNullWhenNotRequired = function (t) {
  var m = new MyModel({ ctime: new Date() });
  m.on('change', function () {
    t.equal(m.get('ctime'), null);
    t.done();
  });
  m.set({ ctime: null }, { validate: true });
};

exports.doNotAllowToSetDateFieldToAnythingOtherThanADate = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.equal(err, 'Attribute "ctime" must be of type date and got value "not a date".');
    t.equal(m.get('ctime'), undefined);
    t.done();
  });
  m.set({ ctime: 'not a date' }, { validate: true });
};

exports.notAUrl = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.equal(err, 'Attribute "url" must be of type url and got value "not a url".');
    t.equal(m.get('url'), undefined);
    t.done();
  });
  m.set({ url: 'not a url' }, { validate: true });
};

exports.tryToSetAnArrayFieldToSomethingOtherThanAnArray = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/type array/.test(err));
    t.equal(m.get('an_array'), undefined);
    t.done();
  });
  m.set({ an_array: 'not an array' }, { validate: true });
};

exports.dontAllowEmptyArrayIfMinLengthMoreThanZero = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/minimum length/.test(err));
    t.equal(m.get('an_array'), undefined);
    t.done();
  });
  m.set({ a_non_empty_array: [] }, { validate: true });
};
<commit_msg>Tweaking tests<commit_after>/*globals require, exports */

var
  Backbone = require('backbone'),
  validator = require('../index'),

  MyModel = Backbone.Model.extend({
    validate: validator.create({
      type: { equal: 'user' },
      ctime: { type: 'date' },
      firstname: { type: 'string' },
      lastname: { type: 'string', minLength: 2, maxLength: 24 },
      organisation: { type: 'string', maxLength: 24 },
      email: { type: 'email', required: true },
      url: { type: 'url' },
      an_array: { type: 'array' },
      a_non_empty_array: { type: 'array', minLength: 1 }
    })
  });

exports.validateAllGood = function (t) {
  var m = new MyModel({
    type: 'user',
    firstname: 'Lupo',
    lastname: 'Montero',
    email: 'lupo@e-noise.com'
  }, { validate: true });

  t.equal(m.get('type'), 'user');
  t.equal(m.get('firstname'), 'Lupo');
  t.equal(m.get('lastname'), 'Montero');
  t.equal(m.get('email'), 'lupo@e-noise.com');
  t.done();
};

exports.validateBadEmail = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.equal(m.get('email'), undefined);
    t.equal(err, 'Attribute "email" must be of type email and got value "not an email".');
    t.done();
  });
  m.set({ email: 'not an email' }, { validate: true });
};

exports.validateStringMaxLengthFailure = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/maximum length/.test(err));
    t.equal(m.get('organisation'), undefined);
    t.done();
  });
  m.set({
    organisation: 'Some very long string that won\'nt fit here!'
  }, { validate: true });
};

exports.stringMinLengthFailureWithBothMinAndMaxLength = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/minimum length/.test(err));
    t.equal(m.get('lastname'), undefined);
    t.done();
  });
  m.set({ lastname: 'S' }, { validate: true });
};

exports.stringMaxLengthFailureWithBothMinAndMaxLength = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/maximum length/.test(err));
    t.equal(m.get('lastname'), undefined);
    t.done();
  });
  m.set({ lastname: 'A super long lastname or what' }, { validate: true });
};

exports.validateStringMinAndMaxLengthTogetherSuccess = function (t) {
  var m = new MyModel();
  m.on('change', function () {
    t.equal(m.get('lastname'), 'A good lastname');
    t.done();
  });
  m.set({ lastname: 'A good lastname' }, { validate: true });
};

exports.tryToSetRequiredFieldToEmptyString = function (t) {
  var m = new MyModel({ email: 'someone@somewhere.com' });
  m.on('invalid', function (m, err) {
    t.equal(err, 'Attribute "email" is required.');
    t.equal(m.get('email'), 'someone@somewhere.com');
    t.done();
  });
  m.set({ email: '' }, { validate: true });
};

exports.allowToSetEmptyStringWhenNotRequired = function (t) {
  var m = new MyModel({ firstname: 'hahaha' });
  m.on('change', function () {
    t.equal(m.get('firstname'), '');
    t.done();
  });
  m.set({ firstname: '' }, { validate: true });
};

exports.allowToSetDateFieldToNullWhenNotRequired = function (t) {
  var m = new MyModel({ ctime: new Date() });
  m.on('change', function () {
    t.equal(m.get('ctime'), null);
    t.done();
  });
  m.set({ ctime: null }, { validate: true });
};

exports.doNotAllowToSetDateFieldToAnythingOtherThanADate = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.equal(err, 'Attribute "ctime" must be of type date and got value "not a date".');
    t.equal(m.get('ctime'), undefined);
    t.done();
  });
  m.set({ ctime: 'not a date' }, { validate: true });
};

exports.notAUrl = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.equal(err, 'Attribute "url" must be of type url and got value "not a url".');
    t.equal(m.get('url'), undefined);
    t.done();
  });
  m.set({ url: 'not a url' }, { validate: true });
};

exports.tryToSetAnArrayFieldToSomethingOtherThanAnArray = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/type array/.test(err));
    t.equal(m.get('an_array'), undefined);
    t.done();
  });
  m.set({ an_array: 'not an array' }, { validate: true });
};

exports.dontAllowEmptyArrayIfMinLengthMoreThanZero = function (t) {
  var m = new MyModel();
  m.on('invalid', function (m, err) {
    t.ok(/minimum length/.test(err));
    t.equal(m.get('an_array'), undefined);
    t.done();
  });
  m.set({ a_non_empty_array: [] }, { validate: true });
};
<|endoftext|>


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

var BeakerPageObject = require('./beaker.po.js');
var path = require('path');
var os = require('os');
var beakerPO;

describe('EasyForm', function () {

  function loadGroovy() {
    beakerPO.notebookMenu.click();
    beakerPO.languageManagerMenuItem.click();
    beakerPO.languageManagerButton('Groovy').click();
    beakerPO.waitForPlugin('Groovy');
    beakerPO.languageManagerCloseButton.click();
  }

  function evaluate(code) {
    beakerPO.setCellInput(code)
        .then(function(){ beakerPO.evaluateCell(); })
        .then(function(){ browser.sleep(1000); beakerPO.waitForCellOutput(); });
  }

  function testUndoRedo(code, selector) {
    evaluate(code);

    var e = element(by.css(selector));

    e.sendKeys("A").then(function(){
        expect(e.getAttribute('value')).toEqual("A");
    });
    beakerPO.clickElementWithHandlingError(e, 'inputElement');
    //TEST UNDO
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys("\uE03Dz");
    }
    else {
      //CONTROL:      '\uE009',
      e.sendKeys("\uE009z");
    }
    expect(e.getAttribute('value')).toEqual("");
    beakerPO.clickElementWithHandlingError(e, 'inputElement');
    //TEST REDO
    //SHIFT:        '\uE008',
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys("\uE008\uE03Dz");
    } else {
      //CONTROL:      '\uE009',
      e.sendKeys("\uE008\uE009z");
    }
    beakerPO.createScreenshot('easyFormUndoRedo');
    expect(e.getAttribute('value')).toEqual("A");
  }

  beforeEach(function (done) {
    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL).then(done);
    beakerPO.newEmptyNotebook.click();
    loadGroovy();
    beakerPO.insertCellButton.click();
  });

  afterEach(function (done) {
    beakerPO.closeNotebook()
      .then(done);
  });

  it('Text Fields', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1.addTextField(\"second\", 15)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .text-field')).count()).toBe(2);
  });

  it('Text Areas', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';
    evaluate(code);
    expect(element(by.css('bk-output-display  .text-area')).isPresent()).toBe(true);
  });

  it('Dates', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addDatePicker(\"Date\")\\n';
    code += 'f1';
    evaluate(code);
    expect(element(by.css('bk-output-display  .date-picker')).isPresent()).toBe(true);
  });

  it('Check Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addCheckBoxes(\"Check Boxes\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display input[type="checkbox"]')).count()).toBe(4);
  });

  it('Radio Buttons', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addRadioButtons(\"Radio Buttons\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .radio-button-component-item')).count()).toBe(4);
  });

  it('Combo Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addComboBox(\"Combo Box\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .combo-box')).count()).toBe(1);
    expect(element.all(by.css('bk-output-display  option')).count()).toBe(4);
  });

  it('Text Areas Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';
    testUndoRedo(code, 'bk-output-display  .text-area');
  });

  it('Text Fields Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1';
    testUndoRedo(code, 'bk-output-display  .text-field');
  });

});

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

var BeakerPageObject = require('./beaker.po.js');
var path = require('path');
var os = require('os');
var beakerPO;

describe('EasyForm', function () {

  function loadGroovy() {
    beakerPO.notebookMenu.click();
    beakerPO.languageManagerMenuItem.click();
    beakerPO.languageManagerButton('Groovy').click();
    beakerPO.waitForPlugin('Groovy');
    beakerPO.languageManagerCloseButton.click();
  }

  function evaluate(code) {
    beakerPO.setCellInput(code)
        .then(function(){ beakerPO.evaluateCell(); })
        .then(function(){ browser.sleep(1000); beakerPO.waitForCellOutput(); });
  }

  function testUndoRedo(code, selector) {
    evaluate(code);

    var e = element(by.css(selector));

    e.sendKeys("A").then(function(){
        expect(e.getAttribute('value')).toEqual("A");
    });
    beakerPO.clickElementWithHandlingError(e, 'inputElement');
    //TEST UNDO
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys("\uE03Dz");
    }
    else {
      //CONTROL:      '\uE009',
      e.sendKeys("\uE009z");
    }
    expect(e.getAttribute('value')).toEqual("");
    beakerPO.clickElementWithHandlingError(e, 'inputElement');
    //TEST REDO
    //SHIFT:        '\uE008',
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys("\uE008\uE03Dz");
    } else {
      //CONTROL:      '\uE009',
      e.sendKeys("\uE008\uE009z");
    }
    beakerPO.createScreenshot('easyFormUndoRedo');
    expect(e.getAttribute('value')).toEqual("A");
  }

  beforeEach(function (done) {
    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL).then(done);
    beakerPO.newEmptyNotebook.click();
    loadGroovy();
    beakerPO.insertCellButton.click();
  });

  afterEach(function (done) {
    beakerPO.closeNotebook()
      .then(done);
  });

  it('Text Fields', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1.addTextField(\"second\", 15)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .text-field')).count()).toBe(2);
  });

  it('Text Areas', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';
    evaluate(code);
    expect(element(by.css('bk-output-display  .text-area')).isPresent()).toBe(true);
  });

  it('Dates', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addDatePicker(\"Date\")\\n';
    code += 'f1';
    evaluate(code);
    expect(element(by.css('bk-output-display  .date-picker')).isPresent()).toBe(true);
  });

  it('Check Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addCheckBoxes(\"Check Boxes\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display input[type="checkbox"]')).count()).toBe(4);
  });

  it('Radio Buttons', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addRadioButtons(\"Radio Buttons\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .radio-button-component-item')).count()).toBe(4);
  });

  it('Combo Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addComboBox(\"Combo Box\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .combo-box')).count()).toBe(1);
    expect(element.all(by.css('bk-output-display  option')).count()).toBe(4);
  });
  //
  //it('Text Areas Undo/Redo', function () {
  //  var code = 'f1 = new EasyForm(\"Form\")\\n';
  //  code += 'f1.addTextArea(\"Text Area\")\\n';
  //  code += 'f1';
  //  testUndoRedo(code, 'bk-output-display  .text-area');
  //});
  //
  //it('Text Fields Undo/Redo', function () {
  //  var code = 'f1 = new EasyForm(\"Form\")\\n';
  //  code += 'f1.addTextField(\"first\", 15)\\n';
  //  code += 'f1';
  //  testUndoRedo(code, 'bk-output-display  .text-field');
  //});

});

<|endoftext|>