<commit_before>var assert = require("chai").assert;
var Duckface = require("../src/duckface.js");

describe('Duckface', function(){
    describe('#constructor', function(){
        it('should throw error when no arguments are provided', function(){
            assert.throws(
                function(){
                    var d = new Duckface();
                },
                Error
            );
        });

        it('should throw error when more than 2 arguments are provided', function(){
            assert.throws(
                function(){
                    var d = new Duckface('foo', 'bar', 'baz');
                },
                Error
            );
        });

        it('should throw error when not called as a constructor', function(){
            assert.throws(
                function(){
                    Duckface('foo', ['bar']);
                },
                Error
            );
        });

        it('should throw error when first argument is not a string', function(){
            assert.throws(
                function(){
                    var d = new Duckface(123, 'bar');
                },
                Error
            );
        });

        it('should throw error when second argument is not an object or array', function(){
            assert.throws(
                function(){
                    var d = new Duckface('Foo', 'bar');
                },
                Error
            );

            assert.throws(
                function(){
                    var d = new Duckface('Foo', 123);
                },
                Error
            );

            assert.doesNotThrow(
                function(){
                    var d = new Duckface('Foo', []);
                },
                Error
            );

            assert.doesNotThrow(
                function(){
                    var d = new Duckface('Foo', {});
                },
                Error
            );
        });

        it('should throw error when second argument contains a non-string', function(){
            assert.throws(
                function(){
                    var d = new Duckface('Foo', ['bar', 'baz', 123]);
                },
                Error
            );

            assert.doesNotThrow(
                function(){
                    var d = new Duckface('Foo', ['bar', 'baz']);
                },
                Error
            );
        });

        it('should add an object to internal property when a valid method-name is provided', function(){
            var methods = ['bar', 'baz'];
            var d = new Duckface('Foo', methods);
            assert.lengthOf(d.methods, methods.length);
            for (var i =0; i < d.methods.length; i++) {
                assert.isObject(d.methods[i]);
                assert.lengthOf(Object.keys(d.methods[i]), 2);
                assert.property(d.methods[i], 'name');
                assert.property(d.methods[i], 'args');
                assert.equal(d.methods[i].name, methods[i]);
                assert.isNull(d.methods[i].args);
            }
        });

        it('should be an instance of Duckface', function(){
            var d = new Duckface('Foo', []);
            assert.instanceOf(d, Duckface);
        });

        it('should add an object to internal property when a valid method-name and function signature are provided', function() {
            var signatures = {
                'foo':function(bar, baz) {},
                'test':function() {}
            };
            var d = new Duckface('Dummy', signatures);
            var keys = Object.keys(signatures);
            assert.lengthOf(d.methods, keys.length);
            for (var i =0; i < d.methods.length; i++) {
                assert.isObject(d.methods[i]);
                assert.lengthOf(Object.keys(d.methods[i]), 2);
                assert.property(d.methods[i], 'name');
                assert.property(d.methods[i], 'args');
                var key = keys[i];
                assert.equal(d.methods[i].name, key);
                assert.isArray(d.methods[i].args);
                if (i === 0) {
                    assert.sameMembers(
                        d.methods[i].args,
                        ['bar', 'baz']
                    );
                }
                if (i === 1) {
                    assert.lengthOf(d.methods[i].args, 0);
                }
            }
        });
    });

    describe('#ensureImplements', function() {
        it('should throw error when no arguments are provided', function(){
            assert.throws(
                function(){
                    Duckface.ensureImplements();
                },
                Error
            );
        });
        it('should throw error when only 1 argument is provided', function(){
            assert.throws(
                function(){
                    Duckface.ensureImplements({});
                },
                Error
            );
        });
        it('should throw error when argument 2 is not a duckface', function(){
            assert.throws(
                function(){
                    Duckface.ensureImplements({}, {});
                },
                Error
            );
        });
        it('should throw error when argument bigger than 2 is not a duckface', function(){
            assert.throws(
                function(){
                    var a = new Duckface('A', ['a']);
                    var b = new Duckface('B', ['B']);
                    Duckface.ensureImplements({}, a, b, {});
                },
                Error
            );
        });
        it('should throw error when object does not implement all methods of a duckface', function(){
            assert.throws(
                function(){
                    var a = new Duckface('A', ['a', 'b', 'c']);
                    Duckface.ensureImplements({}, a);
                },
                Error
            );
        });
        it('should not throw an error when object implements all methods of a duckface', function(){
            assert.doesNotThrow(
                function(){
                    var a = new Duckface('A', ['a', 'b', 'c']);
                    var obj = {
                        a: function(){},
                        b: function(){},
                        c: function(){},
                    };
                    Duckface.ensureImplements(obj, a);
                },
                Error
            );
        });
        it('should throw error when object does not implement all methods correctly of a duckface with function signatures', function(){
            assert.throws(
                function(){
                    var methods = {
                        a: function(foo, bar) {},
                        b: function() {}
                    };
                    var a = new Duckface('A', methods);
                    Duckface.ensureImplements({}, a);
                },
                Error
            );
            assert.throws(
                function(){
                    var methods = {
                        a: function(foo, bar) {},
                        b: function() {}
                    };
                    var a = new Duckface('A', methods);
                    Duckface.ensureImplements({b:function(){}}, a);
                },
                Error
            );
        });
        it('should throw error when object does not correctly implement all method signatures of a duckface', function(){
            assert.throws(
                function(){
                    var methods = {
                        a: function(foo, bar) {},
                        b: function() {}
                    };
                    var a = new Duckface('A', methods);

                    var impl = {
                        a: function(foo) {},
                        b: function(){}
                    };
                    Duckface.ensureImplements(impl, a);
                },
                Error
            );
            assert.doesNotThrow(
                function(){
                    var methods = {
                        a: function(foo, bar) {},
                        b: function() {}
                    };
                    var a = new Duckface('A', methods);

                    var impl = {
                        a: function(foo, bar) {},
                        b: function(){}
                    };
                    Duckface.ensureImplements(impl, a);
                },
                Error
            );
        });
    });
});
<commit_msg>Add unit tests for Array.prototype.equals<commit_after>var assert = require("chai").assert;
var Duckface = require("../src/duckface.js");

describe('Duckface', function(){
    describe('#constructor', function(){
        it('should throw error when no arguments are provided', function(){
            assert.throws(
                function(){
                    var d = new Duckface();
                },
                Error
            );
        });

        it('should throw error when more than 2 arguments are provided', function(){
            assert.throws(
                function(){
                    var d = new Duckface('foo', 'bar', 'baz');
                },
                Error
            );
        });

        it('should throw error when not called as a constructor', function(){
            assert.throws(
                function(){
                    Duckface('foo', ['bar']);
                },
                Error
            );
        });

        it('should throw error when first argument is not a string', function(){
            assert.throws(
                function(){
                    var d = new Duckface(123, 'bar');
                },
                Error
            );
        });

        it('should throw error when second argument is not an object or array', function(){
            assert.throws(
                function(){
                    var d = new Duckface('Foo', 'bar');
                },
                Error
            );

            assert.throws(
                function(){
                    var d = new Duckface('Foo', 123);
                },
                Error
            );

            assert.doesNotThrow(
                function(){
                    var d = new Duckface('Foo', []);
                },
                Error
            );

            assert.doesNotThrow(
                function(){
                    var d = new Duckface('Foo', {});
                },
                Error
            );
        });

        it('should throw error when second argument contains a non-string', function(){
            assert.throws(
                function(){
                    var d = new Duckface('Foo', ['bar', 'baz', 123]);
                },
                Error
            );

            assert.doesNotThrow(
                function(){
                    var d = new Duckface('Foo', ['bar', 'baz']);
                },
                Error
            );
        });

        it('should add an object to internal property when a valid method-name is provided', function(){
            var methods = ['bar', 'baz'];
            var d = new Duckface('Foo', methods);
            assert.lengthOf(d.methods, methods.length);
            for (var i =0; i < d.methods.length; i++) {
                assert.isObject(d.methods[i]);
                assert.lengthOf(Object.keys(d.methods[i]), 2);
                assert.property(d.methods[i], 'name');
                assert.property(d.methods[i], 'args');
                assert.equal(d.methods[i].name, methods[i]);
                assert.isNull(d.methods[i].args);
            }
        });

        it('should be an instance of Duckface', function(){
            var d = new Duckface('Foo', []);
            assert.instanceOf(d, Duckface);
        });

        it('should add an object to internal property when a valid method-name and function signature are provided', function() {
            var signatures = {
                'foo':function(bar, baz) {},
                'test':function() {}
            };
            var d = new Duckface('Dummy', signatures);
            var keys = Object.keys(signatures);
            assert.lengthOf(d.methods, keys.length);
            for (var i =0; i < d.methods.length; i++) {
                assert.isObject(d.methods[i]);
                assert.lengthOf(Object.keys(d.methods[i]), 2);
                assert.property(d.methods[i], 'name');
                assert.property(d.methods[i], 'args');
                var key = keys[i];
                assert.equal(d.methods[i].name, key);
                assert.isArray(d.methods[i].args);
                if (i === 0) {
                    assert.sameMembers(
                        d.methods[i].args,
                        ['bar', 'baz']
                    );
                }
                if (i === 1) {
                    assert.lengthOf(d.methods[i].args, 0);
                }
            }
        });
    });

    describe('#ensureImplements', function() {
        it('should throw error when no arguments are provided', function(){
            assert.throws(
                function(){
                    Duckface.ensureImplements();
                },
                Error
            );
        });
        it('should throw error when only 1 argument is provided', function(){
            assert.throws(
                function(){
                    Duckface.ensureImplements({});
                },
                Error
            );
        });
        it('should throw error when argument 2 is not a duckface', function(){
            assert.throws(
                function(){
                    Duckface.ensureImplements({}, {});
                },
                Error
            );
        });
        it('should throw error when argument bigger than 2 is not a duckface', function(){
            assert.throws(
                function(){
                    var a = new Duckface('A', ['a']);
                    var b = new Duckface('B', ['B']);
                    Duckface.ensureImplements({}, a, b, {});
                },
                Error
            );
        });
        it('should throw error when object does not implement all methods of a duckface', function(){
            assert.throws(
                function(){
                    var a = new Duckface('A', ['a', 'b', 'c']);
                    Duckface.ensureImplements({}, a);
                },
                Error
            );
        });
        it('should not throw an error when object implements all methods of a duckface', function(){
            assert.doesNotThrow(
                function(){
                    var a = new Duckface('A', ['a', 'b', 'c']);
                    var obj = {
                        a: function(){},
                        b: function(){},
                        c: function(){},
                    };
                    Duckface.ensureImplements(obj, a);
                },
                Error
            );
        });
        it('should throw error when object does not implement all methods correctly of a duckface with function signatures', function(){
            assert.throws(
                function(){
                    var methods = {
                        a: function(foo, bar) {},
                        b: function() {}
                    };
                    var a = new Duckface('A', methods);
                    Duckface.ensureImplements({}, a);
                },
                Error
            );
            assert.throws(
                function(){
                    var methods = {
                        a: function(foo, bar) {},
                        b: function() {}
                    };
                    var a = new Duckface('A', methods);
                    Duckface.ensureImplements({b:function(){}}, a);
                },
                Error
            );
        });
        it('should throw error when object does not correctly implement all method signatures of a duckface', function(){
            assert.throws(
                function(){
                    var methods = {
                        a: function(foo, bar) {},
                        b: function() {}
                    };
                    var a = new Duckface('A', methods);

                    var impl = {
                        a: function(foo) {},
                        b: function(){}
                    };
                    Duckface.ensureImplements(impl, a);
                },
                Error
            );
            assert.doesNotThrow(
                function(){
                    var methods = {
                        a: function(foo, bar) {},
                        b: function() {}
                    };
                    var a = new Duckface('A', methods);

                    var impl = {
                        a: function(foo, bar) {},
                        b: function(){}
                    };
                    Duckface.ensureImplements(impl, a);
                },
                Error
            );
        });
    });
});

describe('Array.prototype.equals', function() {
    it('should return false when compared with a non-array', function(){
        assert.isFalse([].equals('foo'));
        assert.isFalse([].equals(true));
        assert.isFalse([].equals(false));
        assert.isFalse([].equals({}));
        assert.isFalse([].equals(123));
        assert.isFalse([].equals(123.45));
    });

    it('should return false when lengths are not the same', function() {
        assert.isFalse(['foo'].equals([]));
        assert.isFalse(['foo'].equals(['bar','baz']));
    });

    it('should return true when both arrays are empty', function() {
        assert.isTrue([].equals([]));
    });

    it('should return false when sub-arrays are not equal', function() {
        assert.isFalse([[]].equals([['foo']]));
    });

    it('should return false if at least one of the elements is different', function() {
        assert.isFalse(['foo','bar','baz'].equals(['foo','bar','faz']));
    });
});
<|endoftext|>


<commit_before>const assert = require('chai').assert;
const Enemy = require("../lib/enemies.js");
// const Bluecifer = require('../lib/bluecifer');

describe("Enemy", function () {
    context("it allows me to customize it", function () {
      it("should let me assign a height and width", function () {
        var enemy = new Enemy({height:10, width:15});
        assert.strictEqual(enemy.height, 10);
        assert.strictEqual(enemy.width, 15);
      });

      it("should default to 500 for its x coord", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.x, 500);
      });

      it("should have a default width of 50", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.width, 50);
      });

      it("should have a default height of 35", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.height, 35);
      });

      it("should have a default pic of the airplane", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.image, "../IMGS/airplane.png");
      });

      it("should have a default speed of equal or less than 3", function () {
        var enemy = new Enemy();
        assert.isBelow(enemy.speed, 3.001);
      });

      it("should have a default y coord of equal or less than 300", function () {
        var enemy = new Enemy();
        assert.isBelow(enemy.y, 301);
      });
  });
}); // end of describe Enemy
<commit_msg>all tests still pass for enemy<commit_after>const assert = require('chai').assert;
const Enemy = require("../lib/enemies.js");

describe("Enemy", function () {
    context("it allows me to customize it", function () {
      it("should let me assign a height and width", function () {
        var enemy = new Enemy({height:10, width:15});
        assert.strictEqual(enemy.height, 10);
        assert.strictEqual(enemy.width, 15);
      });

      it("should default to 500 for its x coord", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.x, 500);
      });

      it("should have a default width of 50", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.width, 50);
      });

      it("should have a default height of 35", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.height, 35);
      });

      it("should have a default pic of the airplane", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.image, "../IMGS/airplane.png");
      });

      it("should have a default speed of equal or less than 3", function () {
        var enemy = new Enemy();
        assert.isBelow(enemy.speed, 3.001);
      });

      it("should have a default y coord of equal or less than 300", function () {
        var enemy = new Enemy();
        assert.isBelow(enemy.y, 301);
      });
  });
}); // end of describe Enemy
<|endoftext|>


<commit_before>/* global unexpected */

const expect = unexpected.clone();

if (typeof process === 'object') {
  describe('invoked in a test via an external test runner', () => {
    const findNodeModules = require('find-node-modules');
    const pathModule = require('path');
    const childProcess = require('child_process');
    const basePath = pathModule.join(findNodeModules()[0], '..');
    const externaltestsDir = pathModule.join(__dirname, '..', 'externaltests');
    const extend = require('../lib/utils').extend;
    describe('executed through mocha', () => {
      expect.addAssertion(
        '<array|string> executed through mocha <object?>',
        function (expect, subject, env) {
          if (!Array.isArray(subject)) {
            subject = [subject];
          }
          return expect.promise(function (run) {
            childProcess.execFile(
              pathModule.resolve(basePath, 'node_modules', '.bin', 'mocha'),
              [
                '--config',
                pathModule.resolve(__dirname, '..', '.mocharc.json'),
                ...subject.map(function (fileName) {
                  return pathModule.resolve(
                    externaltestsDir,
                    `${fileName}.spec.js`
                  );
                }),
              ],
              {
                cwd: basePath,
                env: extend({}, process.env, env || {}),
              },
              run(function (err, stdout, stderr) {
                return [err, stdout, stderr];
              })
            );
          });
        }
      );

      it('should report that a promise was created, but not returned by the it block', () => {
        return expect(
          'forgotToReturnPendingPromiseFromSuccessfulItBlock',
          'executed through mocha'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'to contain',
            'Error: should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not report that a promise was created if the test already failed synchronously', () => {
        return expect(
          'forgotToReturnPendingPromiseFromFailingItBlock',
          'executed through mocha'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'not to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should trim unexpected plugins from the stack trace when the UNEXPECTED_FULL_TRACE environment variable is not set', () => {
        return expect('fullTrace', 'executed through mocha', {
          UNEXPECTED_FULL_TRACE: '',
        }).spread(function (err, stdout, stderr) {
          expect(stdout, 'not to contain', 'node_modules/unexpected-bogus/');
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not trim unexpected plugins from the stack trace when the UNEXPECTED_FULL_TRACE environment variable is set', () => {
        return expect('fullTrace', 'executed through mocha', {
          UNEXPECTED_FULL_TRACE: 'yes',
        }).spread(function (err, stdout, stderr) {
          expect(stdout, 'to contain', 'node_modules/unexpected-bogus/');
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should accept an UNEXPECTED_DEPTH environment variable', () => {
        return expect('deepObject', 'executed through mocha', {
          UNEXPECTED_DEPTH: 6,
        }).spread(function (err, stdout, stderr) {
          expect(err, 'to be falsy');
        });
      });

      it('should render a long stack trace for an async test', () => {
        return expect('failingAsync', 'executed through mocha').spread(
          function (err, stdout, stderr) {
            expect(err, 'to be truthy');
            expect(stdout, 'to contain', 'From previous event:');
          }
        );
      });

      it('should fail when a promise failing in the next tick is created but not returned', () => {
        return expect(
          'forgotToReturnPromiseRejectedInTheNextTick',
          'executed through mocha'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'to contain',
            'Error: should fail: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', {
            code: expect.it('to be greater than', 0),
          });
        });
      });

      it('should not fail when an unresolved promise was used in a expect.promise.any construct', () => {
        return expect(
          'avoidPromiseAnyFootgunFalsePositive',
          'executed through mocha'
        ).then(([err]) => {
          expect(err, 'to be falsy');
        });
      });

      it('should not fail when an unresolved promise was used in a expect.promise.race construct', () => {
        return expect(
          'avoidPromiseRaceFootgunFalsePositive',
          'executed through mocha'
        ).then(([err]) => {
          expect(err, 'to be falsy');
        });
      });

      describe('with a test suite spanning multiple files', () => {
        it('should report that a promise was created, but not returned by the it block in the first test', () => {
          return expect(
            ['forgotToReturnPendingPromiseFromSuccessfulItBlock', 'successful'],
            'executed through mocha'
          ).spread(function (err, stdout, stderr) {
            expect(
              stdout,
              'to contain',
              'Error: should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to satisfy', { code: 1 });
          });
        });

        it('should report that a promise was created, but not returned by the it block in the second test', () => {
          return expect(
            ['successful', 'forgotToReturnPendingPromiseFromSuccessfulItBlock'],
            'executed through mocha'
          ).spread(function (err, stdout, stderr) {
            expect(
              stdout,
              'to contain',
              'Error: should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to satisfy', { code: 1 });
          });
        });
      });

      describe('with an assertion that succeeds, but creates a promise that remains pending', () => {
        it('should pass', () => {
          return expect(
            'assertionSucceedsWhilePromiseIsPending',
            'executed through mocha'
          ).spread(function (err, stdout, stderr) {
            expect(
              stdout,
              'not to contain',
              'Error: should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to be falsy');
          });
        });
      });

      it('should render the stack trace of the thrown error without any artifacts when "not to error" encounters an error', () => {
        return expect('notToErrorCaughtError', 'executed through mocha').spread(
          function (err, stdout, stderr) {
            expect(err, 'to satisfy', { code: 1 });
            expect(
              stdout,
              'to contain',
              'not to error\n' +
                "  returned promise rejected with: Error('argh')\n"
            ).and('to contain', '      at thisIsImportant');
          }
        );
      });
    });

    describe('executed through jasmine', () => {
      expect.addAssertion('<string> executed through jasmine', function (
        expect,
        subject
      ) {
        return expect.promise(function (run) {
          childProcess.execFile(
            pathModule.resolve(basePath, 'node_modules', '.bin', 'jasmine'),
            {
              cwd: pathModule.join(externaltestsDir, '..'),
              env: extend({}, process.env, {
                JASMINE_CONFIG_PATH: `${externaltestsDir}/${subject}.jasmine.json`,
              }),
            },
            run(function (err, stdout, stderr) {
              return [err, stdout, stderr];
            })
          );
        });
      });

      it('should report that a promise was created, but not returned by the it block when the test ', () => {
        return expect(
          'forgotToReturnPendingPromiseFromSuccessfulItBlock',
          'executed through jasmine'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not report that a promise was created if the test already failed synchronously', () => {
        return expect(
          'forgotToReturnPendingPromiseFromFailingItBlock',
          'executed through jasmine'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'not to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should render the stack trace of the thrown error without any artifacts when "not to error" encounters an error', () => {
        return expect(
          'notToErrorCaughtError',
          'executed through jasmine'
        ).spread(function (err, stdout, stderr) {
          expect(err, 'to satisfy', { code: 1 });
          expect(
            stdout,
            'to contain',
            '    not to error\n' +
              "      returned promise rejected with: Error('argh')\n"
          ).and('to contain', '        at thisIsImportant');
        });
      });
    });

    describe('executed through jest', () => {
      expect.addAssertion(
        '<array|string> executed through jest <object?>',
        function (expect, subject, env) {
          if (!Array.isArray(subject)) {
            subject = [subject];
          }
          return expect.promise(function (run) {
            childProcess.execFile(
              pathModule.resolve(basePath, 'node_modules', '.bin', 'jest'),
              [
                '--config',
                pathModule.resolve(externaltestsDir, 'jestconfig.json'),
              ].concat(
                subject.map(function (fileName) {
                  return pathModule.resolve(
                    externaltestsDir,
                    `${fileName}.spec.js`
                  );
                })
              ),
              {
                cwd: basePath,
                env: extend({}, process.env, env || {}),
              },
              run(function (err, stdout, stderr) {
                return [err, stdout, stderr];
              })
            );
          });
        }
      );

      it('should report that a promise was created, but not returned by the it block', () => {
        return expect(
          'forgotToReturnPendingPromiseFromSuccessfulItBlock',
          'executed through jest'
        ).spread(function (err, stdout, stderr) {
          expect(
            stderr,
            'to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not report that a promise was created if the test already failed synchronously', () => {
        return expect(
          'forgotToReturnPendingPromiseFromFailingItBlock',
          'executed through jest'
        ).spread(function (err, stdout, stderr) {
          expect(
            stderr,
            'not to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should trim unexpected plugins from the stack trace when the UNEXPECTED_FULL_TRACE environment variable is not set', () => {
        return expect('fullTrace', 'executed through jest', {
          UNEXPECTED_FULL_TRACE: '',
        }).spread(function (err, stdout, stderr) {
          expect(stderr, 'not to contain', 'node_modules/unexpected-bogus/');
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not trim unexpected plugins from the stack trace when the UNEXPECTED_FULL_TRACE environment variable is set', () => {
        return expect('fullTrace', 'executed through jest', {
          UNEXPECTED_FULL_TRACE: 'yes',
        }).spread(function (err, stdout, stderr) {
          expect(stderr, 'to contain', 'node_modules/unexpected-bogus/');
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should accept an UNEXPECTED_DEPTH environment variable', () => {
        return expect('deepObject', 'executed through jest', {
          UNEXPECTED_DEPTH: 6,
        }).spread(function (err, stdout, stderr) {
          expect(err, 'to be falsy');
        });
      });

      it('should render a long stack trace for an async test', () => {
        return expect('failingAsync', 'executed through jest').spread(function (
          err,
          stdout,
          stderr
        ) {
          expect(err, 'to be truthy');
          expect(stderr, 'to contain', 'From previous event:');
        });
      });

      it('should fail when a promise failing in the next tick is created but not returned', () => {
        return expect(
          'forgotToReturnPromiseRejectedInTheNextTick',
          'executed through jest'
        ).spread(function (err, stdout, stderr) {
          expect(
            stderr,
            'to contain',
            'should fail: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not fail when an unresolved promise was used in a expect.promise.any construct', () => {
        return expect(
          'avoidPromiseAnyFootgunFalsePositive',
          'executed through jest'
        ).then(([err]) => {
          expect(err, 'to be falsy');
        });
      });

      it('should not fail when an unresolved promise was used in a expect.promise.race construct', () => {
        return expect(
          'avoidPromiseRaceFootgunFalsePositive',
          'executed through jest'
        ).then(([err]) => {
          expect(err, 'to be falsy');
        });
      });

      describe('with a test suite spanning multiple files', () => {
        it('should report that a promise was created, but not returned by the it block in the first test', () => {
          return expect(
            ['forgotToReturnPendingPromiseFromSuccessfulItBlock', 'successful'],
            'executed through jest'
          ).spread(function (err, stdout, stderr) {
            expect(
              stderr,
              'to contain',
              'should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to satisfy', { code: 1 });
          });
        });

        it('should report that a promise was created, but not returned by the it block in the second test', () => {
          return expect(
            ['successful', 'forgotToReturnPendingPromiseFromSuccessfulItBlock'],
            'executed through jest'
          ).spread(function (err, stdout, stderr) {
            expect(
              stderr,
              'to contain',
              'should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to satisfy', { code: 1 });
          });
        });
      });

      describe('with an assertion that succeeds, but creates a promise that remains pending', () => {
        it('should pass', () => {
          return expect(
            'assertionSucceedsWhilePromiseIsPending',
            'executed through jest'
          ).spread(function (err, stdout, stderr) {
            expect(
              stderr,
              'not to contain',
              'should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to be falsy');
          });
        });
      });

      it('should render the stack trace of the thrown error without any artifacts when "not to error" encounters an error', () => {
        return expect('notToErrorCaughtError', 'executed through jest').spread(
          function (err, stdout, stderr) {
            expect(err, 'to satisfy', { code: 1 });
            expect(
              stderr,
              'to contain',
              '    not to error\n' +
                "      returned promise rejected with: Error('argh')\n"
            ).and('to contain', '      at thisIsImportant');
          }
        );
      });
    });
  });
}
<commit_msg>Use basePath to locate .mocharc.json<commit_after>/* global unexpected */

const expect = unexpected.clone();

if (typeof process === 'object') {
  describe('invoked in a test via an external test runner', () => {
    const findNodeModules = require('find-node-modules');
    const pathModule = require('path');
    const childProcess = require('child_process');
    const basePath = pathModule.join(findNodeModules()[0], '..');
    const externaltestsDir = pathModule.join(__dirname, '..', 'externaltests');
    const extend = require('../lib/utils').extend;
    describe('executed through mocha', () => {
      expect.addAssertion(
        '<array|string> executed through mocha <object?>',
        function (expect, subject, env) {
          if (!Array.isArray(subject)) {
            subject = [subject];
          }
          return expect.promise(function (run) {
            childProcess.execFile(
              pathModule.resolve(basePath, 'node_modules', '.bin', 'mocha'),
              [
                '--config',
                pathModule.resolve(basePath, '.mocharc.json'),
                ...subject.map(function (fileName) {
                  return pathModule.resolve(
                    externaltestsDir,
                    `${fileName}.spec.js`
                  );
                }),
              ],
              {
                cwd: basePath,
                env: extend({}, process.env, env || {}),
              },
              run(function (err, stdout, stderr) {
                return [err, stdout, stderr];
              })
            );
          });
        }
      );

      it('should report that a promise was created, but not returned by the it block', () => {
        return expect(
          'forgotToReturnPendingPromiseFromSuccessfulItBlock',
          'executed through mocha'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'to contain',
            'Error: should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not report that a promise was created if the test already failed synchronously', () => {
        return expect(
          'forgotToReturnPendingPromiseFromFailingItBlock',
          'executed through mocha'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'not to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should trim unexpected plugins from the stack trace when the UNEXPECTED_FULL_TRACE environment variable is not set', () => {
        return expect('fullTrace', 'executed through mocha', {
          UNEXPECTED_FULL_TRACE: '',
        }).spread(function (err, stdout, stderr) {
          expect(stdout, 'not to contain', 'node_modules/unexpected-bogus/');
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not trim unexpected plugins from the stack trace when the UNEXPECTED_FULL_TRACE environment variable is set', () => {
        return expect('fullTrace', 'executed through mocha', {
          UNEXPECTED_FULL_TRACE: 'yes',
        }).spread(function (err, stdout, stderr) {
          expect(stdout, 'to contain', 'node_modules/unexpected-bogus/');
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should accept an UNEXPECTED_DEPTH environment variable', () => {
        return expect('deepObject', 'executed through mocha', {
          UNEXPECTED_DEPTH: 6,
        }).spread(function (err, stdout, stderr) {
          expect(err, 'to be falsy');
        });
      });

      it('should render a long stack trace for an async test', () => {
        return expect('failingAsync', 'executed through mocha').spread(
          function (err, stdout, stderr) {
            expect(err, 'to be truthy');
            expect(stdout, 'to contain', 'From previous event:');
          }
        );
      });

      it('should fail when a promise failing in the next tick is created but not returned', () => {
        return expect(
          'forgotToReturnPromiseRejectedInTheNextTick',
          'executed through mocha'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'to contain',
            'Error: should fail: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', {
            code: expect.it('to be greater than', 0),
          });
        });
      });

      it('should not fail when an unresolved promise was used in a expect.promise.any construct', () => {
        return expect(
          'avoidPromiseAnyFootgunFalsePositive',
          'executed through mocha'
        ).then(([err]) => {
          expect(err, 'to be falsy');
        });
      });

      it('should not fail when an unresolved promise was used in a expect.promise.race construct', () => {
        return expect(
          'avoidPromiseRaceFootgunFalsePositive',
          'executed through mocha'
        ).then(([err]) => {
          expect(err, 'to be falsy');
        });
      });

      describe('with a test suite spanning multiple files', () => {
        it('should report that a promise was created, but not returned by the it block in the first test', () => {
          return expect(
            ['forgotToReturnPendingPromiseFromSuccessfulItBlock', 'successful'],
            'executed through mocha'
          ).spread(function (err, stdout, stderr) {
            expect(
              stdout,
              'to contain',
              'Error: should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to satisfy', { code: 1 });
          });
        });

        it('should report that a promise was created, but not returned by the it block in the second test', () => {
          return expect(
            ['successful', 'forgotToReturnPendingPromiseFromSuccessfulItBlock'],
            'executed through mocha'
          ).spread(function (err, stdout, stderr) {
            expect(
              stdout,
              'to contain',
              'Error: should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to satisfy', { code: 1 });
          });
        });
      });

      describe('with an assertion that succeeds, but creates a promise that remains pending', () => {
        it('should pass', () => {
          return expect(
            'assertionSucceedsWhilePromiseIsPending',
            'executed through mocha'
          ).spread(function (err, stdout, stderr) {
            expect(
              stdout,
              'not to contain',
              'Error: should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to be falsy');
          });
        });
      });

      it('should render the stack trace of the thrown error without any artifacts when "not to error" encounters an error', () => {
        return expect('notToErrorCaughtError', 'executed through mocha').spread(
          function (err, stdout, stderr) {
            expect(err, 'to satisfy', { code: 1 });
            expect(
              stdout,
              'to contain',
              'not to error\n' +
                "  returned promise rejected with: Error('argh')\n"
            ).and('to contain', '      at thisIsImportant');
          }
        );
      });
    });

    describe('executed through jasmine', () => {
      expect.addAssertion('<string> executed through jasmine', function (
        expect,
        subject
      ) {
        return expect.promise(function (run) {
          childProcess.execFile(
            pathModule.resolve(basePath, 'node_modules', '.bin', 'jasmine'),
            {
              cwd: pathModule.join(externaltestsDir, '..'),
              env: extend({}, process.env, {
                JASMINE_CONFIG_PATH: `${externaltestsDir}/${subject}.jasmine.json`,
              }),
            },
            run(function (err, stdout, stderr) {
              return [err, stdout, stderr];
            })
          );
        });
      });

      it('should report that a promise was created, but not returned by the it block when the test ', () => {
        return expect(
          'forgotToReturnPendingPromiseFromSuccessfulItBlock',
          'executed through jasmine'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not report that a promise was created if the test already failed synchronously', () => {
        return expect(
          'forgotToReturnPendingPromiseFromFailingItBlock',
          'executed through jasmine'
        ).spread(function (err, stdout, stderr) {
          expect(
            stdout,
            'not to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should render the stack trace of the thrown error without any artifacts when "not to error" encounters an error', () => {
        return expect(
          'notToErrorCaughtError',
          'executed through jasmine'
        ).spread(function (err, stdout, stderr) {
          expect(err, 'to satisfy', { code: 1 });
          expect(
            stdout,
            'to contain',
            '    not to error\n' +
              "      returned promise rejected with: Error('argh')\n"
          ).and('to contain', '        at thisIsImportant');
        });
      });
    });

    describe('executed through jest', () => {
      expect.addAssertion(
        '<array|string> executed through jest <object?>',
        function (expect, subject, env) {
          if (!Array.isArray(subject)) {
            subject = [subject];
          }
          return expect.promise(function (run) {
            childProcess.execFile(
              pathModule.resolve(basePath, 'node_modules', '.bin', 'jest'),
              [
                '--config',
                pathModule.resolve(externaltestsDir, 'jestconfig.json'),
              ].concat(
                subject.map(function (fileName) {
                  return pathModule.resolve(
                    externaltestsDir,
                    `${fileName}.spec.js`
                  );
                })
              ),
              {
                cwd: basePath,
                env: extend({}, process.env, env || {}),
              },
              run(function (err, stdout, stderr) {
                return [err, stdout, stderr];
              })
            );
          });
        }
      );

      it('should report that a promise was created, but not returned by the it block', () => {
        return expect(
          'forgotToReturnPendingPromiseFromSuccessfulItBlock',
          'executed through jest'
        ).spread(function (err, stdout, stderr) {
          expect(
            stderr,
            'to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not report that a promise was created if the test already failed synchronously', () => {
        return expect(
          'forgotToReturnPendingPromiseFromFailingItBlock',
          'executed through jest'
        ).spread(function (err, stdout, stderr) {
          expect(
            stderr,
            'not to contain',
            'should call the callback: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should trim unexpected plugins from the stack trace when the UNEXPECTED_FULL_TRACE environment variable is not set', () => {
        return expect('fullTrace', 'executed through jest', {
          UNEXPECTED_FULL_TRACE: '',
        }).spread(function (err, stdout, stderr) {
          expect(stderr, 'not to contain', 'node_modules/unexpected-bogus/');
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not trim unexpected plugins from the stack trace when the UNEXPECTED_FULL_TRACE environment variable is set', () => {
        return expect('fullTrace', 'executed through jest', {
          UNEXPECTED_FULL_TRACE: 'yes',
        }).spread(function (err, stdout, stderr) {
          expect(stderr, 'to contain', 'node_modules/unexpected-bogus/');
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should accept an UNEXPECTED_DEPTH environment variable', () => {
        return expect('deepObject', 'executed through jest', {
          UNEXPECTED_DEPTH: 6,
        }).spread(function (err, stdout, stderr) {
          expect(err, 'to be falsy');
        });
      });

      it('should render a long stack trace for an async test', () => {
        return expect('failingAsync', 'executed through jest').spread(function (
          err,
          stdout,
          stderr
        ) {
          expect(err, 'to be truthy');
          expect(stderr, 'to contain', 'From previous event:');
        });
      });

      it('should fail when a promise failing in the next tick is created but not returned', () => {
        return expect(
          'forgotToReturnPromiseRejectedInTheNextTick',
          'executed through jest'
        ).spread(function (err, stdout, stderr) {
          expect(
            stderr,
            'to contain',
            'should fail: You have created a promise that was not returned from the it block'
          );
          expect(err, 'to satisfy', { code: 1 });
        });
      });

      it('should not fail when an unresolved promise was used in a expect.promise.any construct', () => {
        return expect(
          'avoidPromiseAnyFootgunFalsePositive',
          'executed through jest'
        ).then(([err]) => {
          expect(err, 'to be falsy');
        });
      });

      it('should not fail when an unresolved promise was used in a expect.promise.race construct', () => {
        return expect(
          'avoidPromiseRaceFootgunFalsePositive',
          'executed through jest'
        ).then(([err]) => {
          expect(err, 'to be falsy');
        });
      });

      describe('with a test suite spanning multiple files', () => {
        it('should report that a promise was created, but not returned by the it block in the first test', () => {
          return expect(
            ['forgotToReturnPendingPromiseFromSuccessfulItBlock', 'successful'],
            'executed through jest'
          ).spread(function (err, stdout, stderr) {
            expect(
              stderr,
              'to contain',
              'should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to satisfy', { code: 1 });
          });
        });

        it('should report that a promise was created, but not returned by the it block in the second test', () => {
          return expect(
            ['successful', 'forgotToReturnPendingPromiseFromSuccessfulItBlock'],
            'executed through jest'
          ).spread(function (err, stdout, stderr) {
            expect(
              stderr,
              'to contain',
              'should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to satisfy', { code: 1 });
          });
        });
      });

      describe('with an assertion that succeeds, but creates a promise that remains pending', () => {
        it('should pass', () => {
          return expect(
            'assertionSucceedsWhilePromiseIsPending',
            'executed through jest'
          ).spread(function (err, stdout, stderr) {
            expect(
              stderr,
              'not to contain',
              'should call the callback: You have created a promise that was not returned from the it block'
            );
            expect(err, 'to be falsy');
          });
        });
      });

      it('should render the stack trace of the thrown error without any artifacts when "not to error" encounters an error', () => {
        return expect('notToErrorCaughtError', 'executed through jest').spread(
          function (err, stdout, stderr) {
            expect(err, 'to satisfy', { code: 1 });
            expect(
              stderr,
              'to contain',
              '    not to error\n' +
                "      returned promise rejected with: Error('argh')\n"
            ).and('to contain', '      at thisIsImportant');
          }
        );
      });
    });
  });
}
<|endoftext|>


<commit_before>import test from 'ava';
import findPatterns from '../source/find-patterns';

test('when calling find-patterns with no arguments', t => {
	const actual = findPatterns();
	t.throws(actual, TypeError, 'it should throw a TypeError');
});
<commit_msg>test(find-patterns): define behaviour for non-existing paths<commit_after>import test from 'ava';
import findPatterns from '../source/find-patterns';

test('when calling find-patterns with no arguments', t => {
	const actual = findPatterns();
	t.throws(actual, TypeError, 'it should throw a TypeError');
});

test('when calling find-patterns with a non-existing path', t => {
	const actual = findPatterns('./something/very/unlikely');
	t.throws(actual, RangeError, 'it should throw a RangeError');
});
<|endoftext|>


<commit_before>// Webflow code to submit form
const conversion = (e, n) => {

	let i = null

	// n stores names already with values (good for checkbox/radio)
	n = n || {}

	const nodelist = e[0].querySelectorAll('input:not([type="submit"])')
	console.log(nodelist)

	nodelist.forEach((item, index) => {
		// If we already have an error, exit early
		if (i) {
			return
		}
		let s = item.type,
			u = item.getAttribute("data-name") || item.getAttribute("name") || "Field " + (index + 1),
			l = item.value

		// Checkbox/radio uses checked attribute and should be handled seperately
		if ("checkbox" === s ||"radio" === s) {
			// If we already have a value for radio/checkbox of this name, exit early
			if (null === n[u] || "string" == typeof n[u]) return
			// get value
			l = e.querySelector('input[name="' + item.getAttribute("name") + '"]:checked').value || null
		}

		if("string" == typeof l) {
			(l = l.trim())
		}
		n[u] = l
		i = verification(item, s, u, l)

	})

	return i

}

const verification = (item, e, n, i) => {
	let r = null, k = /e(-)?mail/i, _ = /^\S+@\S+$/
	if ("password" === e) {
		return "Passwords cannot be submitted."
	}
	if (!item.getAttribute("required")) {
		return r
	}
	if (!i){
		return "Please fill out the required field: " + n
	}
	if ((k.test(n) || k.test(item.getAttribute("type"))) && _.test(i)) {
		return "Please enter a valid email address for: " + n
	}
	return null
}

const createForm = () => {
	let formData = {
		name: page() === 'Event' ? 'Event Registration' : 'Custom Charge',
		source: window.location.href,
		test: false,
		fields: {},
		dolphin: false
	}
	let error = conversion(page() === 'Event' ? getElementById(eventForm) : getElementById(customForm), formData.fields)
	if (error) {
		throw error
	}
	console.log(formData)
	return formData
}
<commit_msg>Changes by Sam Tobia for new version.<commit_after>// Webflow code to submit form
const conversion = (e, n) => {

	let i = null

	// n stores names already with values (good for checkbox/radio)
	n = n || {}

	const nodelist = e[0].querySelectorAll('input:not([type="submit"])')
	console.log(nodelist)

	nodelist.forEach((item, index) => {
		// If we already have an error, exit early
		if (i) {
			return
		}
		let s = item.type,
			u = item.getAttribute("data-name") || item.getAttribute("name") || "Field " + (index + 1),
			l = item.value

		// Checkbox/radio uses checked attribute and should be handled seperately
		if ("checkbox" === s ||"radio" === s) {
			// If we already have a value for radio/checkbox of this name, exit early
			if (null === n[u] || "string" == typeof n[u]) return
			// get value
			l = e[0].querySelector('input[name="' + item.getAttribute("name") + '"]:checked').value || null
		}

		if("string" == typeof l) {
			(l = l.trim())
		}
		n[u] = l
		i = verification(item, s, u, l)

	})

	return i

}

const verification = (item, e, n, i) => {
	let r = null, k = /e(-)?mail/i, _ = /^\S+@\S+$/
	if ("password" === e) {
		return "Passwords cannot be submitted."
	}
	if (!item.getAttribute("required")) {
		return r
	}
	if (!i){
		return "Please fill out the required field: " + n
	}
	if ((k.test(n) || k.test(item.getAttribute("type"))) && _.test(i)) {
		return "Please enter a valid email address for: " + n
	}
	return null
}

const createForm = () => {
	let formData = {
		name: page() === 'Event' ? 'Event Registration' : 'Custom Charge',
		source: window.location.href,
		test: false,
		fields: {},
		dolphin: false
	}
	let error = conversion(page() === 'Event' ? getElementById(eventForm) : getElementById(customForm), formData.fields)
	if (error) {
		throw error
	}
	console.log(formData)
	return formData
}
<|endoftext|>


<commit_before><commit_msg>Makes script more tolerant<commit_after><|endoftext|>


<commit_before>(function() {
    'use strict';

    // Declare the main module taking all other modules together
    var veganautModule = angular.module('veganaut.app', [
        'ngRoute',
        'ngSanitize',
        'ui.bootstrap',
        'angular-loading-bar',
        'leaflet-directive',
        'pascalprecht.translate',
        'veganaut.ui',
        'veganaut.alert',
        'veganaut.form',
        'veganaut.geocode',
        'veganaut.angularPiwik',
        'veganaut.app.templates',
        'veganaut.app.main',
        'veganaut.app.session',
        'veganaut.app.backend',
        'veganaut.app.location',
        'veganaut.app.map',
        'veganaut.app.missions',
        'veganaut.app.community',
        'veganaut.app.user'
    ]);

    veganautModule.config([
        '$routeProvider', '$locationProvider', '$compileProvider', '$translateProvider',
        'angularPiwikProvider', 'appSettings', 'piwikSettings', 'i18nSettings',
        function($routeProvider, $locationProvider, $compileProvider, $translateProvider,
            angularPiwikProvider, appSettings, piwikSettings, i18nSettings)
        {
            // Configure general settings
            $locationProvider.html5Mode(appSettings.html5Mode);
            $compileProvider.debugInfoEnabled(appSettings.debugInfo);

            // Set up routes
            $routeProvider.when('/register', {template: '<vg-register></vg-register>'});
            $routeProvider.when('/login', {templateUrl: '/veganaut/user/login.tpl.html', controller: 'LoginCtrl'});
            $routeProvider.when('/forgot', {templateUrl: '/veganaut/user/forgot.tpl.html'});
            $routeProvider.when('/reset/:token', {templateUrl: '/veganaut/user/reset.tpl.html'});

            $routeProvider.when('/', {templateUrl: '/veganaut/home/home.tpl.html'});
            $routeProvider.when('/map', {
                templateUrl: '/veganaut/map/map.tpl.html',
                // Don't reload when get params or hash changes
                reloadOnSearch: false
            });

            // Location list (with trailing slash for Piwik)
            $routeProvider.when('/list/locations/', {template: '<vg-location-list></vg-location-list>'});
            $routeProvider.when('/location/:id', {templateUrl: '/veganaut/map/locationDetails.tpl.html'});
            $routeProvider.when('/location/:id/edit', {templateUrl: '/veganaut/map/editLocation.tpl.html'});
            $routeProvider.when('/me', {templateUrl: '/veganaut/user/profile.tpl.html'});
            $routeProvider.when('/me/edit', {templateUrl: '/veganaut/user/editProfile.tpl.html'});
            $routeProvider.when('/community', {templateUrl: '/veganaut/community/community.tpl.html'});
            $routeProvider.when('/veganaut/:personId', {templateUrl: '/veganaut/user/person.tpl.html', controller: 'PersonCtrl'});

            // Legacy URL redirects
            $routeProvider.when('/score', {redirectTo: '/community'});
            $routeProvider.when('/list', {redirectTo: '/list/locations'});

            $routeProvider.otherwise({redirectTo: '/'});
            // TODO: make sure only routes are accessed that are allowed for the current situation (e.g. logged out)

            // Set up translations
            $translateProvider.useStaticFilesLoader({
                prefix: 'locale/',
                suffix: '.json'
            });
            $translateProvider.registerAvailableLanguageKeys(i18nSettings.availableLocales);
            $translateProvider.fallbackLanguage(i18nSettings.defaultLocale);
            $translateProvider.determinePreferredLanguage();
            $translateProvider.useSanitizeValueStrategy('escapeParameters');

            // Configure piwik
            angularPiwikProvider.enableTracking(piwikSettings.enabled);
            if (piwikSettings.enabled) {
                angularPiwikProvider.setPiwikDomain(piwikSettings.domain);
                angularPiwikProvider.setSiteId(piwikSettings.siteId);
            }
        }
    ]);

    // Add $onRootScope method for pub/sub
    // See https://github.com/angular/angular.js/issues/4574
    veganautModule.config(['$provide', function($provide) {
        $provide.decorator('$rootScope', ['$delegate', function($delegate) {

            $delegate.constructor.prototype.$onRootScope = function(name, listener) {
                var unsubscribe = $delegate.$on(name, listener);
                this.$on('$destroy', unsubscribe);
            };

            return $delegate;
        }]);
    }]);

    // Main module for components that don't belong anywhere particular
    var mainModule = angular.module('veganaut.app.main', []);

    // Define the different modules of the app
    var locationModule = angular.module('veganaut.app.location', []);
    var mapModule = angular.module('veganaut.app.map', []);
    var missionsModule = angular.module('veganaut.app.missions', []);
    var communityModule = angular.module('veganaut.app.community', []);
    var userModule = angular.module('veganaut.app.user', []);

    // Make Leaflet available as angular service
    mapModule.value('Leaflet', window.L);

    window.veganaut = {
        mainModule: mainModule,
        locationModule: locationModule,
        mapModule: mapModule,
        missionsModule: missionsModule,
        communityModule: communityModule,
        userModule: userModule
    };
})();
<commit_msg>Correcting redirect for old list urls<commit_after>(function() {
    'use strict';

    // Declare the main module taking all other modules together
    var veganautModule = angular.module('veganaut.app', [
        'ngRoute',
        'ngSanitize',
        'ui.bootstrap',
        'angular-loading-bar',
        'leaflet-directive',
        'pascalprecht.translate',
        'veganaut.ui',
        'veganaut.alert',
        'veganaut.form',
        'veganaut.geocode',
        'veganaut.angularPiwik',
        'veganaut.app.templates',
        'veganaut.app.main',
        'veganaut.app.session',
        'veganaut.app.backend',
        'veganaut.app.location',
        'veganaut.app.map',
        'veganaut.app.missions',
        'veganaut.app.community',
        'veganaut.app.user'
    ]);

    veganautModule.config([
        '$routeProvider', '$locationProvider', '$compileProvider', '$translateProvider',
        'angularPiwikProvider', 'appSettings', 'piwikSettings', 'i18nSettings',
        function($routeProvider, $locationProvider, $compileProvider, $translateProvider,
            angularPiwikProvider, appSettings, piwikSettings, i18nSettings)
        {
            // Configure general settings
            $locationProvider.html5Mode(appSettings.html5Mode);
            $compileProvider.debugInfoEnabled(appSettings.debugInfo);

            // Set up routes
            $routeProvider.when('/register', {template: '<vg-register></vg-register>'});
            $routeProvider.when('/login', {templateUrl: '/veganaut/user/login.tpl.html', controller: 'LoginCtrl'});
            $routeProvider.when('/forgot', {templateUrl: '/veganaut/user/forgot.tpl.html'});
            $routeProvider.when('/reset/:token', {templateUrl: '/veganaut/user/reset.tpl.html'});

            $routeProvider.when('/', {templateUrl: '/veganaut/home/home.tpl.html'});
            $routeProvider.when('/map', {
                templateUrl: '/veganaut/map/map.tpl.html',
                // Don't reload when get params or hash changes
                reloadOnSearch: false
            });

            // Location list (with trailing slash for Piwik)
            $routeProvider.when('/list/locations/', {template: '<vg-location-list></vg-location-list>'});
            $routeProvider.when('/location/:id', {templateUrl: '/veganaut/map/locationDetails.tpl.html'});
            $routeProvider.when('/location/:id/edit', {templateUrl: '/veganaut/map/editLocation.tpl.html'});
            $routeProvider.when('/me', {templateUrl: '/veganaut/user/profile.tpl.html'});
            $routeProvider.when('/me/edit', {templateUrl: '/veganaut/user/editProfile.tpl.html'});
            $routeProvider.when('/community', {templateUrl: '/veganaut/community/community.tpl.html'});
            $routeProvider.when('/veganaut/:personId', {templateUrl: '/veganaut/user/person.tpl.html', controller: 'PersonCtrl'});

            // Legacy URL redirects
            $routeProvider.when('/score', {redirectTo: '/community'});
            $routeProvider.when('/list', {redirectTo: '/list/locations/'});

            $routeProvider.otherwise({redirectTo: '/'});
            // TODO: make sure only routes are accessed that are allowed for the current situation (e.g. logged out)

            // Set up translations
            $translateProvider.useStaticFilesLoader({
                prefix: 'locale/',
                suffix: '.json'
            });
            $translateProvider.registerAvailableLanguageKeys(i18nSettings.availableLocales);
            $translateProvider.fallbackLanguage(i18nSettings.defaultLocale);
            $translateProvider.determinePreferredLanguage();
            $translateProvider.useSanitizeValueStrategy('escapeParameters');

            // Configure piwik
            angularPiwikProvider.enableTracking(piwikSettings.enabled);
            if (piwikSettings.enabled) {
                angularPiwikProvider.setPiwikDomain(piwikSettings.domain);
                angularPiwikProvider.setSiteId(piwikSettings.siteId);
            }
        }
    ]);

    // Add $onRootScope method for pub/sub
    // See https://github.com/angular/angular.js/issues/4574
    veganautModule.config(['$provide', function($provide) {
        $provide.decorator('$rootScope', ['$delegate', function($delegate) {

            $delegate.constructor.prototype.$onRootScope = function(name, listener) {
                var unsubscribe = $delegate.$on(name, listener);
                this.$on('$destroy', unsubscribe);
            };

            return $delegate;
        }]);
    }]);

    // Main module for components that don't belong anywhere particular
    var mainModule = angular.module('veganaut.app.main', []);

    // Define the different modules of the app
    var locationModule = angular.module('veganaut.app.location', []);
    var mapModule = angular.module('veganaut.app.map', []);
    var missionsModule = angular.module('veganaut.app.missions', []);
    var communityModule = angular.module('veganaut.app.community', []);
    var userModule = angular.module('veganaut.app.user', []);

    // Make Leaflet available as angular service
    mapModule.value('Leaflet', window.L);

    window.veganaut = {
        mainModule: mainModule,
        locationModule: locationModule,
        mapModule: mapModule,
        missionsModule: missionsModule,
        communityModule: communityModule,
        userModule: userModule
    };
})();
<|endoftext|>


<commit_before>'use strict';

var fs        = require('fs')
  , resolve   = require('path').resolve
  , deferred  = require('deferred')
  , delay     = deferred.delay
  , promisify = deferred.promisify
  , mkdir     = promisify(fs.mkdir)
  , open      = promisify(fs.open)
  , rename    = promisify(fs.rename)
  , write     = promisify(fs.write)
  , close     = promisify(fs.close)
  , writeFile = promisify(fs.writeFile)
  , unlink    = promisify(fs.unlink)
  , rmdir     = promisify(fs.rmdir)

  , pgPath = resolve(__dirname, '../__playground/_watch-alt')

module.exports = function (t, a, d) {
	var ondirchange = 0, onfilechange = 0, ondirend = 0, onfileend = 0, tmpPath
	  , DELAY = 100, DELAYWAIT = 2000
	  , tmpFilePath, alt
	  , dirPath = resolve(pgPath, 'tmpdir')
	  , filePath = resolve(dirPath, 'tmpfile')
	  , dirCurrent, fileCurrent

	a.throws(function () {
		t(filePath);
	}, "Not existing");

	delay(function () {
		return mkdir(dirPath);
	}, DELAY)()(function () {
		var dirWatch;
		dirWatch = t(dirPath);
		dirWatch.on('change', function (e) { ++ondirchange; });
		dirWatch.on('end', function (e) { ++ondirend; });
	})(delay(function () {
		return writeFile(filePath, 'raz');
	}, DELAY))(delay(function () {
		var fileWatch;
		a(ondirchange, 1, "Dir change: File created");
		a(ondirend, 0, "Dir end: File created");
		ondirchange = ondirend = 0;
		fileWatch = t(filePath);
		fileWatch.on('change', function () { ++onfilechange });
		fileWatch.on('end', function () { ++onfileend });
	}, DELAYWAIT))(delay(function () {
		return open(filePath, 'a')(function (fd) {
			return write(fd, new Buffer('dwatrzy'), 0, 3, null)(function () {
				return close(fd);
			});
		});
	}, DELAY))(delay(function () {
		a(ondirchange, 0, "Dir change: File changed");
		a(ondirend, 0, "Dir end: File changed");
		a(onfilechange, 1, "File change: File created");
		a(onfileend, 0, "File end: File created");
		ondirchange = ondirend = onfilechange = onfileend = 0;
		return rename(filePath, filePath + 'r');
	}, DELAYWAIT))(delay(function () {
		a(ondirchange, 1, "Dir change: File renamed");
		a(ondirend, 0, "Dir end: File renamed");
		a(onfilechange, 0, "File change: File renamed");
		a(onfileend, 1, "File end: File renamed");
		ondirchange = ondirend = onfilechange = onfileend = 0;
		return rename(filePath + 'r', filePath);
	}, DELAYWAIT))(delay(function () {
		a(ondirchange, 1, "Dir change: File renamed back");
		a(ondirend, 0, "Dir end: File renamed back");
		a(onfilechange, 0, "File change: File renamed back");
		a(onfileend, 0, "File end: File renamed back");
		ondirchange = ondirend = onfilechange = onfileend = 0;
		return unlink(filePath);
	}, DELAYWAIT))(delay(function () {
		a(ondirchange, 1, "Dir change: File removed");
		a(ondirend, 0, "Dir end: File removed");
		a(onfilechange, 0, "File change: File removed");
		a(onfileend, 0, "File end: File removed");
		ondirchange = ondirend = onfilechange = onfileend = 0;
		return rmdir(dirPath);
	}, DELAYWAIT))(delay(function () {
		a(ondirchange, 0, "Dir change: Dir removed");
		a(ondirend, 1, "Dir end: Dir removed");
		a(onfilechange, 0, "File change: Dir removed");
		a(onfileend, 0, "File end: Dir removed");
	}, DELAYWAIT)).end(d);
};
<commit_msg>(tests) Longer wait time between file system changes<commit_after>'use strict';

var fs        = require('fs')
  , resolve   = require('path').resolve
  , deferred  = require('deferred')
  , delay     = deferred.delay
  , promisify = deferred.promisify
  , mkdir     = promisify(fs.mkdir)
  , open      = promisify(fs.open)
  , rename    = promisify(fs.rename)
  , write     = promisify(fs.write)
  , close     = promisify(fs.close)
  , writeFile = promisify(fs.writeFile)
  , unlink    = promisify(fs.unlink)
  , rmdir     = promisify(fs.rmdir)

  , pgPath = resolve(__dirname, '../__playground/_watch-alt')

module.exports = function (t, a, d) {
	var ondirchange = 0, onfilechange = 0, ondirend = 0, onfileend = 0, tmpPath
	  , DELAY = 200, DELAYWAIT = 2000
	  , tmpFilePath, alt
	  , dirPath = resolve(pgPath, 'tmpdir')
	  , filePath = resolve(dirPath, 'tmpfile')
	  , dirCurrent, fileCurrent

	a.throws(function () {
		t(filePath);
	}, "Not existing");

	delay(function () {
		return mkdir(dirPath);
	}, DELAY)()(delay(function () {
		var dirWatch;
		dirWatch = t(dirPath);
		dirWatch.on('change', function (e) { ++ondirchange; });
		dirWatch.on('end', function (e) { ++ondirend; });
	}, DELAY))(delay(function () {
		return writeFile(filePath, 'raz');
	}, DELAY))(delay(function () {
		var fileWatch;
		a(ondirchange, 1, "Dir change: File created");
		a(ondirend, 0, "Dir end: File created");
		ondirchange = ondirend = 0;
		fileWatch = t(filePath);
		fileWatch.on('change', function () { ++onfilechange });
		fileWatch.on('end', function () { ++onfileend });
	}, DELAYWAIT))(delay(function () {
		return open(filePath, 'a')(function (fd) {
			return write(fd, new Buffer('dwatrzy'), 0, 3, null)(function () {
				return close(fd);
			});
		});
	}, DELAY))(delay(function () {
		a(ondirchange, 0, "Dir change: File changed");
		a(ondirend, 0, "Dir end: File changed");
		a(onfilechange, 1, "File change: File created");
		a(onfileend, 0, "File end: File created");
		ondirchange = ondirend = onfilechange = onfileend = 0;
		return rename(filePath, filePath + 'r');
	}, DELAYWAIT))(delay(function () {
		a(ondirchange, 1, "Dir change: File renamed");
		a(ondirend, 0, "Dir end: File renamed");
		a(onfilechange, 0, "File change: File renamed");
		a(onfileend, 1, "File end: File renamed");
		ondirchange = ondirend = onfilechange = onfileend = 0;
		return rename(filePath + 'r', filePath);
	}, DELAYWAIT))(delay(function () {
		a(ondirchange, 1, "Dir change: File renamed back");
		a(ondirend, 0, "Dir end: File renamed back");
		a(onfilechange, 0, "File change: File renamed back");
		a(onfileend, 0, "File end: File renamed back");
		ondirchange = ondirend = onfilechange = onfileend = 0;
		return unlink(filePath);
	}, DELAYWAIT))(delay(function () {
		a(ondirchange, 1, "Dir change: File removed");
		a(ondirend, 0, "Dir end: File removed");
		a(onfilechange, 0, "File change: File removed");
		a(onfileend, 0, "File end: File removed");
		ondirchange = ondirend = onfilechange = onfileend = 0;
		return rmdir(dirPath);
	}, DELAYWAIT))(delay(function () {
		a(ondirchange, 0, "Dir change: Dir removed");
		a(ondirend, 1, "Dir end: Dir removed");
		a(onfilechange, 0, "File change: Dir removed");
		a(onfileend, 0, "File end: Dir removed");
	}, DELAYWAIT)).end(d);
};
<|endoftext|>


<commit_before>function assertSingleActor(d, actor) {

	equal(d.actors.length, 1, "Correct actors count");

	var a = d.actors[0];
	equal(a.name, actor, "Actors A's name");
}

function assertSingleArrow(d, arrowtype, linetype, actorA, actorB, message) {

	actorA = actorA || "A";
	actorB = actorB || "B";
	message = message || "Message";

	equal(d.actors.length, 2, "Correct actors count");

	var a = d.actors[0];
	var b = d.actors[1];
	equal(a.name, actorA, "Actors A name");
	equal(b.name, actorB, "Actors B name");

	equal(d.signals.length, 1, "Correct signals count");
	equal(d.signals[0].type, "Signal", "Correct signal type");
	equal(d.signals[0].actorA, a, "Actors A");
	equal(d.signals[0].actorB, b, "Actors B");

	equal(d.signals[0].message, message, "Signal message");

	equal(d.signals[0].arrowtype, arrowtype, "Arrowhead type");
	equal(d.signals[0].linetype, linetype, "Line type");
}

function assertSingleNote(d, placement, actors, message) {

	message = message || "Message";

	equal(d.signals.length, 1, "Correct notes count");

	var note = d.signals[0];
	equal(note.type, "Note", "Correct signal type");
	equal(note.placement, placement, "Correct signal placement");
	equal(note.message, message, "Correct signal message");

	if (_.isArray(actors)) {
		equal(_.isArray(d.actors), true, "Correct actors array");
		equal(d.actors.length, actors.length, "Correct actors count");

		equal(note.actor.length, actors.length, "Correct note actors");
		for (var i = 0; i < actors.length; i++) {
			equal(d.actors[i].name, actors[i], "Correct actor");
			equal(note.actor[i].name, actors[i], "Correct note actor");
		}

	} else {
		equal(d.actors.length, 1, "Correct actors count");
		equal(note.actor.name, actors, "Correct note actor");
	}
}

function assertEmptyDocument(d) {
	equal(d.title, undefined, "No title");
	equal(d.actors.length,  0, "Zero actors");
	equal(d.signals.length, 0, "Zero signals");
}

var LINETYPE = Diagram.LINETYPE;
var ARROWTYPE = Diagram.ARROWTYPE;
var PLACEMENT = Diagram.PLACEMENT;

function regextest(regex, string) {
	console.log(string, regex.exec(string));
}

/*
test("Regex Tests", function() {
	// These are here to debug regex problems with unicode
	//var r = /[^\->:\n,]+\b/;
	var r = /[^\->:\n,]+/;
	regextest(r, "blah");
	regextest(r, "bl:ah");
	regextest(r, "中国");
	regextest(r, " 中国 ");

	regextest(/^(.+) as (\S+)\s*$/i, "blah");
	regextest(/^(.+) as (\S+)\s*$/i, " as as as b");
});
*/

test( "Solid Arrow", function() {
	var d = Diagram.parse("A->B: Message");
	assertSingleArrow(d, ARROWTYPE.FILLED, LINETYPE.SOLID);
});

test( "Dashed Arrow", function() {
	var d = Diagram.parse("A-->B: Message");
	assertSingleArrow(d, ARROWTYPE.FILLED, LINETYPE.DOTTED);
});

test( "Solid Open Arrow", function() {
	var d = Diagram.parse("A->>B: Message");
	assertSingleArrow(d, ARROWTYPE.OPEN, LINETYPE.SOLID);
});

test( "Dashed Open Arrow", function() {
	var d = Diagram.parse("A-->>B: Message");
	assertSingleArrow(d, ARROWTYPE.OPEN, LINETYPE.DOTTED);
});

test( "Titles", function() {
	equal(Diagram.parse("Title: title").title, "title", "Title");
	equal(Diagram.parse("Title: line1\\nline2").title, "line1\nline2", "Multiline Title");
});

test( "Unicode", function() {
	equal(Diagram.parse("Title: 中国").title, "中国", "Unicode Title");
	assertEmptyDocument(Diagram.parse("# 中国"));
	assertSingleActor(Diagram.parse("Participant 中国"), "中国");
	assertSingleActor(Diagram.parse("Participant 中国 as alias"), "中国");
	assertSingleActor(Diagram.parse("中国->中国: Message"), "中国");
});

test( "Empty documents", function() {
	assertEmptyDocument(Diagram.parse(""));
	assertEmptyDocument(Diagram.parse(" \t\n"));
	assertEmptyDocument(Diagram.parse("\r\n\r\n"));
});

test( "Whitespace", function() {
	assertSingleArrow(Diagram.parse("  A  -  > B  : Message  "), ARROWTYPE.FILLED, LINETYPE.SOLID);
	assertSingleArrow(Diagram.parse("\n\nA->B: Message\n\n"), ARROWTYPE.FILLED, LINETYPE.SOLID);
});

test( "Comments", function() {
	// Comments must be on lines on their own
	assertEmptyDocument(Diagram.parse("#"));
	assertEmptyDocument(Diagram.parse("# comment"));
	assertEmptyDocument(Diagram.parse(" # comment"));
	assertEmptyDocument(Diagram.parse("# A->B: Title"));

	// If # is encountered elsewhere, it is part of the names
	assertSingleArrow(Diagram.parse("A#->B: Message"), ARROWTYPE.FILLED, LINETYPE.SOLID, "A#", "B");
	assertSingleArrow(Diagram.parse("A->B#: Message"), ARROWTYPE.FILLED, LINETYPE.SOLID, "A", "B#");
	assertSingleArrow(Diagram.parse("A->B: Message # not a comment"), ARROWTYPE.FILLED, LINETYPE.SOLID, "A", "B", "Message # not a comment");

	equal(Diagram.parse("Title: title # not a comment").title, "title # not a comment");
	assertSingleNote(Diagram.parse("note left of A: Message # not a comment"), PLACEMENT.LEFTOF, "A", "Message # not a comment");
});

test( "Notes", function() {
	assertSingleNote(Diagram.parse("Note left of A: Message"), PLACEMENT.LEFTOF, 'A');
	assertSingleNote(Diagram.parse("Note right of A: Message"), PLACEMENT.RIGHTOF, 'A');
	assertSingleNote(Diagram.parse("Note over A: Message"), PLACEMENT.OVER, 'A');
	assertSingleNote(Diagram.parse("Note over A,B: Message"), PLACEMENT.OVER, ['A', 'B']);

	// We don't allow "as X" when referencing an actor
	assertSingleNote(Diagram.parse("Note over C as A,B: Message"), PLACEMENT.OVER, ['C as A', 'B']);
});

test( "Participants", function() {
	assertSingleActor(Diagram.parse("Participant Bob"), "Bob");
	assertSingleActor(Diagram.parse("Participant Name with spaces"), "Name with spaces");
	assertSingleActor(Diagram.parse("Participant Name with spaces as alias"), "Name with spaces");
	assertSingleActor(Diagram.parse("Participant Name with 'as' in it"), "Name with 'as' in it");
	assertSingleActor(Diagram.parse("Participant Bob \\n with newline"), "Bob \n with newline");
	assertSingleActor(Diagram.parse("Participant Bob \\n with newline as alias"), "Bob \n with newline");
	assertSingleActor(Diagram.parse("Participant Object"), "Object");
});

test( "Newlines", function() {
	assertSingleActor(Diagram.parse("Participant A\nNote left of A: Hello"), "A");
	assertSingleActor(Diagram.parse("Participant A\rNote left of A: Hello"), "A");
	assertSingleActor(Diagram.parse("Participant A\r\nNote left of A: Hello"), "A");
});
<commit_msg>Test to ensure the public API stays the same.<commit_after>function assertSingleActor(d, actor) {

	equal(d.actors.length, 1, "Correct actors count");

	var a = d.actors[0];
	equal(a.name, actor, "Actors A's name");
}

function assertSingleArrow(d, arrowtype, linetype, actorA, actorB, message) {

	actorA = actorA || "A";
	actorB = actorB || "B";
	message = message || "Message";

	equal(d.actors.length, 2, "Correct actors count");

	var a = d.actors[0];
	var b = d.actors[1];
	equal(a.name, actorA, "Actors A name");
	equal(b.name, actorB, "Actors B name");

	equal(d.signals.length, 1, "Correct signals count");
	equal(d.signals[0].type, "Signal", "Correct signal type");
	equal(d.signals[0].actorA, a, "Actors A");
	equal(d.signals[0].actorB, b, "Actors B");

	equal(d.signals[0].message, message, "Signal message");

	equal(d.signals[0].arrowtype, arrowtype, "Arrowhead type");
	equal(d.signals[0].linetype, linetype, "Line type");
}

function assertSingleNote(d, placement, actors, message) {

	message = message || "Message";

	equal(d.signals.length, 1, "Correct notes count");

	var note = d.signals[0];
	equal(note.type, "Note", "Correct signal type");
	equal(note.placement, placement, "Correct signal placement");
	equal(note.message, message, "Correct signal message");

	if (_.isArray(actors)) {
		equal(_.isArray(d.actors), true, "Correct actors array");
		equal(d.actors.length, actors.length, "Correct actors count");

		equal(note.actor.length, actors.length, "Correct note actors");
		for (var i = 0; i < actors.length; i++) {
			equal(d.actors[i].name, actors[i], "Correct actor");
			equal(note.actor[i].name, actors[i], "Correct note actor");
		}

	} else {
		equal(d.actors.length, 1, "Correct actors count");
		equal(note.actor.name, actors, "Correct note actor");
	}
}

function assertEmptyDocument(d) {
	equal(d.title, undefined, "No title");
	equal(d.actors.length,  0, "Zero actors");
	equal(d.signals.length, 0, "Zero signals");
}

var LINETYPE = Diagram.LINETYPE;
var ARROWTYPE = Diagram.ARROWTYPE;
var PLACEMENT = Diagram.PLACEMENT;

/*
function regextest(regex, string) {
	console.log(string, regex.exec(string));
}

test("Regex Tests", function() {
	// These are here to debug regex problems with unicode
	//var r = /[^\->:\n,]+\b/;
	var r = /[^\->:\n,]+/;
	regextest(r, "blah");
	regextest(r, "bl:ah");
	regextest(r, "中国");
	regextest(r, " 中国 ");

	regextest(/^(.+) as (\S+)\s*$/i, "blah");
	regextest(/^(.+) as (\S+)\s*$/i, " as as as b");
});
*/

test( "Solid Arrow", function() {
	var d = Diagram.parse("A->B: Message");
	assertSingleArrow(d, ARROWTYPE.FILLED, LINETYPE.SOLID);
});

test( "Dashed Arrow", function() {
	var d = Diagram.parse("A-->B: Message");
	assertSingleArrow(d, ARROWTYPE.FILLED, LINETYPE.DOTTED);
});

test( "Solid Open Arrow", function() {
	var d = Diagram.parse("A->>B: Message");
	assertSingleArrow(d, ARROWTYPE.OPEN, LINETYPE.SOLID);
});

test( "Dashed Open Arrow", function() {
	var d = Diagram.parse("A-->>B: Message");
	assertSingleArrow(d, ARROWTYPE.OPEN, LINETYPE.DOTTED);
});

test( "Titles", function() {
	equal(Diagram.parse("Title: title").title, "title", "Title");
	equal(Diagram.parse("Title: line1\\nline2").title, "line1\nline2", "Multiline Title");
});

test( "Unicode", function() {
	equal(Diagram.parse("Title: 中国").title, "中国", "Unicode Title");
	assertEmptyDocument(Diagram.parse("# 中国"));
	assertSingleActor(Diagram.parse("Participant 中国"), "中国");
	assertSingleActor(Diagram.parse("Participant 中国 as alias"), "中国");
	assertSingleActor(Diagram.parse("中国->中国: Message"), "中国");
});

test( "Empty documents", function() {
	assertEmptyDocument(Diagram.parse(""));
	assertEmptyDocument(Diagram.parse(" \t\n"));
	assertEmptyDocument(Diagram.parse("\r\n\r\n"));
});

test( "Whitespace", function() {
	assertSingleArrow(Diagram.parse("  A  -  > B  : Message  "), ARROWTYPE.FILLED, LINETYPE.SOLID);
	assertSingleArrow(Diagram.parse("\n\nA->B: Message\n\n"), ARROWTYPE.FILLED, LINETYPE.SOLID);
});

test( "Comments", function() {
	// Comments must be on lines on their own
	assertEmptyDocument(Diagram.parse("#"));
	assertEmptyDocument(Diagram.parse("# comment"));
	assertEmptyDocument(Diagram.parse(" # comment"));
	assertEmptyDocument(Diagram.parse("# A->B: Title"));

	// If # is encountered elsewhere, it is part of the names
	assertSingleArrow(Diagram.parse("A#->B: Message"), ARROWTYPE.FILLED, LINETYPE.SOLID, "A#", "B");
	assertSingleArrow(Diagram.parse("A->B#: Message"), ARROWTYPE.FILLED, LINETYPE.SOLID, "A", "B#");
	assertSingleArrow(Diagram.parse("A->B: Message # not a comment"), ARROWTYPE.FILLED, LINETYPE.SOLID, "A", "B", "Message # not a comment");

	equal(Diagram.parse("Title: title # not a comment").title, "title # not a comment");
	assertSingleNote(Diagram.parse("note left of A: Message # not a comment"), PLACEMENT.LEFTOF, "A", "Message # not a comment");
});

test( "Notes", function() {
	assertSingleNote(Diagram.parse("Note left of A: Message"), PLACEMENT.LEFTOF, 'A');
	assertSingleNote(Diagram.parse("Note right of A: Message"), PLACEMENT.RIGHTOF, 'A');
	assertSingleNote(Diagram.parse("Note over A: Message"), PLACEMENT.OVER, 'A');
	assertSingleNote(Diagram.parse("Note over A,B: Message"), PLACEMENT.OVER, ['A', 'B']);

	// We don't allow "as X" when referencing an actor
	assertSingleNote(Diagram.parse("Note over C as A,B: Message"), PLACEMENT.OVER, ['C as A', 'B']);
});

test( "Participants", function() {
	assertSingleActor(Diagram.parse("Participant Bob"), "Bob");
	assertSingleActor(Diagram.parse("Participant Name with spaces"), "Name with spaces");
	assertSingleActor(Diagram.parse("Participant Name with spaces as alias"), "Name with spaces");
	assertSingleActor(Diagram.parse("Participant Name with 'as' in it"), "Name with 'as' in it");
	assertSingleActor(Diagram.parse("Participant Bob \\n with newline"), "Bob \n with newline");
	assertSingleActor(Diagram.parse("Participant Bob \\n with newline as alias"), "Bob \n with newline");
	assertSingleActor(Diagram.parse("Participant Object"), "Object");
});

test( "Newlines", function() {
	assertSingleActor(Diagram.parse("Participant A\nNote left of A: Hello"), "A");
	assertSingleActor(Diagram.parse("Participant A\rNote left of A: Hello"), "A");
	assertSingleActor(Diagram.parse("Participant A\r\nNote left of A: Hello"), "A");
});

test( "API", function() {
	// Public API
	ok(typeof Diagram.parse == "function");

	var d = Diagram.parse("Participant A");
	ok(d instanceof Diagram);
	ok(typeof d.drawSVG == "function");

	// Private API
	ok(typeof d.getActor == "function");
	ok(typeof d.getActorWithAlias == "function");
	ok(typeof d.setTitle == "function");
	ok(typeof d.addSignal == "function");
});<|endoftext|>