<commit_before>import test from 'tape'
import QueryBuilder from '../src/query-builder'

test('QueryBuilder should build query with no field', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('match_all')

  t.deepEqual(result._queries, {
    match_all: {}
  })
})

test('QueryBuilder should build query with field but no value', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('exists', 'user')

  t.deepEqual(result._queries, {
    exists: {
      field: 'user'
    }
  })
})

test('QueryBuilder should build query with field and value', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('term', 'user', 'kimchy')

  t.deepEqual(result._queries, {
    term: {
      user: 'kimchy'
    }
  })
})

test('QueryBuilder should build query with field and object value', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('range', 'date', {gt: 'now-1d'})

  t.deepEqual(result._queries, {
    range: {
      date: {gt: 'now-1d'}
    }
  })
})

test('QueryBuilder should build query with more options', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('geo_distance', 'point', {lat: 40, lon: 20}, {distance: '12km'})

  t.deepEqual(result._queries, {
    geo_distance: {
      distance: '12km',
      point: {
        lat: 40,
        lon: 20
      }
    }
  })
})

test('QueryBuilder should build nested queries', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('nested', 'path', 'obj1', (q) => q.query('match', 'obj1.color', 'blue'))

  t.deepEqual(result._queries, {
    nested: {
      path: 'obj1',
      query: {
        match: {
          'obj1.color': 'blue'
        }
      }
    }
  })
})

test('QueryBuilder should nest bool-merged queries', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('nested', 'path', 'obj1', {score_mode: 'avg'}, (q) => {
    return q.query('match', 'obj1.name', 'blue').query('range', 'obj1.count', {gt: 5})
  })

  t.deepEqual(result._queries, {
    nested: {
      path: 'obj1',
      score_mode: 'avg',
      query: {
        bool: {
          must: [
            {
              match: {'obj1.name': 'blue'}
            },
            {
              range: {'obj1.count': {gt: 5}}
            }
          ]
        }
      }
    }
  })
})

test('QueryBuilder should make this chained nested query', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('match', 'title', 'eggs').query('nested', 'path', 'comments', {score_mode: 'max'} , (q) => {
      return q.query('match', 'comments.name', 'john').query('match', 'comments.age', 28)
  })

  t.deepEqual(result._queries, {
    bool: {
      must: [
        {
          match: {
            title: 'eggs'
          }
        },
        {
          nested: {
            path: 'comments',
            score_mode: 'max',
            query: {
              bool: {
                must: [
                  {
                    match: {
                      'comments.name': 'john'
                    }
                  },
                  {
                    match: {
                      'comments.age': 28
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  })
})

test('QueryBuilder should create this big-ass query', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('constant_score', '', '', {}, (q) => {
    return q.orFilter('term', 'created_by.user_id', 'abc')
            .orFilter('nested', 'path', 'doc_meta', {}, (q) => {
              return q.query('constant_score', '', '', {}, (q) => {
                return q.filter('term', 'doc_meta.user_id', 'abc')
              })
            })
            .orFilter('nested', 'path', 'tests', {}, (q) => {
              return q.query('constant_score', '', '', {}, (q) => {
                return q.filter('term', 'tests.created_by.user_id', 'abc')
              })
            })
          })

  console.log(""+JSON.stringify(result._queries))

  t.deepEqual(result._queries, {
    constant_score: {
      filter: {
        bool: {
          should: [
            {
              term: {
                'created_by.user_id': 'abc'
              }
            }, {
              nested: {
                path: 'doc_meta',
                query: {
                  constant_score: {
                    filter: {
                      term: {
                        'doc_meta.user_id': 'abc'
                      }
                    }
                  }
                }
              }
            }, {
              nested: {
                path: 'tests',
                query: {
                  constant_score: {
                    filter: {
                      term: {
                        'tests.created_by.user_id': 'abc'
                      }
                    }
                  }
                }
              }
            }
          ]
        }
      }
    }
  })
})

<commit_msg>ops... forgot a 'console.log()' statement... my bad<commit_after>import test from 'tape'
import QueryBuilder from '../src/query-builder'

test('QueryBuilder should build query with no field', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('match_all')

  t.deepEqual(result._queries, {
    match_all: {}
  })
})

test('QueryBuilder should build query with field but no value', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('exists', 'user')

  t.deepEqual(result._queries, {
    exists: {
      field: 'user'
    }
  })
})

test('QueryBuilder should build query with field and value', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('term', 'user', 'kimchy')

  t.deepEqual(result._queries, {
    term: {
      user: 'kimchy'
    }
  })
})

test('QueryBuilder should build query with field and object value', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('range', 'date', {gt: 'now-1d'})

  t.deepEqual(result._queries, {
    range: {
      date: {gt: 'now-1d'}
    }
  })
})

test('QueryBuilder should build query with more options', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('geo_distance', 'point', {lat: 40, lon: 20}, {distance: '12km'})

  t.deepEqual(result._queries, {
    geo_distance: {
      distance: '12km',
      point: {
        lat: 40,
        lon: 20
      }
    }
  })
})

test('QueryBuilder should build nested queries', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('nested', 'path', 'obj1', (q) => q.query('match', 'obj1.color', 'blue'))

  t.deepEqual(result._queries, {
    nested: {
      path: 'obj1',
      query: {
        match: {
          'obj1.color': 'blue'
        }
      }
    }
  })
})

test('QueryBuilder should nest bool-merged queries', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('nested', 'path', 'obj1', {score_mode: 'avg'}, (q) => {
    return q.query('match', 'obj1.name', 'blue').query('range', 'obj1.count', {gt: 5})
  })

  t.deepEqual(result._queries, {
    nested: {
      path: 'obj1',
      score_mode: 'avg',
      query: {
        bool: {
          must: [
            {
              match: {'obj1.name': 'blue'}
            },
            {
              range: {'obj1.count': {gt: 5}}
            }
          ]
        }
      }
    }
  })
})

test('QueryBuilder should make this chained nested query', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('match', 'title', 'eggs').query('nested', 'path', 'comments', {score_mode: 'max'} , (q) => {
      return q.query('match', 'comments.name', 'john').query('match', 'comments.age', 28)
  })

  t.deepEqual(result._queries, {
    bool: {
      must: [
        {
          match: {
            title: 'eggs'
          }
        },
        {
          nested: {
            path: 'comments',
            score_mode: 'max',
            query: {
              bool: {
                must: [
                  {
                    match: {
                      'comments.name': 'john'
                    }
                  },
                  {
                    match: {
                      'comments.age': 28
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  })
})

test('QueryBuilder should create this big-ass query', (t) => {
  t.plan(1)

  const result = new QueryBuilder().query('constant_score', '', '', {}, (q) => {
    return q.orFilter('term', 'created_by.user_id', 'abc')
            .orFilter('nested', 'path', 'doc_meta', {}, (q) => {
              return q.query('constant_score', '', '', {}, (q) => {
                return q.filter('term', 'doc_meta.user_id', 'abc')
              })
            })
            .orFilter('nested', 'path', 'tests', {}, (q) => {
              return q.query('constant_score', '', '', {}, (q) => {
                return q.filter('term', 'tests.created_by.user_id', 'abc')
              })
            })
          })

  t.deepEqual(result._queries, {
    constant_score: {
      filter: {
        bool: {
          should: [
            {
              term: {
                'created_by.user_id': 'abc'
              }
            }, {
              nested: {
                path: 'doc_meta',
                query: {
                  constant_score: {
                    filter: {
                      term: {
                        'doc_meta.user_id': 'abc'
                      }
                    }
                  }
                }
              }
            }, {
              nested: {
                path: 'tests',
                query: {
                  constant_score: {
                    filter: {
                      term: {
                        'tests.created_by.user_id': 'abc'
                      }
                    }
                  }
                }
              }
            }
          ]
        }
      }
    }
  })
})

<|endoftext|>


<commit_before>var sightengine = require('./sightengine')('1234','test');
var assert = require('assert');
var fs = require('fs');
var path = require('path');

describe('test feedback', function() {
  it('should return success', function(done) {
    sightengine.feedback('nudity', 'safe', 'https://sightengine.com/assets/img/examples/example5.jpg').then((result) => {
      done(assert.equal('success', result.status))
    })
  });

  it('should return error', function(done) {
    sightengine.feedback('nudity', 'safe', 'https://sightengine.com/assets/img/examples/example99999.jpg').then((result) => {
      done(assert.equal('failure', result.status))
    })
  });
});

describe('test image moderation', function() {
  it('should return success', function(done) {
    sightengine.check(['nudity', 'type', 'properties','wad','faces', 'celebrities']).set_url('https://sightengine.com/assets/img/examples/example5.jpg').then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    sightengine.check(['nudity']).set_url('https://sightengine.com/assets/img/examples/example5.jpg').then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    sightengine.check(['nudity', 'type', 'properties','wad','faces', 'celebrities']).set_file(path.resolve(__dirname, 'assets', 'image.jpg')).then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    sightengine.check(['celebrities']).set_file(path.resolve(__dirname, 'assets', 'image.jpg')).then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    var binaryImage = fs.createReadStream(path.resolve(__dirname, 'assets', 'image.jpg'));

    sightengine.check(['nudity']).set_bytes(binaryImage).then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    var binaryImage = fs.createReadStream(path.resolve(__dirname, 'assets', 'image.jpg'));

    sightengine.check(['nudity', 'type', 'properties','wad','faces', 'celebrities']).set_bytes(binaryImage).then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return error', function(done) {
    sightengine.check(['nudity','wad','properties','type','faces','celebrities']).set_url('https://sightengine.com/assets/img/examples/example99999.jpg').then(function(result) {
      done(assert.equal('failure', result.status))
    })
  });
});

describe('video moderation', function() {
  it('should return success', function(done) {
    this.timeout(60000);
    sightengine.check(['nudity','wad','properties','type','face','celebrities']).video('https://sightengine.com/assets/stream/examples/funfair.mp4', 'http://requestb.in/1d097l71').then(function(result) {
      done(assert.equal('success', result.status))
    })
  });
});

<commit_msg>change position timeout<commit_after>var sightengine = require('./sightengine')('1234','test');
var assert = require('assert');
var fs = require('fs');
var path = require('path');

describe('test feedback', function() {
  it('should return success', function(done) {
    sightengine.feedback('nudity', 'safe', 'https://sightengine.com/assets/img/examples/example5.jpg').then((result) => {
      done(assert.equal('success', result.status))
    })
  });

  it('should return error', function(done) {
    sightengine.feedback('nudity', 'safe', 'https://sightengine.com/assets/img/examples/example99999.jpg').then((result) => {
      done(assert.equal('failure', result.status))
    })
  });
});

describe('test image moderation', function() {
  it('should return success', function(done) {
    sightengine.check(['nudity', 'type', 'properties','wad','faces', 'celebrities']).set_url('https://sightengine.com/assets/img/examples/example5.jpg').then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    sightengine.check(['nudity']).set_url('https://sightengine.com/assets/img/examples/example5.jpg').then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    sightengine.check(['nudity', 'type', 'properties','wad','faces', 'celebrities']).set_file(path.resolve(__dirname, 'assets', 'image.jpg')).then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    sightengine.check(['celebrities']).set_file(path.resolve(__dirname, 'assets', 'image.jpg')).then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    var binaryImage = fs.createReadStream(path.resolve(__dirname, 'assets', 'image.jpg'));

    sightengine.check(['nudity']).set_bytes(binaryImage).then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return success', function(done) {
    var binaryImage = fs.createReadStream(path.resolve(__dirname, 'assets', 'image.jpg'));

    sightengine.check(['nudity', 'type', 'properties','wad','faces', 'celebrities']).set_bytes(binaryImage).then(function(result) {
      done(assert.equal('success', result.status))
    })
  });

  it('should return error', function(done) {
    sightengine.check(['nudity','wad','properties','type','faces','celebrities']).set_url('https://sightengine.com/assets/img/examples/example99999.jpg').then(function(result) {
      done(assert.equal('failure', result.status))
    })
  });
});

describe('video moderation', function() {
  it('should return success', function(done) {
    sightengine.check(['nudity','wad','properties','type','face','celebrities']).video('https://sightengine.com/assets/stream/examples/funfair.mp4', 'http://requestb.in/1d097l71').then(function(result) {
      this.timeout(60000);
      done(assert.equal('success', result.status))
    })
  });
});

<|endoftext|>


<commit_before>var vows = require('vows'),
    assert = require('assert');

var readonly = require('../lib/index.js');
var UnableRewriteException = require('../lib/UnableRewriteException.js');
var _ = require('underscore');

vows.describe('ReadOnly function').addBatch({
    'Restrict rewrite': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },

        'Writable from module A': function (topic) {
            var moduleA = {};
            moduleA.obj = topic;
            moduleA.obj.A = 'd';
            assert.equal(moduleA.obj.A, 'd');
        },

        'Not writable from module B': function (topic) {
            var moduleB = {};
            moduleB.obj = readonly(topic);
            assert.throws(function() { moduleB.obj.B = 'b'; }, UnableRewriteException);
        },
    },

    'Update and rewrite': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },

        'can rewrite from A and access from B': function (topic) {
            var moduleA = {};
            var moduleB = {};
            moduleA.obj = topic;
            moduleB.obj = readonly(topic);
            moduleA.obj.A = 'd';

            assert.equal(moduleB.obj.A, 'd');
        }
    },

    'Reference of _original': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },
        'cannot refer _original': function(topic) {
            var moduleB = {};
            moduleB.obj = readonly(topic);
        }
    },

    'Extends test': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },

        'can copy': function(obj) {
            var obj2 = _.clone(obj);
            obj2.A = 'd';
            assert.equal(obj.A, 'a');
        }
    },

    'Getter Test': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            var cloned = {};

            function makeReadOnlyProperty(cloned, obj, prop) {
                Object.defineProperty(cloned, prop, {
                    set: function() {
                        throw new UnableRewriteException('original cannot be rewrite');
                    },
                    get: function() {
                        return obj[prop]
                    },
                    enumerable: true
                });
            }

            for (var prop in obj) {
                makeReadOnlyProperty(cloned, obj, prop);
            }

            /*
            function makeGetter(prop) {
                return function() {
                    var p = prop;
                    return obj[p];
                };
            }

            var _cloned = {};
            for (var prop in obj) {
                var getter = makeGetter(prop);
                Object.defineProperty(_cloned, prop, {
                    set: function() {
                        throw new UnableRewriteException('original cannot be rewrite');
                    },
                    get: function() {
                        return obj[prop]
                    },
                    enumerable: true
                });
                _cloned[prop];
            }
            */
            return cloned;
        },

        'get a': function(obj) {
            assert.equal(obj.A, 'a');
        }
    }

}).export(module); // Export the Suite<commit_msg>Also remove from test<commit_after>var vows = require('vows'),
    assert = require('assert');

var readonly = require('../lib/index.js');
var UnableRewriteException = require('../lib/UnableRewriteException.js');

vows.describe('ReadOnly function').addBatch({
    'Restrict rewrite': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },

        'Writable from module A': function (topic) {
            var moduleA = {};
            moduleA.obj = topic;
            moduleA.obj.A = 'd';
            assert.equal(moduleA.obj.A, 'd');
        },

        'Not writable from module B': function (topic) {
            var moduleB = {};
            moduleB.obj = readonly(topic);
            assert.throws(function() { moduleB.obj.B = 'b'; }, UnableRewriteException);
        },
    },

    'Update and rewrite': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },

        'can rewrite from A and access from B': function (topic) {
            var moduleA = {};
            var moduleB = {};
            moduleA.obj = topic;
            moduleB.obj = readonly(topic);
            moduleA.obj.A = 'd';

            assert.equal(moduleB.obj.A, 'd');
        }
    },

    'Reference of _original': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },
        'cannot refer _original': function(topic) {
            var moduleB = {};
            moduleB.obj = readonly(topic);
        }
    },

    'Extends test': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },

        'can copy': function(obj) {
            var obj2 = _.clone(obj);
            obj2.A = 'd';
            assert.equal(obj.A, 'a');
        }
    },

    'Getter Test': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            var cloned = {};

            function makeReadOnlyProperty(cloned, obj, prop) {
                Object.defineProperty(cloned, prop, {
                    set: function() {
                        throw new UnableRewriteException('original cannot be rewrite');
                    },
                    get: function() {
                        return obj[prop]
                    },
                    enumerable: true
                });
            }

            for (var prop in obj) {
                makeReadOnlyProperty(cloned, obj, prop);
            }

            /*
            function makeGetter(prop) {
                return function() {
                    var p = prop;
                    return obj[p];
                };
            }

            var _cloned = {};
            for (var prop in obj) {
                var getter = makeGetter(prop);
                Object.defineProperty(_cloned, prop, {
                    set: function() {
                        throw new UnableRewriteException('original cannot be rewrite');
                    },
                    get: function() {
                        return obj[prop]
                    },
                    enumerable: true
                });
                _cloned[prop];
            }
            */
            return cloned;
        },

        'get a': function(obj) {
            assert.equal(obj.A, 'a');
        }
    }

}).export(module); // Export the Suite<|endoftext|>


<commit_before>var assert = require("assert");
var classNames = require('./');
var dedupe = require('./dedupe');
var SPACE = /\s+/;

describe('classNames', function() {
  it('keeps object keys with truthy values', function() {
    assert.equal(classNames({
      a: true,
      b: false,
      c: 0,
      d: null,
      e: undefined,
      f: 1,
    }), 'a f');
  });

  it('joins arrays of class names and ignore falsy values', function() {
    assert.equal(classNames('a', 0, null, undefined, true, 1, 'b'), 'a 1 b');
  });

  it('supports heterogenous arguments', function() {
    assert.equal(classNames({a: true}, 'b', 0), 'a b');
  });

  it('should be trimmed', function() {
    assert.equal(classNames('', 'b', {}, ''), 'b');
  });

  it('returns an empty string for an empty configuration', function() {
    assert.equal(classNames({}), '');
  });

  it('supports an array of class names', function() {
    assert.equal(classNames(['a', 'b']), 'a b');
  });

  it('joins array arguments with string arguments', function() {
    assert.equal(classNames(['a', 'b'], 'c'), 'a b c');
    assert.equal(classNames('c', ['a', 'b']), 'c a b');
  });

  it('handles multiple array arguments', function() {
    assert.equal(classNames(['a', 'b'], ['c', 'd']), 'a b c d');
  });

  it('handles arrays that include falsy and true values', function() {
    assert.equal(classNames(['a', 0, null, undefined, false, true, 'b']), 'a b');
  });

  it('handles arrays that include arrays', function() {
    assert.equal(classNames(['a', ['b', 'c']]), 'a b c');
  });

  it('handles arrays that include objects', function() {
    assert.equal(classNames(['a', {b: true, c: false}]), 'a b');
  });

  it('handles deep array recursion', function() {
    assert.equal(classNames(['a', ['b', ['c', {d: true}]]]), 'a b c d');
  });
});

describe('dedupe', function () {
	function _hasSameClasses (c1, c2) {
		if (c1 === c2) {
			return true;
		}

		c1 = c1.split(SPACE).sort();
		c2 = c2.split(SPACE).sort();

		if (c1.length !== c2.length) {
			return false;
		}

		return c1.reduce(function (result, val, i) {
			return result &= (val === c2[i]);
		}, true);
	}

	it('keeps object keys with truthy values', function() {
		assert.equal(dedupe({
			a: true,
			b: false,
			c: 0,
			d: null,
			e: undefined,
			f: 1,
		}), 'a f');
	});

	it('should dedupe dedupe', function () {
		assert(_hasSameClasses(dedupe('foo', 'bar', 'foo', 'bar', { foo: true }), 'foo bar'));
	});

	it('should make sure subsequent objects can remove/add classes', function () {
		assert(_hasSameClasses(dedupe('foo', { foo: false }, { foo: true, bar: true }), 'foo bar'));
	});

	it('should make sure object with falsy value wipe out previous classes', function () {
		assert(_hasSameClasses(dedupe('foo foo', 0, null, undefined, true, 1, 'b', { 'foo': false }), '1 b'));
		assert(_hasSameClasses(dedupe("foo", "foobar", "bar", { foo: false }), "foobar bar"));
		assert(_hasSameClasses(dedupe("foo", "foo-bar", "bar", { foo: false }), "foo-bar bar"));
		assert(_hasSameClasses(dedupe("foo", "-moz-foo-bar", "bar", { foo: false }), "-moz-foo-bar bar"));
	});

	it('joins arrays of class names and ignore falsy values', function() {
		assert(_hasSameClasses(dedupe('a', 0, null, undefined, true, 1, 'b'), 'a 1 b'));
	});

	it('supports heterogenous arguments', function() {
		assert(_hasSameClasses(dedupe({a: true}, 'b', 0), 'a b'));
	});

	it('should be trimmed', function() {
		assert(_hasSameClasses(dedupe('', 'b', {}, ''), 'b'));
	});

	it('returns an empty string for an empty configuration', function() {
		assert(_hasSameClasses(dedupe({}), ''));
	});

	it('supports an array of class names', function() {
		assert(_hasSameClasses(dedupe(['a', 'b']), 'a b'));
	});

	it('joins array arguments with string arguments', function() {
		assert(_hasSameClasses(dedupe(['a', 'b'], 'c'), 'a b c'));
		assert(_hasSameClasses(dedupe('c', ['a', 'b']), 'c a b'));
	});

	it('handles multiple array arguments', function() {
		assert(_hasSameClasses(dedupe(['a', 'b'], ['c', 'd']), 'a b c d'));
	});

	it('handles arrays that include falsy and true values', function() {
		assert(_hasSameClasses(dedupe(['a', 0, null, undefined, false, true, 'b']), 'a b'));
	});

	it('handles arrays that include arrays', function() {
		assert(_hasSameClasses(dedupe(['a', ['b', 'c']]), 'a b c'));
	});

	it('handles arrays that include objects', function() {
		assert(_hasSameClasses(dedupe(['a', {b: true, c: false}]), 'a b'));
	});

	it('handles deep array recursion', function() {
		assert(_hasSameClasses(dedupe(['a', ['b', ['c', {d: true}]]]), 'a b c d'));
	});
});
<commit_msg>tests: add globals to top<commit_after>/* global describe, it */

var assert = require("assert");
var classNames = require('./');
var dedupe = require('./dedupe');
var SPACE = /\s+/;

describe('classNames', function() {
  it('keeps object keys with truthy values', function() {
    assert.equal(classNames({
      a: true,
      b: false,
      c: 0,
      d: null,
      e: undefined,
      f: 1,
    }), 'a f');
  });

  it('joins arrays of class names and ignore falsy values', function() {
    assert.equal(classNames('a', 0, null, undefined, true, 1, 'b'), 'a 1 b');
  });

  it('supports heterogenous arguments', function() {
    assert.equal(classNames({a: true}, 'b', 0), 'a b');
  });

  it('should be trimmed', function() {
    assert.equal(classNames('', 'b', {}, ''), 'b');
  });

  it('returns an empty string for an empty configuration', function() {
    assert.equal(classNames({}), '');
  });

  it('supports an array of class names', function() {
    assert.equal(classNames(['a', 'b']), 'a b');
  });

  it('joins array arguments with string arguments', function() {
    assert.equal(classNames(['a', 'b'], 'c'), 'a b c');
    assert.equal(classNames('c', ['a', 'b']), 'c a b');
  });

  it('handles multiple array arguments', function() {
    assert.equal(classNames(['a', 'b'], ['c', 'd']), 'a b c d');
  });

  it('handles arrays that include falsy and true values', function() {
    assert.equal(classNames(['a', 0, null, undefined, false, true, 'b']), 'a b');
  });

  it('handles arrays that include arrays', function() {
    assert.equal(classNames(['a', ['b', 'c']]), 'a b c');
  });

  it('handles arrays that include objects', function() {
    assert.equal(classNames(['a', {b: true, c: false}]), 'a b');
  });

  it('handles deep array recursion', function() {
    assert.equal(classNames(['a', ['b', ['c', {d: true}]]]), 'a b c d');
  });
});

describe('dedupe', function () {
	function _hasSameClasses (c1, c2) {
		if (c1 === c2) {
			return true;
		}

		c1 = c1.split(SPACE).sort();
		c2 = c2.split(SPACE).sort();

		if (c1.length !== c2.length) {
			return false;
		}

		return c1.reduce(function (result, val, i) {
			return result &= (val === c2[i]);
		}, true);
	}

	it('keeps object keys with truthy values', function() {
		assert.equal(dedupe({
			a: true,
			b: false,
			c: 0,
			d: null,
			e: undefined,
			f: 1,
		}), 'a f');
	});

	it('should dedupe dedupe', function () {
		assert(_hasSameClasses(dedupe('foo', 'bar', 'foo', 'bar', { foo: true }), 'foo bar'));
	});

	it('should make sure subsequent objects can remove/add classes', function () {
		assert(_hasSameClasses(dedupe('foo', { foo: false }, { foo: true, bar: true }), 'foo bar'));
	});

	it('should make sure object with falsy value wipe out previous classes', function () {
		assert(_hasSameClasses(dedupe('foo foo', 0, null, undefined, true, 1, 'b', { 'foo': false }), '1 b'));
		assert(_hasSameClasses(dedupe("foo", "foobar", "bar", { foo: false }), "foobar bar"));
		assert(_hasSameClasses(dedupe("foo", "foo-bar", "bar", { foo: false }), "foo-bar bar"));
		assert(_hasSameClasses(dedupe("foo", "-moz-foo-bar", "bar", { foo: false }), "-moz-foo-bar bar"));
	});

	it('joins arrays of class names and ignore falsy values', function() {
		assert(_hasSameClasses(dedupe('a', 0, null, undefined, true, 1, 'b'), 'a 1 b'));
	});

	it('supports heterogenous arguments', function() {
		assert(_hasSameClasses(dedupe({a: true}, 'b', 0), 'a b'));
	});

	it('should be trimmed', function() {
		assert(_hasSameClasses(dedupe('', 'b', {}, ''), 'b'));
	});

	it('returns an empty string for an empty configuration', function() {
		assert(_hasSameClasses(dedupe({}), ''));
	});

	it('supports an array of class names', function() {
		assert(_hasSameClasses(dedupe(['a', 'b']), 'a b'));
	});

	it('joins array arguments with string arguments', function() {
		assert(_hasSameClasses(dedupe(['a', 'b'], 'c'), 'a b c'));
		assert(_hasSameClasses(dedupe('c', ['a', 'b']), 'c a b'));
	});

	it('handles multiple array arguments', function() {
		assert(_hasSameClasses(dedupe(['a', 'b'], ['c', 'd']), 'a b c d'));
	});

	it('handles arrays that include falsy and true values', function() {
		assert(_hasSameClasses(dedupe(['a', 0, null, undefined, false, true, 'b']), 'a b'));
	});

	it('handles arrays that include arrays', function() {
		assert(_hasSameClasses(dedupe(['a', ['b', 'c']]), 'a b c'));
	});

	it('handles arrays that include objects', function() {
		assert(_hasSameClasses(dedupe(['a', {b: true, c: false}]), 'a b'));
	});

	it('handles deep array recursion', function() {
		assert(_hasSameClasses(dedupe(['a', ['b', ['c', {d: true}]]]), 'a b c d'));
	});
});
<|endoftext|>


<commit_before>
(function(){

    function assertNeedException(timeout, anyException) {
	var okMsg;
	var oldWindowOnerror = window.onerror;
	var any=false;
	if (anyException) {
	    any = true;
	}

	window.onerror = function(errorMsg, url, lineNumber) {
	    if (
		/*(url.indexOf('need.') != -1) && */
//		(anyException || (errorMsg.indexOf('need.js: no source for hash ') != -1))
		(any || (errorMsg.indexOf('need.js: no source for hash ') != -1))
	    ) {
		window.onerror = oldWindowOnerror;
		oldWindowOnerror = 0;
		// wrong execution context: QUnit won't accept this as ok
//		ok( true, 'exception: '+errorMsg);
//		okMsg = 'Correctly raised exception: '+errorMsg;
		okMsg = ''+errorMsg;
		return true;
	    };
	    return oldWindowOnerror.call(arguments);
	};
	setTimeout(
	    function() {
		if (oldWindowOnerror !== 0) {
		    window.onerror = oldWindowOnerror;
		    oldWindowOnerror = 0;
		    ok( false, 'failed to throw expected exception');
		    start();
		};
	    },
	    timeout ||
		(Math.max(
		    QUnit.config.testTimeout / 2,
		    QUnit.config.testTimeout - 1000)
		)
	);
	var fastOkay = function() {
	    if (oldWindowOnerror !== 0) {
		setTimeout(fastOkay, 20);
		return;
	    };
	    if (okMsg) {
		ok( true, okMsg);
		start();
	    };
	}
	setTimeout(fastOkay, 30);
    };

    function doWhen(cond, callback) { (function(){
	if ('string' === typeof cond) {
	    cond = function() { return eval(cond); }
	}
	var cnt=0;
	var testCb = function() {
	    if (cond()) {
		callback();
	    } else {
		cnt++;
		if (cnt < 100) {
		    setTimeout(testCb, 20);
		};
	    };
	};
	setTimeout(testCb, 30);
    })(); }

    // create a callback function to be used with QUnit's asyncTest(..)
    // cond: first parameter to QUnit's ok(..); will be eval(..)'d if a string
    // msg: second parameter to QUnit's ok(..)
    // finish: boolean; set to true if this callback ends the current test
    function okCallback(cond, msg, finishTest) {
	return function(param) {
	    if ('string' === typeof cond) {
		ok( eval(cond),  msg);
	    } else {
		ok(cond, msg);
	    };
	    if (finishTest) {
		start();
	    };
	    // make this function useable as (pass-through) callback.filter:
	    // need(callback = {filter: okCallback(..), ..}, ..);
	    return param;
	};
    };

    // a javascript file to test loading,
    // with functions to test if it was successfully loaded and executed,
    // and to remove (clean) it again for new tests
    var jsURL
	= 'https://cdn.jsdelivr.net/accounting.js/0.3.2/accounting.min.js';
    var jsSHA256
	= '1b1589c7a7e1338b07b9164daf283dd9f7cb658cba9752c2e872b813d3b7e5e4';
    var jsLength
	= 3133;
    // valid javascript soruce not triggering our jsIsPresent() detection
    var jsBadContent
	= 'https://cdn.jsdelivr.net/alertify.js/0.4.0rc1/alertify.min.js';
    var jsBadContent2
	= 'https://cdn.jsdelivr.net/alertify.js/0.4.0rc1/alertify.js';
    var wrongHash = 'incorrect_and_even_invalid_hash';
    var cleanJs = function() {
	window.accounting = null;
    };
    var jsIsPresent = function() {
	return window.accounting;
    };

    function runTests(needVersion, bootstrap, name) {

	window.needSHA256 = needVersion.needSHA256;
	window.need = needVersion.need;

	// tests suitable for all versions
	asyncTest('load script, correct hash', function() {
	    expect( 1 + 1 );
	    cleanJs();
	    need(
		[jsURL],
		jsSHA256
	    );
	    doWhen(
		jsIsPresent,
		function() {
		    okCallback('jsIsPresent()', 'script loaded', true)();
		    cleanJs();
		    ok( !jsIsPresent(), 'script unloaded (affects later tests)' );
		}
	    );
	});

	asyncTest( 'exception after failed fallbacks, no callback', function() {
	    expect( 1+1 );
	    cleanJs();
	    ok( !jsIsPresent(), 'test script not present' );
	    // for the bootstrap version, accept any exception
	    assertNeedException(1000, bootstrap);
	    need(
		[jsBadContent, jsBadContent2],
		jsSHA256
	    );
	});

	// the following tests all make use of the callback parameter,
	// which is unavailable in the bootstrap version
	// so add a bootstrap-only tests as replacement, then quit
	if (bootstrap) {

/*
	    // this can fail due to CORS when using the file:// protocol
	    asyncTest('bootstrap (loading need.min.js)', function() {
		need(['need.min.js'],'ce119b39a138d787392db2112271b85abbae207424a26248d5a260505e5a5282');
		doWhen(
		    function() { return window.need != needVersion.need; },
		    okCallback('true', 'bootstrap attempt changed window.need', true)
		);
	    });
	    */
	    return;
	}

	asyncTest('callback function', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', 'script loaded', true),
		[jsURL],
		jsSHA256
	    );
	});

	asyncTest( 'callback object', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		{cb: okCallback('jsIsPresent()', 'script loaded', true)},
		[jsURL],
		jsSHA256
	    );
	});

	asyncTest( 'load script, filter and regular callback', function() {
	    expect( 2);
	    cleanJs();
	    need(
		{
		    cb: okCallback(
			'jsIsPresent()',
			'script loaded',
			true
		    ),
		    filter: okCallback(
			'arguments[0].length === jsLength',
			'filter callback, correct length',
			false
		    ),
		},
		[jsURL],
		jsSHA256
	    );
	});

	asyncTest( 'fallback after hash mismatch', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', '', true),
		[jsBadContent, jsURL],
		jsSHA256
	    );
	});

	asyncTest( 'exception after failed fallbacks', function() {
	    expect( 1 );
	    cleanJs();
	    assertNeedException();
	    need(
		okCallback(false, 'incorrectly accepted bad content', true),
		[jsBadContent, jsBadContent2],
		jsSHA256
	    );
	});

/*
	asyncTest( 'exception after failed fallbacks, no callback', function() {
	    expect( 1 );
	    cleanJs();
	    assertNeedException();
	    need(
		[jsBadContent, jsBadContent2],
		jsSHA256
	    );
	});
*/

	asyncTest( 'honor 0 flag: no exception after failed fallbacks', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback(false, 'incorrectly accepted bad content', true),
		[jsBadContent, jsBadContent2, 0],
		jsSHA256
	    );
	    setTimeout(
		function(){
		    ok(!jsIsPresent(), 'was bad content loaded?');
		    start();
		},
		1000
	    );
	});

	asyncTest( 'honor 0 flag: no exception after failed fallbacks, no callback', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		[jsBadContent, jsBadContent2, 0],
		jsSHA256
	    );
	    setTimeout(
		function(){
		    ok(!jsIsPresent(), 'was bad content loaded?');
		    start();
		},
		1000
	    );
	});

	asyncTest( 'honor \'\' flag', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', '', true),
		[jsURL, ''],
		wrongHash
	    );
	});

	asyncTest( 'honor \'\' flag when no hash given', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', '', true),
		[jsURL, '']
	    );
	});

	asyncTest( 'honor \'\' flag, no callback, no hash', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		[jsURL, '']
	    );
	    var cnt = 0;
	    var tst = function() {
		if (!jsIsPresent()) {
		    cnt++;
		    if (cnt < 6) {
			setTimeout(tst, 50);
			return;
		    }
		}
		okCallback('jsIsPresent()', '', true)();
	    };
	    setTimeout(tst, 50);
	});

	asyncTest( 'honor \'\' flag after fallback', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', '', true),
		[jsBadContent, jsURL, ''],
		wrongHash
	    );
	});
    };

    // wait 5 seconds for tests to finish
    QUnit.config.testTimeout = 5000;

    // prime cache to speed up other tests
 //   need(function(){ cleanJs(); runTests(); }, [jsURL],jsSHA256);

    module('Boostrap version bootstrap.min.js');
    runTests(needjsBootstrap, true, 'bootstrap.js');

    var needjsNeedDevStarted = 0;
    QUnit.done(function() {
	if (needjsNeedDevStarted) {
	    return;
	}
	needjsNeedDevStarted = 1;
	module('Development version need.js');
	runTests(needjsNeedDev, false, 'need.js');

	var needjsNeedMinStarted = 0;
	setTimeout(
	    function() {
		QUnit.done(function() {
		    if (needjsNeedMinStarted) {
			return;
		    }
		    needjsNeedMinStarted = 1;
		    module('Production version need.min.js');
		    runTests(needjsNeedMin, false, 'need.min.js');
		});
	    },
	    2000
	);
    });

})();<commit_msg>test bad source urls<commit_after>
(function(){

    function assertNeedException(timeout, anyException) {
	var okMsg;
	var oldWindowOnerror = window.onerror;
	var any=false;
	if (anyException) {
	    any = true;
	}

	window.onerror = function(errorMsg, url, lineNumber) {
	    if (
		/*(url.indexOf('need.') != -1) && */
//		(anyException || (errorMsg.indexOf('need.js: no source for hash ') != -1))
		(any || (errorMsg.indexOf('need.js: no source for hash ') != -1))
	    ) {
		window.onerror = oldWindowOnerror;
		oldWindowOnerror = 0;
		// wrong execution context: QUnit won't accept this as ok
//		ok( true, 'exception: '+errorMsg);
//		okMsg = 'Correctly raised exception: '+errorMsg;
		okMsg = ''+errorMsg;
		return true;
	    };
	    return oldWindowOnerror.call(arguments);
	};
	setTimeout(
	    function() {
		if (oldWindowOnerror !== 0) {
		    window.onerror = oldWindowOnerror;
		    oldWindowOnerror = 0;
		    ok( false, 'failed to throw expected exception');
		    start();
		};
	    },
	    timeout ||
		(Math.max(
		    QUnit.config.testTimeout / 2,
		    QUnit.config.testTimeout - 1000)
		)
	);
	var fastOkay = function() {
	    if (oldWindowOnerror !== 0) {
		setTimeout(fastOkay, 20);
		return;
	    };
	    if (okMsg) {
		ok( true, okMsg);
		start();
	    };
	}
	setTimeout(fastOkay, 30);
    };

    function doWhen(cond, callback) { (function(){
	if ('string' === typeof cond) {
	    cond = function() { return eval(cond); }
	}
	var cnt=0;
	var testCb = function() {
	    if (cond()) {
		callback();
	    } else {
		cnt++;
		if (cnt < 100) {
		    setTimeout(testCb, 20);
		};
	    };
	};
	setTimeout(testCb, 30);
    })(); }

    // create a callback function to be used with QUnit's asyncTest(..)
    // cond: first parameter to QUnit's ok(..); will be eval(..)'d if a string
    // msg: second parameter to QUnit's ok(..)
    // finish: boolean; set to true if this callback ends the current test
    function okCallback(cond, msg, finishTest) {
	return function(param) {
	    if ('string' === typeof cond) {
		ok( eval(cond),  msg);
	    } else {
		ok(cond, msg);
	    };
	    if (finishTest) {
		start();
	    };
	    // make this function useable as (pass-through) callback.filter:
	    // need(callback = {filter: okCallback(..), ..}, ..);
	    return param;
	};
    };

    // a javascript file to test loading,
    // with functions to test if it was successfully loaded and executed,
    // and to remove (clean) it again for new tests
    var jsURL
	= 'https://cdn.jsdelivr.net/accounting.js/0.3.2/accounting.min.js';
    var jsSHA256
	= '1b1589c7a7e1338b07b9164daf283dd9f7cb658cba9752c2e872b813d3b7e5e4';
    var jsLength
	= 3133;
    // valid javascript soruce not triggering our jsIsPresent() detection
    var jsBadContent
	= 'https://cdn.jsdelivr.net/alertify.js/0.4.0rc1/alertify.min.js';
    var jsBadContent2
	= 'https://cdn.jsdelivr.net/alertify.js/0.4.0rc1/alertify.js';
    // a path that hopefully results in a "not found" condition
    var urlNotFound
	= 'https://cdn.jsdelivr.net/not/even/the/right/path-structure.sure.not';
    // a url that does not resolve
    var urlNoHost
        = 'https://dlehforeuihfncrelncferoifheriuchnepofjer.not-even.a.top-level-domain';
    // a url (localhost) that should resolve but time-out due to there not being a webserver (hopefully...)
    var urlTimeOut
	= 'https://0.0.0.1:81';
    var wrongHash = 'incorrect_and_even_invalid_hash';
    var cleanJs = function() {
	window.accounting = null;
    };
    var jsIsPresent = function() {
	return window.accounting;
    };

    function runTests(needVersion, bootstrap, name) {

	window.needSHA256 = needVersion.needSHA256;
	window.need = needVersion.need;

	// tests suitable for all versions
	asyncTest('load script, correct hash', function() {
	    expect( 1 + 1 );
	    cleanJs();
	    need(
		[jsURL],
		jsSHA256
	    );
	    doWhen(
		jsIsPresent,
		function() {
		    okCallback('jsIsPresent()', 'script loaded', true)();
		    cleanJs();
		    ok( !jsIsPresent(), 'script unloaded (affects later tests)' );
		}
	    );
	});

	asyncTest( 'exception after fallbacks, no callback', function() {
	    expect( 1 );
	    cleanJs();
	    // for the bootstrap version, accept any exception
	    assertNeedException(1000, bootstrap);
	    need(
		[jsBadContent, jsBadContent2],
		jsSHA256
	    );
	});

	asyncTest('load script from third fallback url', function() {
	    expect( 3 );
	    cleanJs();
	    ok( !jsIsPresent(), 'test script not initially present' );
	    need(
		[jsBadContent, jsBadContent2, jsURL],
		jsSHA256
	    );
	    doWhen(
		jsIsPresent,
		function() {
		    okCallback('jsIsPresent()', 'script loaded', true)();
		    cleanJs();
		    ok( !jsIsPresent(), 'script unloaded (affects later tests)' );
		}
	    );
	});

	// for some reason, the bootstrap version fails here,
	// throwing (in iceweasel, at least) a ...BAD_URI... exception
	/*bootstrap || */
	asyncTest('load script after non-200 url', function() {
	    expect( 3 );
	    cleanJs();
	    ok( !jsIsPresent(), 'test script not initially present' );
	    need(
		[urlNotFound, jsURL],
		jsSHA256
	    );
	    doWhen(
		jsIsPresent,
		function() {
		    okCallback('jsIsPresent()', 'script loaded', true)();
		    cleanJs();
		    ok( !jsIsPresent(), 'script unloaded (affects later tests)' );
		}
	    );
	});

	asyncTest('load script after non-existent url', function() {
	    expect( 3 );
	    cleanJs();
	    ok( !jsIsPresent(), 'test script not initially present' );
	    need(
		[urlNoHost, jsURL],
		jsSHA256
	    );
	    doWhen(
		jsIsPresent,
		function() {
		    okCallback('jsIsPresent()', 'script loaded', true)();
		    cleanJs();
		    ok( !jsIsPresent(), 'script unloaded (affects later tests)' );
		}
	    );
	});

	  // bad idea: with current IP (localhost),
	  // there's no timeout---instead, instant "port closed" reply(?)
	asyncTest('load script after time-out url', function() {
	    expect( 3 );
	    cleanJs();
	    ok( !jsIsPresent(), 'test script not initially present' );
	    need(
		[urlTimeOut, jsURL],
		jsSHA256
	    );
	    doWhen(
		jsIsPresent,
		function() {
		    okCallback('jsIsPresent()', 'script loaded', true)();
		    cleanJs();
		    ok( !jsIsPresent(), 'script unloaded (affects later tests)' );
		}
	    );
	});

	// the following tests all make use of the callback parameter,
	// which is unavailable in the bootstrap version
	// so add a bootstrap-only tests as replacement, then quit
	if (bootstrap) {

/*
	    // this can fail due to CORS when using the file:// protocol
	    asyncTest('bootstrap (loading need.min.js)', function() {
		need(['need.min.js'],'ce119b39a138d787392db2112271b85abbae207424a26248d5a260505e5a5282');
		doWhen(
		    function() { return window.need != needVersion.need; },
		    okCallback('true', 'bootstrap attempt changed window.need', true)
		);
	    });
	    */
	    return;
	}

	asyncTest('callback function', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', 'script loaded', true),
		[jsURL],
		jsSHA256
	    );
	});

	asyncTest( 'callback object', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		{cb: okCallback('jsIsPresent()', 'script loaded', true)},
		[jsURL],
		jsSHA256
	    );
	});

	asyncTest( 'load script, filter and regular callback', function() {
	    expect( 2);
	    cleanJs();
	    need(
		{
		    cb: okCallback(
			'jsIsPresent()',
			'script loaded',
			true
		    ),
		    filter: okCallback(
			'arguments[0].length === jsLength',
			'filter callback, correct length',
			false
		    ),
		},
		[jsURL],
		jsSHA256
	    );
	});

	asyncTest( 'fallback after hash mismatch', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', '', true),
		[jsBadContent, jsURL],
		jsSHA256
	    );
	});

	asyncTest( 'exception after failed fallbacks', function() {
	    expect( 1 );
	    cleanJs();
	    assertNeedException();
	    need(
		okCallback(false, 'incorrectly accepted bad content', true),
		[jsBadContent, jsBadContent2],
		jsSHA256
	    );
	});

/*
	asyncTest( 'exception after failed fallbacks, no callback', function() {
	    expect( 1 );
	    cleanJs();
	    assertNeedException();
	    need(
		[jsBadContent, jsBadContent2],
		jsSHA256
	    );
	});
*/

	asyncTest( 'honor 0 flag: no exception after failed fallbacks', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback(false, 'incorrectly accepted bad content', true),
		[jsBadContent, jsBadContent2, 0],
		jsSHA256
	    );
	    setTimeout(
		function(){
		    ok(!jsIsPresent(), 'was bad content loaded?');
		    start();
		},
		1000
	    );
	});

	asyncTest( 'honor 0 flag: no exception after failed fallbacks, no callback', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		[jsBadContent, jsBadContent2, 0],
		jsSHA256
	    );
	    setTimeout(
		function(){
		    ok(!jsIsPresent(), 'was bad content loaded?');
		    start();
		},
		1000
	    );
	});

	asyncTest( 'honor \'\' flag', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', '', true),
		[jsURL, ''],
		wrongHash
	    );
	});

	asyncTest( 'honor \'\' flag when no hash given', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', '', true),
		[jsURL, '']
	    );
	});

	asyncTest( 'honor \'\' flag, no callback, no hash', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		[jsURL, '']
	    );
	    var cnt = 0;
	    var tst = function() {
		if (!jsIsPresent()) {
		    cnt++;
		    if (cnt < 6) {
			setTimeout(tst, 50);
			return;
		    }
		}
		okCallback('jsIsPresent()', '', true)();
	    };
	    setTimeout(tst, 50);
	});

	asyncTest( 'honor \'\' flag after fallback', function() {
	    expect( 1 );
	    cleanJs();
	    need(
		okCallback('jsIsPresent()', '', true),
		[jsBadContent, jsURL, ''],
		wrongHash
	    );
	});
    };

    // wait 5 seconds for tests to finish
    QUnit.config.testTimeout = 5000;

    // prime cache to speed up other tests
 //   need(function(){ cleanJs(); runTests(); }, [jsURL],jsSHA256);

    module('Boostrap version bootstrap.min.js');
    runTests(needjsBootstrap, true, 'bootstrap.js');

    var needjsNeedDevStarted = 0;
    QUnit.done(function() {
	if (needjsNeedDevStarted) {
	    return;
	}
	needjsNeedDevStarted = 1;
	module('Development version need.js');
	runTests(needjsNeedDev, false, 'need.js');

	var needjsNeedMinStarted = 0;
	setTimeout(
	    function() {
		QUnit.done(function() {
		    if (needjsNeedMinStarted) {
			return;
		    }
		    needjsNeedMinStarted = 1;
		    module('Production version need.min.js');
		    runTests(needjsNeedMin, false, 'need.min.js');
		});
	    },
	    2000
	);
    });

})();<|endoftext|>


<commit_before>var demand = require('must');
var listToArray = require('./index');

describe('listToArray', function() {
	it('splits a comma-delimited list into an array', function() {
		listToArray('one,two,three').must.eql(['one', 'two', 'three']);
	});
	it('splits a space-delimited list into an array', function() {
		listToArray('one two three').must.eql(['one', 'two', 'three']);
	});
	it('trims whitespace from values', function() {
		listToArray('one, two, three').must.eql(['one', 'two', 'three']);
	});
	it('splits a list into an array', function() {
		listToArray('one,two,three').must.eql(['one', 'two', 'three']);
	});
	it('returns a empty array w/ no arguments', function() {
		listToArray().must.eql([]);
	});
	it('returns a empty array for a blank string', function() {
		listToArray('').must.eql([]);
	});
	it('returns a empty array when only given whitespace', function() {
		listToArray(' ').must.eql([]);
	});
	it('returns a empty array when only given whitespace and commas', function() {
		listToArray(' , ').must.eql([]);
	});
	/*
	describe('()', function() {
		it('must be an instance of Wrapper', function() {
			di(fn_basic).must.be.an.instanceof(di.Wrapper);
		});
	});
	describe('(notAFunction)', function(){
		it('must throw an error', function(){
			demand(function(){
				di(notAFunction);
			}).to.throw(/function/i);
		});
	});
	describe('fn_basic.isAsync', function() {
		it('must not be async', function() {
			demand(di(fn_basic).isAsync).not.be.true();
		});
	});
	describe('fn_async.isAsync', function() {
		it('must be async', function() {
			demand(di(fn_async).isAsync).be.true();
		});
	});
	describe('fn_basic.deps', function() {
		it('must be empty', function() {
			demand(di(fn_async).deps).eql([]);
		});
	});
	describe('fn_basic.call(callback)', function() {
		it('must callback(null, true)', function(done) {
			di(fn_basic).call(function(err, val) {
				demand(err).be.null();
				demand(val).be.true();
				done();
			});
		});
	});
	describe('fn_basic.call()', function() {
		it('must return true', function() {
			di(fn_basic).call().must.be.true();
		});
	});
	describe('fn_async.call(callback)', function() {
		it('must callback(null, true)', function(done) {
			di(fn_async).call(function(err, val) {
				demand(err).be.null();
				demand(val).be.true();
				done();
			});
		});
	});
	describe('fn_one.requires', function() {
		it('must require `one`', function() {
			demand(di(fn_one).requires.one).be.true();
		});
	});
	describe('fn_one.requires', function() {
		it('must not require `two`', function() {
			demand(di(fn_one).requires.two).be.undefined();
		});
	});
	describe('(fn_scope).call(scope, callback)', function(){
		it('must return scope', function(done){
			di(fn_scope).call(scope, function(err, val){
				demand(val).equal(scope);
				done();
			});
		});
	});
	describe('(fn_scope, scope).call(callback)', function(){
		it('must return scope', function(done){
			di(fn_scope, scope).call(function(err, val){
				demand(val).equal(scope);
				done();
			});
		});
	});
	describe('(fn_error).call(callback)', function(){
		it('must return thrownErr', function(done){
			di(fn_error).call(function(err, val){
				demand(err).equal(thrownErr);
				done();
			});
		});
	});
	*/
});
<commit_msg>Cleaning up tests<commit_after>var demand = require('must');
var listToArray = require('./index');

describe('listToArray', function() {
	it('splits a comma-delimited list into an array', function() {
		listToArray('one,two,three').must.eql(['one', 'two', 'three']);
	});
	it('splits a space-delimited list into an array', function() {
		listToArray('one two three').must.eql(['one', 'two', 'three']);
	});
	it('trims whitespace from values', function() {
		listToArray('one, two, three').must.eql(['one', 'two', 'three']);
	});
	it('splits a list into an array', function() {
		listToArray('one,two,three').must.eql(['one', 'two', 'three']);
	});
	it('returns a empty array w/ no arguments', function() {
		listToArray().must.eql([]);
	});
	it('returns a empty array for a blank string', function() {
		listToArray('').must.eql([]);
	});
	it('returns a empty array when only given whitespace', function() {
		listToArray(' ').must.eql([]);
	});
	it('returns a empty array when only given whitespace and commas', function() {
		listToArray(' , ').must.eql([]);
	});
});
<|endoftext|>


<commit_before>require('@jymfony/autoloader');
require('mocha/bin/_mocha');
<commit_msg>enabled autoloader debug mode for tests<commit_after>require('@jymfony/autoloader');

__jymfony.autoload.debug = true;

require('mocha/bin/_mocha');
<|endoftext|>


<commit_before>var nohm = require(__dirname + '/../tsOut/').Nohm;
var args = require(__dirname + '/testArgs.js');
var async = require('async');
var redis = args.redis;
var h = require(__dirname + '/helper.js');
var relationsprefix = nohm.prefix.relations;
var UserLinkMockup = nohm.model('UserLinkMockup', {
  properties: {
    name: {
      type: 'string',
      defaultValue: 'testName',
      validations: [
        'notEmpty'
      ]
    }
  },
  idGenerator: 'increment'
});
var CommentLinkMockup = nohm.model('CommentLinkMockup', {
  properties: {
    text: {
      type: 'string',
      defaultValue: 'this is a comment! REALLY!',
      validations: [
        'notEmpty'
      ]
    }
  }
});
var RoleLinkMockup = nohm.model('RoleLinkMockup', {
  properties: {
    name: {
      type: 'string',
      defaultValue: 'user'
    }
  },
  idGenerator: 'increment'
});

exports.relation = {

  setUp: function (next) {
    if (!nohm.client) {
      nohm.setClient(redis);
    }
    next();
  },
  tearDown: function (next) {
    h.cleanUp(redis, args.prefix, next);
  },

  instances: (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2;

    t.expect(2);

    role.link(user);

    t.ok(role.relationChanges !== user.relationChanges, 'Instances share the relationchanges, initiate them as an empty array in the constructor.');

    role2 = new RoleLinkMockup();
    t.same(role2.relationChanges, [], 'Creating a new instance does not reset the relationchanges of that instance.');

    t.done();
  },

  link: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup(),
      linkCallbackCalled = false,
      linkCallbackCalled2 = false;
    t.expect(9);

    user.link(role, function (action, on, name, obj) {
      linkCallbackCalled = true;
      t.equals(action, 'link', 'The argument "action" given to the link callback are not correct');
      t.equals(on, 'UserLinkMockup', 'The argument "on" given to the link callback are not correct');
      t.equals(name, 'default', 'The argument "name" given to the link callback are not correct');
      t.same(obj, role, 'The argument "obj" given to the link callback are not correct');
    });

    role2.property('name', 'test');

    user.link(role2, function () {
      linkCallbackCalled2 = true;
    });

    await user.save();
    t.ok(linkCallbackCalled, 'The provided callback for linking was not called.');
    t.ok(linkCallbackCalled2, 'The provided callback for the second(!) linking was not called.');
    redis.keys(relationsprefix + '*', function (err, values) {
      let firstDone = false;
      const keyCheck = function (err, members) {
        t.equals(members[0], '1', 'The set of a relationship contained a wrong member');
        if (firstDone === true) {
          t.done();
        } else {
          firstDone = true;
        }
      };
      if (!err) {
        t.same(values.length, 3, 'Linking an object did not create the correct number of keys.');
        redis.smembers(values[0].toString(), keyCheck);
        redis.smembers(values[1].toString(), keyCheck);
      } else {
        console.dir(err);
        t.done();
      }
    });
  },

  unlink: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup(),
      unlinkCallbackCalled = false,
      unlinkCallbackCalled2 = false;
    t.expect(7);

    user.id = 1;
    role.id = 1;
    role2.id = 2;

    user.unlink(role, function (action, on, name, obj) {
      unlinkCallbackCalled = true;
      t.equals(action, 'unlink', 'The argument "action" given to the unlink callback are not correct');
      t.equals(on, 'UserLinkMockup', 'The argument "on" given to the unlink callback are not correct');
      t.equals(name, 'default', 'The argument "name" given to the unlink callback are not correct');
      t.equals(obj, role, 'The argument "obj" given to the unlink callback are not correct');
    });

    user.unlink(role2, function () {
      unlinkCallbackCalled2 = true;
    });

    await user.save();
    t.ok(unlinkCallbackCalled, 'The provided callback for unlinking was not called.');
    t.ok(unlinkCallbackCalled2, 'The provided callback for the second(!) unlinking was not called.');
    redis.keys(relationsprefix + '*', function (err, value) {
      if (!err) {
        var check = (Array.isArray(value) && value.length === 0) || value === null;
        t.ok(check, 'Unlinking an object did not delete keys.');
      }
      t.done();
    });
  },

  deeplink: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      comment = new CommentLinkMockup(),
      userLinkCallbackCalled = false,
      commentLinkCallbackCalled = false;
    t.expect(5);

    role.link(user, function () {
      userLinkCallbackCalled = true;
    });
    user.link(comment, function () {
      commentLinkCallbackCalled = true;
    });

    await role.save();
    t.ok(userLinkCallbackCalled, 'The user link callback was not called.');
    t.ok(commentLinkCallbackCalled, 'The comment link callback was not called.');
    t.ok(user.id !== null, 'The deeplinked user does not have an id and thus is probably not saved correctly.');
    t.ok(comment.id !== null, 'The deeplinked comment does not have an id and thus is probably not saved correctly.');
    redis.smembers(relationsprefix + comment.modelName + ':defaultForeign:' +
      user.modelName + ':' + comment.id,
      function (err, value) {
        if (!err) {
          t.equals(value, user.id, 'The user does not have the neccessary relations saved. There are probably more problems, if this occurs.');
        } else {
          console.dir(err);
        }
        t.done();
      });
  },

  removeUnlinks: async (t) => {
    // uses unlinkAll in remove
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup(),
      comment = new CommentLinkMockup(),
      linkName = 'creator';
    t.expect(6);

    user.property('name', 'removeUnlinks');

    role.link(user, linkName);
    user.link(role, 'isA');
    user.link(comment);
    role2.link(user);

    await role2.save();
    var tmpid = user.id;
    await user.remove();
    async.parallel([
      function (next) {
        redis.exists(relationsprefix + user.modelName + ':' + linkName + 'Foreign:' + role.modelName + ':' + tmpid,
          function (err, value) {
            t.equals(value, 0, 'The foreign link to the custom-link-name role was not deleted');
            next(err);
          });
      },
      function (next) {
        redis.exists(relationsprefix + role.modelName + ':' + linkName + ':' + user.modelName + ':' + role.id,
          function (err, value) {
            t.equals(value, 0, 'The link to the custom-link-name role was not deleted');
            next(err);
          });
      },
      function (next) {
        redis.exists(relationsprefix + user.modelName + ':default:' + comment.modelName + ':' + tmpid,
          function (err, value) {
            t.equals(value, 0, 'The link to the child comment was not deleted');
            next(err);
          });
      },
      function (next) {
        redis.sismember(relationsprefix + comment.modelName + ':defaultForeign:' + user.modelName + ':' + comment.id, tmpid,
          function (err, value) {
            t.equals(value, 0, 'The link to the comment parent was not deleted');
            next(err);
          });
      },
      function (next) {
        redis.sismember(relationsprefix + role2.modelName + ':default:' + user.modelName + ':' + role2.id, tmpid,
          function (err, value) {
            t.equals(value, 0, 'The removal did not delete the link from a parent to the object itself.');
            next(err);
          }
        );
      }],
      function (err) {
        t.ok(!err, 'An unexpected redis error occured.');
        t.done();
      }
    );
  },

  belongsTo: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup();
    t.expect(1);

    user.link(role);

    await user.save();
    const belongs = await user.belongsTo(role);
    t.equals(belongs, true, 'The link was not detected correctly by belongsTo()');
    t.done();
  },

  getAll: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup();
    t.expect(2);

    user.link(role);
    user.link(role2);

    await user.save();
    var should = [role.id, role2.id];
    const relationIds = await user.getAll(role.modelName);
    t.ok(Array.isArray(relationIds), 'getAll() did not return an array.');
    t.same(relationIds, should, 'getAll() did not return the correct array');
    t.done();
  },

  'getAll with different id generators': async (t) => {
    var user = new UserLinkMockup(),
      comment = new CommentLinkMockup();
    t.expect(1);

    user.link(comment);

    await user.save();
    var should = [comment.id];
    const relationIds = await user.getAll(comment.modelName);
    t.same(relationIds, should, 'getAll() did not return the correct array');
    t.done();
  },

  numLinks: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup();
    t.expect(1);

    user.link(role);
    user.link(role2);

    await user.save();
    const numLinks = await user.numLinks(role.modelName);
    t.same(numLinks, 2, 'The number of links was not returned correctly');
    t.done();
  },

  deeplinkError: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      comment = new CommentLinkMockup();
    t.expect(8);

    role.link(user);
    user.link(comment);
    comment.property('text', ''); // makes the comment fail

    try {
      await role.save();
    } catch (err) {
      t.ok(user.id !== null, 'The deeplinked user does not have an id and thus is probably not saved correctly.');
      t.same(comment.id, null, 'The deeplinked erroneous comment does not have an id and thus is probably saved.');
      t.ok(err instanceof nohm.LinkError, 'The deeplinked comment did not produce a top-level LinkError.');
      t.same(err.errors.length, 1, 'The deeplinked role did not fail in a child or reported it wrong.');
      t.ok(err.errors[0].error instanceof nohm.ValidationError, 'The deeplinked comment did not produce a ValidationError.');
      t.same(err.errors[0].child.errors, { text: ['notEmpty'] }, 'The deeplinked role did not fail.');
      t.same(err.errors[0].child.modelName, 'CommentLinkMockup', 'The deeplinked role failed in the wrong model or reported it wrong.');
      t.same(err.errors[0].parent.modelName, 'UserLinkMockup', 'The deeplinked role failed in the wrong model or reported it wrong.');
      t.done();
    }
  },

  linkToSelf: async (t) => {
    var user = new UserLinkMockup();
    t.expect(1);

    user.link(user);

    await user.save();
    t.ok(true, 'Linking an object to itself failed.');
    t.done();
  },

  deppLinkErrorCallback: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      comment = new CommentLinkMockup();
    t.expect(7);

    role.link(user, {
      error: function (err, obj) {
        console.log(err, obj.errors, obj.allProperties())
        t.ok(false, 'Error callback for role.link(user) called even though user is valid.');
      }
    });
    user.link(comment, {
      error: function (err, obj) {
        t.ok(err instanceof nohm.ValidationError, 'err in error callback was not a ValidationError');
        t.same(comment, obj, 'obj in Error callback was not the right object.');
      }
    });
    comment.property('text', ''); // makes the comment fail

    try {
      await role.save();
    } catch (err) {
      t.ok(user.id !== null, 'The deeplinked user does not have an id and thus is probably not saved correctly.');
      t.same(comment.id, null, 'The deeplinked erroneous comment does not have an id and thus is probably saved.');
      t.ok(err, 'The deeplinked role did not fail.');
      t.ok(err instanceof nohm.LinkError, true, 'The deeplinked role did not fail in a child or reported it wrong.');
      t.same(err.errors[0].child.modelName, 'CommentLinkMockup', 'The deeplinked role failed in the wrong model or reported it wrong.');
      t.done();
    }
  },

  contineOnError: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      comment = new CommentLinkMockup(),
      comment2 = new CommentLinkMockup(),
      comment3 = new CommentLinkMockup();
    t.expect(4);

    role.link(user, {
      error: function (err, obj) {
        console.log(err, obj.errors, obj.allProperties())
        t.ok(false, 'Error callback for role.link(user) called even though user is valid.');
      }
    });
    user.link(comment, {
      error: function (err, obj) {
        t.ok(err instanceof nohm.ValidationError, 'err in error callback was not a ValidationError');
        t.same(comment, obj, 'obj in Error callback was not the right object.');
      }
    });
    user.link(comment2, {
      error: function (err, obj) {
        console.log(err, obj.errors, obj.allProperties())
        t.ok(false, 'Error callback for comment2.link(user) called even though user is valid.');
      }
    });
    user.link(comment3, {
      error: function (err, obj) {
        console.log(err, obj.errors, obj.allProperties())
        t.ok(false, 'Error callback for comment3.link(user) called even though user is valid.');
      }
    });
    comment.property('text', ''); // makes the first comment fail

    try {
      await role.save({ continue_on_link_error: true });
      t.done();
    } catch (e) {
      redis.sismember(relationsprefix + comment3.modelName + ':defaultForeign:' + user.modelName + ':' + comment3.id, user.id,
        function (err, value) {
          t.ok(!err, 'There was a redis error');
          t.same(value, "1", 'The comment3 relation was not saved');
          t.done();
        }
      );
    }
  }
};

/* Maybe this isn't such a good idea. I like that model definitions are completely
   lacking relation definitions.
cascadingDeletes: function (t) {
  var user = new UserLinkMockup(),
  role = new RoleLinkMockup(),
  comment = new CommentLinkMockup(),
  testComment = new CommentLinkMockup();
  t.expect(1);

  user.link(role);
  role.link(comment);

  user.save(function (err) {
    if (err) {
      console.dir(err);
      t.done();
    }
    var testid = comment.id;
    user.remove(function (err) {
      if (err) {
        console.dir(err);
        t.done();
      }
      testComment.load(testid, function (err) {
        t.equals(err, 'not found', 'Removing an object that has cascading deletes did not remove the relations');
        t.done();
      });
    });
  });
};*/
<commit_msg>Fix link tests to properly fail with uuid ids<commit_after>var nohm = require(__dirname + '/../tsOut/').Nohm;
var args = require(__dirname + '/testArgs.js');
var async = require('async');
var redis = args.redis;
var h = require(__dirname + '/helper.js');
var relationsprefix = nohm.prefix.relations;
var UserLinkMockup = nohm.model('UserLinkMockup', {
  properties: {
    name: {
      type: 'string',
      defaultValue: 'testName',
      validations: [
        'notEmpty'
      ]
    }
  }
});
var CommentLinkMockup = nohm.model('CommentLinkMockup', {
  properties: {
    text: {
      type: 'string',
      defaultValue: 'this is a comment! REALLY!',
      validations: [
        'notEmpty'
      ]
    }
  }
});
var RoleLinkMockup = nohm.model('RoleLinkMockup', {
  properties: {
    name: {
      type: 'string',
      defaultValue: 'user'
    }
  }
});

exports.relation = {

  setUp: function (next) {
    if (!nohm.client) {
      nohm.setClient(redis);
    }
    next();
  },
  tearDown: function (next) {
    h.cleanUp(redis, args.prefix, next);
  },

  instances: (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2;

    t.expect(2);

    role.link(user);

    t.ok(role.relationChanges !== user.relationChanges, 'Instances share the relationchanges, initiate them as an empty array in the constructor.');

    role2 = new RoleLinkMockup();
    t.same(role2.relationChanges, [], 'Creating a new instance does not reset the relationchanges of that instance.');

    t.done();
  },

  link: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup(),
      linkCallbackCalled = false,
      linkCallbackCalled2 = false;
    t.expect(14);

    user.link(role, function (action, on, name, obj) {
      linkCallbackCalled = true;
      t.equals(action, 'link', 'The argument "action" given to the link callback are not correct');
      t.equals(on, 'UserLinkMockup', 'The argument "on" given to the link callback are not correct');
      t.equals(name, 'default', 'The argument "name" given to the link callback are not correct');
      t.same(obj, role, 'The argument "obj" given to the link callback are not correct');
    });

    role2.property('name', 'test');

    user.link(role2, function () {
      linkCallbackCalled2 = true;
    });

    await user.save();

    t.ok(linkCallbackCalled, 'The provided callback for linking was not called.');
    t.ok(linkCallbackCalled2, 'The provided callback for the second(!) linking was not called.');
    redis.keys(relationsprefix + '*', function (err, values) {
      const keyCheck = function (compareIds) {
        return (err, members) => {
          t.equals(members.length, compareIds.length, 'The set of a relationship contained the wrong amount of ids.');
          members.forEach((member) => {
            t.ok(compareIds.includes(member), 'The set of a relationship contained a wrong id');
          });
        };
      };
      if (!err) {
        t.same(values.length, 3, 'Linking an object did not create the correct number of keys.');
        values.forEach((value) => {
          const isForeignLink = value.includes(':defaultForeign:');
          // user links to role1 and role2, each role links to only user
          const ids = isForeignLink ? [user.id] : [role.id, role2.id];
          redis.smembers(value.toString(), keyCheck(ids));
        });
        t.done();
      } else {
        console.dir(err);
        t.done();
      }
    });
  },

  unlink: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup(),
      unlinkCallbackCalled = false,
      unlinkCallbackCalled2 = false;
    t.expect(7);

    user.id = 1;
    role.id = 1;
    role2.id = 2;

    user.unlink(role, function (action, on, name, obj) {
      unlinkCallbackCalled = true;
      t.equals(action, 'unlink', 'The argument "action" given to the unlink callback are not correct');
      t.equals(on, 'UserLinkMockup', 'The argument "on" given to the unlink callback are not correct');
      t.equals(name, 'default', 'The argument "name" given to the unlink callback are not correct');
      t.equals(obj, role, 'The argument "obj" given to the unlink callback are not correct');
    });

    user.unlink(role2, function () {
      unlinkCallbackCalled2 = true;
    });

    await user.save();
    t.ok(unlinkCallbackCalled, 'The provided callback for unlinking was not called.');
    t.ok(unlinkCallbackCalled2, 'The provided callback for the second(!) unlinking was not called.');
    redis.keys(relationsprefix + '*', function (err, value) {
      if (!err) {
        var check = (Array.isArray(value) && value.length === 0) || value === null;
        t.ok(check, 'Unlinking an object did not delete keys.');
      }
      t.done();
    });
  },

  deeplink: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      comment = new CommentLinkMockup(),
      userLinkCallbackCalled = false,
      commentLinkCallbackCalled = false;
    t.expect(5);

    role.link(user, function () {
      userLinkCallbackCalled = true;
    });
    user.link(comment, function () {
      commentLinkCallbackCalled = true;
    });

    await role.save();
    t.ok(userLinkCallbackCalled, 'The user link callback was not called.');
    t.ok(commentLinkCallbackCalled, 'The comment link callback was not called.');
    t.ok(user.id !== null, 'The deeplinked user does not have an id and thus is probably not saved correctly.');
    t.ok(comment.id !== null, 'The deeplinked comment does not have an id and thus is probably not saved correctly.');
    redis.smembers(relationsprefix + comment.modelName + ':defaultForeign:' +
      user.modelName + ':' + comment.id,
      function (err, value) {
        if (!err) {
          t.equals(value, user.id, 'The user does not have the neccessary relations saved. There are probably more problems, if this occurs.');
        } else {
          console.dir(err);
        }
        t.done();
      });
  },

  removeUnlinks: async (t) => {
    // uses unlinkAll in remove
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup(),
      comment = new CommentLinkMockup(),
      linkName = 'creator';
    t.expect(6);

    user.property('name', 'removeUnlinks');

    role.link(user, linkName);
    user.link(role, 'isA');
    user.link(comment);
    role2.link(user);

    await role2.save();
    var tmpid = user.id;

    await user.remove();
    async.parallel([
      function (next) {
        redis.exists(relationsprefix + user.modelName + ':' + linkName + 'Foreign:' + role.modelName + ':' + tmpid,
          function (err, value) {
            t.equals(value, 0, 'The foreign link to the custom-link-name role was not deleted');
            next(err);
          });
      },
      function (next) {
        redis.exists(relationsprefix + role.modelName + ':' + linkName + ':' + user.modelName + ':' + role.id,
          function (err, value) {
            t.equals(value, 0, 'The link to the custom-link-name role was not deleted');
            next(err);
          });
      },
      function (next) {
        redis.exists(relationsprefix + user.modelName + ':default:' + comment.modelName + ':' + tmpid,
          function (err, value) {
            t.equals(value, 0, 'The link to the child comment was not deleted');
            next(err);
          });
      },
      function (next) {
        redis.sismember(relationsprefix + comment.modelName + ':defaultForeign:' + user.modelName + ':' + comment.id, tmpid,
          function (err, value) {
            t.equals(value, 0, 'The link to the comment parent was not deleted');
            next(err);
          });
      },
      function (next) {
        redis.sismember(relationsprefix + role2.modelName + ':default:' + user.modelName + ':' + role2.id, tmpid,
          function (err, value) {
            t.equals(value, 0, 'The removal did not delete the link from a parent to the object itself.');
            next(err);
          }
        );
      }],
      function (err) {
        t.ok(!err, 'An unexpected redis error occured.');
        t.done();
      }
    );
  },

  belongsTo: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup();
    t.expect(1);

    user.link(role);

    await user.save();
    const belongs = await user.belongsTo(role);
    t.equals(belongs, true, 'The link was not detected correctly by belongsTo()');
    t.done();
  },

  getAll: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup();
    t.expect(2);

    user.link(role);
    user.link(role2);

    await user.save();
    var should = [role.id, role2.id];
    const relationIds = await user.getAll(role.modelName);
    t.ok(Array.isArray(relationIds), 'getAll() did not return an array.');
    t.same(relationIds, should, 'getAll() did not return the correct array');
    t.done();
  },

  'getAll with different id generators': async (t) => {
    var user = new UserLinkMockup(),
      comment = new CommentLinkMockup();
    t.expect(1);

    user.link(comment);

    await user.save();
    var should = [comment.id];
    const relationIds = await user.getAll(comment.modelName);
    t.same(relationIds, should, 'getAll() did not return the correct array');
    t.done();
  },

  numLinks: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      role2 = new RoleLinkMockup();
    t.expect(1);

    user.link(role);
    user.link(role2);

    await user.save();
    const numLinks = await user.numLinks(role.modelName);
    t.same(numLinks, 2, 'The number of links was not returned correctly');
    t.done();
  },

  deeplinkError: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      comment = new CommentLinkMockup();
    t.expect(8);

    role.link(user);
    user.link(comment);
    comment.property('text', ''); // makes the comment fail

    try {
      await role.save();
    } catch (err) {
      t.ok(user.id !== null, 'The deeplinked user does not have an id and thus is probably not saved correctly.');
      t.same(comment.id, null, 'The deeplinked erroneous comment does not have an id and thus is probably saved.');
      t.ok(err instanceof nohm.LinkError, 'The deeplinked comment did not produce a top-level LinkError.');
      t.same(err.errors.length, 1, 'The deeplinked role did not fail in a child or reported it wrong.');
      t.ok(err.errors[0].error instanceof nohm.ValidationError, 'The deeplinked comment did not produce a ValidationError.');
      t.same(err.errors[0].child.errors, { text: ['notEmpty'] }, 'The deeplinked role did not fail.');
      t.same(err.errors[0].child.modelName, 'CommentLinkMockup', 'The deeplinked role failed in the wrong model or reported it wrong.');
      t.same(err.errors[0].parent.modelName, 'UserLinkMockup', 'The deeplinked role failed in the wrong model or reported it wrong.');
      t.done();
    }
  },

  linkToSelf: async (t) => {
    var user = new UserLinkMockup();
    t.expect(1);

    user.link(user);

    await user.save();
    t.ok(true, 'Linking an object to itself failed.');
    t.done();
  },

  deppLinkErrorCallback: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      comment = new CommentLinkMockup();
    t.expect(7);

    role.link(user, {
      error: function (err, obj) {
        console.log(err, obj.errors, obj.allProperties())
        t.ok(false, 'Error callback for role.link(user) called even though user is valid.');
      }
    });
    user.link(comment, {
      error: function (err, obj) {
        t.ok(err instanceof nohm.ValidationError, 'err in error callback was not a ValidationError');
        t.same(comment, obj, 'obj in Error callback was not the right object.');
      }
    });
    comment.property('text', ''); // makes the comment fail

    try {
      await role.save();
    } catch (err) {
      t.ok(user.id !== null, 'The deeplinked user does not have an id and thus is probably not saved correctly.');
      t.same(comment.id, null, 'The deeplinked erroneous comment does not have an id and thus is probably saved.');
      t.ok(err, 'The deeplinked role did not fail.');
      t.ok(err instanceof nohm.LinkError, true, 'The deeplinked role did not fail in a child or reported it wrong.');
      t.same(err.errors[0].child.modelName, 'CommentLinkMockup', 'The deeplinked role failed in the wrong model or reported it wrong.');
      t.done();
    }
  },

  contineOnError: async (t) => {
    var user = new UserLinkMockup(),
      role = new RoleLinkMockup(),
      comment = new CommentLinkMockup(),
      comment2 = new CommentLinkMockup(),
      comment3 = new CommentLinkMockup();
    t.expect(4);

    role.link(user, {
      error: function (err, obj) {
        console.log(err, obj.errors, obj.allProperties())
        t.ok(false, 'Error callback for role.link(user) called even though user is valid.');
      }
    });
    user.link(comment, {
      error: function (err, obj) {
        t.ok(err instanceof nohm.ValidationError, 'err in error callback was not a ValidationError');
        t.same(comment, obj, 'obj in Error callback was not the right object.');
      }
    });
    user.link(comment2, {
      error: function (err, obj) {
        console.log(err, obj.errors, obj.allProperties())
        t.ok(false, 'Error callback for comment2.link(user) called even though user is valid.');
      }
    });
    user.link(comment3, {
      error: function (err, obj) {
        console.log(err, obj.errors, obj.allProperties())
        t.ok(false, 'Error callback for comment3.link(user) called even though user is valid.');
      }
    });
    comment.property('text', ''); // makes the first comment fail

    try {
      await role.save({ continue_on_link_error: true });
      t.done();
    } catch (e) {
      redis.sismember(relationsprefix + comment3.modelName + ':defaultForeign:' + user.modelName + ':' + comment3.id, user.id,
        function (err, value) {
          t.ok(!err, 'There was a redis error');
          t.same(value, "1", 'The comment3 relation was not saved');
          t.done();
        }
      );
    }
  }
};

/* Maybe this isn't such a good idea. I like that model definitions are completely
   lacking relation definitions.
cascadingDeletes: function (t) {
  var user = new UserLinkMockup(),
  role = new RoleLinkMockup(),
  comment = new CommentLinkMockup(),
  testComment = new CommentLinkMockup();
  t.expect(1);

  user.link(role);
  role.link(comment);

  user.save(function (err) {
    if (err) {
      console.dir(err);
      t.done();
    }
    var testid = comment.id;
    user.remove(function (err) {
      if (err) {
        console.dir(err);
        t.done();
      }
      testComment.load(testid, function (err) {
        t.equals(err, 'not found', 'Removing an object that has cascading deletes did not remove the relations');
        t.done();
      });
    });
  });
};*/
<|endoftext|>


<commit_before>var Gu = require('gu')
  , guParams = require('../')
  , sulfur = require('sulfur');

exports.response = function (t) {
  var clvr = new Gu(guParams.scriptdir, guParams.files, { noReload: true });
  sulfur.absorb(clvr.log, 'gu');
  var xs = [
    {user: '#chan:clux', name: 'clux', message: 'hi clvr'},
  ];
  xs.forEach(function (x) {
    clvr.write(x);
  });

  clvr.on('readable', function () {
    var resp = clvr.read();
    t.ok(resp, 'got a response');
    t.equal(resp.user, '#chan:clux', 'addressed to me');
    // TODO: if it starts failing - create a test to ensure
    // resp is not equal to "<html>"" or whatever it returns when permissions fail
    t.done();
  });
};
<commit_msg>simplify test<commit_after>var Gu = require('gu')
  , guParams = require('../')
  , sulfur = require('sulfur');

exports.response = function (t) {
  var clvr = new Gu(guParams.scriptdir, guParams.files, { noReload: true });
  sulfur.absorb(clvr.log, 'gu');
  clvr.write({user: '#chan:clux', name: 'clux', message: 'hi clvr'});

  clvr.on('readable', function () {
    var resp = clvr.read();
    t.ok(resp, 'got a response');
    t.equal(resp.user, '#chan:clux', 'addressed to me');
    // TODO: if it starts failing - create a test to ensure
    // resp is not equal to "<html>"" or whatever it returns when permissions fail
    t.done();
  });
};
<|endoftext|>


<commit_before>/**
 * @author NHN Ent. FE Development Team <dl_javascript@nhnent.com>
 * @fileoverview Test cases of "src/js/component/rotation.js"
 */
import fabric from 'fabric/dist/fabric.require';
import $ from 'jquery';
import Graphics from '../src/js/graphics';
import Rotation from '../src/js/component/rotation';
import 'core-js/library/es6/promise';

describe('Rotation', () => {
    let graphics, rotationModule, mockImage, canvas;

    beforeAll(() => {
        graphics = new Graphics($('<canvas>')[0]);
        canvas = graphics.getCanvas();
        rotationModule = new Rotation(graphics);
    });

    beforeEach(() => {
        mockImage = new fabric.Image();
        graphics.setCanvasImage('mockImage', mockImage);
    });

    it('"getCurrentAngle()" should return current angle value', () => {
        mockImage.angle = 30;

        expect(rotationModule.getCurrentAngle()).toEqual(30);
    });

    it('"setAngle()" should set angle value', () => {
        rotationModule.setAngle(40);

        expect(rotationModule.getCurrentAngle()).toEqual(40);
    });

    it('"rotate()" should add angle value', () => {
        let current = rotationModule.getCurrentAngle();

        rotationModule.rotate(10);
        expect(rotationModule.getCurrentAngle()).toBe(current + 10);

        current = rotationModule.getCurrentAngle();
        rotationModule.rotate(20);
        expect(rotationModule.getCurrentAngle()).toBe(current + 20);
    });

    it('"rotate()" should add angle value modular 360(===2*PI)', () => {
        rotationModule.setAngle(10).then(() => rotationModule.rotate(380)).then(() => {
            expect(rotationModule.getCurrentAngle()).toBe(30);
        });
    });

    // @todo Move this tc to main.spec.js
    it('"adjustCanvasDimension()" should set canvas dimension from image-rect', () => {
        spyOn(mockImage, 'getBoundingRect').and.returnValue({
            width: 100,
            height: 110
        });

        rotationModule.adjustCanvasDimension();
        expect(canvas.getWidth()).toEqual(100);
        expect(canvas.getHeight()).toEqual(110);
    });
});
<commit_msg>fixed broken test<commit_after>/**
 * @author NHN Ent. FE Development Team <dl_javascript@nhnent.com>
 * @fileoverview Test cases of "src/js/component/rotation.js"
 */
import fabric from 'fabric/dist/fabric.require';
import $ from 'jquery';
import Graphics from '../src/js/graphics';
import Rotation from '../src/js/component/rotation';

describe('Rotation', () => {
    let graphics, rotationModule, mockImage, canvas;

    beforeAll(() => {
        graphics = new Graphics($('<canvas>')[0]);
        canvas = graphics.getCanvas();
        rotationModule = new Rotation(graphics);
    });

    beforeEach(() => {
        mockImage = new fabric.Image();
        graphics.setCanvasImage('mockImage', mockImage);
    });

    it('"getCurrentAngle()" should return current angle value', () => {
        mockImage.angle = 30;

        expect(rotationModule.getCurrentAngle()).toEqual(30);
    });

    it('"setAngle()" should set angle value', () => {
        rotationModule.setAngle(40);

        expect(rotationModule.getCurrentAngle()).toEqual(40);
    });

    it('"rotate()" should add angle value', () => {
        let current = rotationModule.getCurrentAngle();

        rotationModule.rotate(10);
        expect(rotationModule.getCurrentAngle()).toBe(current + 10);

        current = rotationModule.getCurrentAngle();
        rotationModule.rotate(20);
        expect(rotationModule.getCurrentAngle()).toBe(current + 20);
    });

    it('"rotate()" should add angle value modular 360(===2*PI)', done => {
        rotationModule.setAngle(10).then(() => rotationModule.rotate(380)).then(() => {
            expect(rotationModule.getCurrentAngle()).toBe(30);
            done();
        });
    });

    // @todo Move this tc to main.spec.js
    it('"adjustCanvasDimension()" should set canvas dimension from image-rect', () => {
        spyOn(mockImage, 'getBoundingRect').and.returnValue({
            width: 100,
            height: 110
        });

        rotationModule.adjustCanvasDimension();
        expect(canvas.getWidth()).toEqual(100);
        expect(canvas.getHeight()).toEqual(110);
    });
});
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict';

let chai = require('chai');
let expect = chai.expect;
let chaiHttp = require('chai-http');
let server = require('../../app');

let ejs = require('ejs');
let read = require('fs').readFileSync;
let join = require('path').join;

chai.use(chaiHttp);

describe('logout', () => {
  describe('get request', () => {
    it('should render successfully with status 200', (done) => {
      let path, data, renderedView;
      chai.request(server)
            .get('/logout')
            .end(function (err, res) {
              if (err) {
                console.log(err);
              }
              expect(res).to.have.status(200);
              expect(res).to.redirect('/');
              expect(res).to.have.property('text');
              path = join(__dirname, '../../views/index.ejs');
              data = {title: 'JamaTrace'};
              renderedView = ejs.compile(read(path, 'utf8'), {filename: path})(data);
              expect(res.text).to.equal(renderedView);
              done();
            });
    });
  });
});
<commit_msg>Updated test on logout for error message<commit_after>/* eslint-env mocha */
'use strict';

let chai = require('chai');
let expect = chai.expect;
let chaiHttp = require('chai-http');
let server = require('../../app');

let ejs = require('ejs');
let read = require('fs').readFileSync;
let join = require('path').join;

chai.use(chaiHttp);

describe('logout', () => {
  describe('get request', () => {
    it('should render successfully with status 200', (done) => {
      let path, data, renderedView;
      chai.request(server)
            .get('/logout')
            .end(function (err, res) {
              if (err) {
                console.log(err);
              }
              expect(res).to.have.status(200);
              expect(res).to.redirect('/');
              expect(res).to.have.property('text');
              path = join(__dirname, '../../views/index.ejs');
              data = {title: 'JamaTrace', error: 'false'};
              renderedView = ejs.compile(read(path, 'utf8'), {filename: path})(data);
              expect(res.text).to.equal(renderedView);
              done();
            });
    });
  });
});
<|endoftext|>


<commit_before>const expect = require("chai").expect;
const assert = require("chai");
const request = require("request");
const Discord = require("discord.js");
const client = new Discord.Client();
const glob = require("glob-all");
const CLIEngine = require("eslint").CLIEngine;
const engine = new CLIEngine({
    envs: ["node", "mocha"],
    useEslintrc: true
});

const paths = glob.sync([
    "./+(bot|test)/**/*.js",
    "./*.js"
]);

const results = engine.executeOnFiles(paths).results;

describe("ESLint", () => {
    results.forEach((result) => generateTest(result));
});

describe("Token", () => {
    it("valid token", () => {
        client.loginWithToken(process.env.TOKEN).then(() => {
            done();
        });
    });
});
describe("Log In", () => {
    it("returns ready", () => {
        client.on("ready", () => {
            done();
        });
    });
});
describe("Twitter API", () => {
    var url = "https://cdn.syndication.twimg.com/widgets/timelines/" + process.env.TWITTER_API + "?&lang=en&supress_response_codes=true&rnd=" + Math.random();

    it("returns status 200", () => {
        /* eslint-disable no-unused-vars */
        request(url, (error, response, body) => {
            /* eslint-enable no-unused-vars */
            expect(response.statusCode).to.equal(200);
            done();
        });
    });
});
describe("Logout", () => {
    it("logs out", () => {
        client.logout().then(() => {
            done();
        });
    });
});

function generateTest(result) {
    const {
        filePath,
        messages
    } = result;

    it("validates " + filePath, () => {
        if (messages.length > 0) {
            assert.fail(false, true, formatMessages(messages));
        }
    });
}

function formatMessages(messages) {
    const errors = messages.map((message) => {
        return message.line + ":" + message.column + " " + message.message.slice(0, -1) + " - " + message.ruleId + "\n";
    });

    return "\n" + errors.join("");
}
<commit_msg>fixed test file<commit_after>const expect = require("chai").expect;
const assert = require("chai").assert;
const request = require("request");
const Discord = require("discord.js");
const client = new Discord.Client();
const glob = require("glob-all");
const CLIEngine = require("eslint").CLIEngine;
const engine = new CLIEngine({
    envs: ["node", "mocha"],
    useEslintrc: true
});

const paths = glob.sync([
    "./+(bot|test)/**/*.js",
    "./*.js"
]);

const results = engine.executeOnFiles(paths).results;

describe("ESLint", () => {
    results.forEach((result) => generateTest(result));
});

describe("Token", () => {
    it("valid token", () => {
        client.loginWithToken(process.env.TOKEN).then(() => {
            done();
        });
    });
});
describe("Log In", () => {
    it("returns ready", () => {
        client.on("ready", () => {
            done();
        });
    });
});
describe("Twitter API", () => {
    var url = "https://cdn.syndication.twimg.com/widgets/timelines/" + process.env.TWITTER_API + "?&lang=en&supress_response_codes=true&rnd=" + Math.random();

    it("returns status 200", () => {
        /* eslint-disable no-unused-vars */
        request(url, (error, response, body) => {
            /* eslint-enable no-unused-vars */
            expect(response.statusCode).to.equal(200);
            done();
        });
    });
});
describe("Logout", () => {
    it("logs out", () => {
        client.logout().then(() => {
            done();
        });
    });
});

function generateTest(result) {
    const {
        filePath,
        messages
    } = result;

    it("validates " + filePath, () => {
        if (messages.length > 0) {
            assert.fail(false, true, formatMessages(messages));
        }
    });
}

function formatMessages(messages) {
    const errors = messages.map((message) => {
        return message.line + ":" + message.column + " " + message.message.slice(0, -1) + " - " + message.ruleId + "\n";
    });

    return "\n" + errors.join("");
}
<|endoftext|>