Exemple #1
0
/* jshint camelcase: false */
var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/support')
  , Sequelize = Support.Sequelize
  // , sinon     = require('sinon')

chai.config.includeStack = true

describe(Support.getTestDialectTeaser("Sequelize Errors"), function () {
  describe('API Surface', function() {
    it('Should have the Error constructors exposed', function() {
      expect(Sequelize).to.have.property('Error')
      expect(Sequelize).to.have.property('ValidationError')
      var sequelize = new Sequelize();
      expect(sequelize).to.have.property('Error')
      expect(sequelize).to.have.property('ValidationError')
    })
    it('Sequelize Errors instances should be instances of Error', function() {
      var error = new Sequelize.Error();
      var validationError = new Sequelize.ValidationError();


      var sequelize = new Sequelize();
      var instError = new sequelize.Error();
      var instValidationError = new sequelize.ValidationError();

      expect(error).to.be.instanceOf(Error)
      expect(validationError).to.be.instanceOf(Error)
      expect(instError).to.be.instanceOf(Error)
      expect(instValidationError).to.be.instanceOf(Error)
Exemple #2
0
'use strict';

var chai = require('chai')
  , expect = chai.expect
  , Support   = require(__dirname + '/../support')
  , current   = Support.sequelize
  , Sequelize = Support.Sequelize
  , sinon     = require('sinon');

describe(Support.getTestDialectTeaser('Instance'), function() {
  describe('decrement', function () {
    describe('options tests', function() {
      var stub
        , Model = current.define('User', {
          id: {
            type:          Sequelize.BIGINT,
            primaryKey:    true,
            autoIncrement: true,
          }
        })
        , instance;

      before(function() {
        stub = sinon.stub(current, 'query').returns(
          Sequelize.Promise.resolve({
            _previousDataValues: {id: 3},
            dataValues: {id: 1}
          })
        );
      });
Exemple #3
0
/* jshint camelcase: false */
/* jshint expr: true */
var chai      = require('chai')
  , Sequelize = require('../../index')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , dialect   = Support.getTestDialect()
  , datetime  = require('chai-datetime')
  , _         = require('lodash')
  , assert    = require('assert')

chai.use(datetime)
chai.config.includeStack = true

describe(Support.getTestDialectTeaser("DAOFactory"), function () {
  beforeEach(function(done) {
    this.User = this.sequelize.define('User', {
      username:     DataTypes.STRING,
      secretValue:  DataTypes.STRING,
      data:         DataTypes.STRING,
      intVal:       DataTypes.INTEGER,
      theDate:      DataTypes.DATE,
      aBool:        DataTypes.BOOLEAN,
      uniqueName:   { type: DataTypes.STRING, unique: true }
    })

    this.User.sync({ force: true }).success(function() {
      done()
    })
  })
Exemple #4
0
'use strict';

var chai = require('chai')
  , expect = chai.expect
  , Support   = require(__dirname + '/support')
  , DataTypes = require(__dirname + '/../../lib/data-types')
  , util      = require('util')
  , expectsql = Support.expectsql
  , current   = Support.sequelize
  , sql       = current.dialect.QueryGenerator
  , Utils     = require(__dirname + '/../../lib/utils');

// Notice: [] will be replaced by dialect specific tick/quote character when there is not dialect specific expectation but only a default expectation

suite(Support.getTestDialectTeaser('Utils'), function() {
  suite('mapOptionFieldNames', function () {
    test('plain where', function () {
      expect(Utils.mapOptionFieldNames({
        where: {
          firstName: 'Paul',
          lastName: 'Atreides'
        }
      }, this.sequelize.define('User', {
        firstName: {
          type: DataTypes.STRING,
          field: 'first_name'
        },
        lastName: {
          type: DataTypes.STRING,
          field: 'last_name'
        }
var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/support')
  , DataTypes = require(__dirname + "/../lib/data-types")
  , dialect   = Support.getTestDialect()
  , _         = require('lodash')
  , exec      = require('child_process').exec
  , version   = (require(__dirname + '/../package.json')).version
  , path      = require('path')
  , os        = require('os')

chai.Assertion.includeStack = true

if (os.type().toLowerCase().indexOf('windows') === -1) {
  describe(Support.getTestDialectTeaser("Executable"), function() {
    describe('call without arguments', function() {
      it("prints usage instructions", function(done) {
        exec('bin/sequelize', function(err, stdout, stderr) {
          expect(stdout).to.include("No action specified. Try \"sequelize --help\" for usage information.")
          done()
        })
      })
    })

    ;(function(flags) {
      flags.forEach(function(flag) {
        describe(flag, function() {
          it("prints the help", function(done) {
            exec("bin/sequelize " + flag, function(err, stdout, stderr) {
              expect(stdout).to.include("Usage: sequelize [options]")
              done()
var chai        = require('chai')
  , expect      = chai.expect
  , Support     = require(__dirname + '/support')
  , dialect     = Support.getTestDialect()
  , Transaction = require(__dirname + '/../lib/transaction')
  , sinon       = require('sinon')


describe(Support.getTestDialectTeaser("Transaction"), function () {
  this.timeout(4000);
  describe('constructor', function() {
    it('stores options', function() {
      var transaction = new Transaction(this.sequelize)
      expect(transaction.options).to.be.an.instanceOf(Object)
    })

    it('generates an identifier', function() {
      var transaction = new Transaction(this.sequelize)
      expect(transaction.id).to.exist
    })
  })

  describe('commit', function() {
    it('is a commit method available', function() {
      expect(Transaction).to.respondTo('commit')
    })
  })

  describe('rollback', function() {
    it('is a rollback method available', function() {
      expect(Transaction).to.respondTo('rollback')
/* jshint -W030 */
/* jshint -W110 */
var chai = require('chai')
  , Sequelize = require('../../index')
  , expect = chai.expect
  , Support = require(__dirname + '/support')
  , sinon = require('sinon')
  , _ = require('lodash')
  , moment = require('moment')
  , current = Support.sequelize
  , uuid = require('uuid')
  , DataTypes = require('../../lib/data-types')
  , dialect = Support.getTestDialect();

describe(Support.getTestDialectTeaser('DataTypes'), function() {
  afterEach(function () {
    // Restore some sanity by resetting all parsers
    switch (dialect) {
      case 'postgres':
        var types = require('pg-types');

        _.each(DataTypes, function (dataType) {
          if (dataType.types && dataType.types.postgres) {
            dataType.types.postgres.oids.forEach(function (oid) {
              types.setTypeParser(oid, _.identity);
            });
          }
        });
        require('pg-types/lib/binaryParsers').init(function (oid, converter) {
          types.setTypeParser(oid, 'binary', converter);
Exemple #8
0
var chai         = require('chai')
  , expect       = chai.expect
  , Support      = require(__dirname + '/support')
  , DataTypes    = require(__dirname + "/../lib/data-types")
  , QueryChainer = require("../lib/query-chainer")
  , Migrator     = require("../lib/migrator")
  , dialect      = Support.getTestDialect()

chai.Assertion.includeStack = true

describe(Support.getTestDialectTeaser("Migrator"), function() {
  beforeEach(function() {
    this.init = function(options, callback) {
      options = Support.Sequelize.Utils._.extend({
        path:    __dirname + '/assets/migrations',
        logging: function(){}
      }, options || {})

      var migrator = new Migrator(this.sequelize, options)

      migrator
        .findOrCreateSequelizeMetaDAO({ force: true })
        .success(function(SequelizeMeta) {
          callback && callback(migrator, SequelizeMeta)
        })
        .error(function(err) { console.log(err) })
    }.bind(this)
  })

  describe('getUndoneMigrations', function() {
    it("returns no files if timestamps are after the files timestamp", function(done) {
  , current = Support.sequelize;


chai.config.includeStack = true;

var qq = function(str) {
  if (dialect === 'postgres' || dialect === 'sqlite' || dialect === 'mssql') {
    return '"' + str + '"';
  } else if (Support.dialectIsMySQL()) {
    return '`' + str + '`';
  } else {
    return str;
  }
};

describe(Support.getTestDialectTeaser('Sequelize'), function() {
  describe('constructor', function() {
    if (dialect !== 'sqlite') {
      it('should work with minConnections', function() {
        var ConnectionManager = require(__dirname + '/../lib/dialects/' + dialect + '/connection-manager.js')
          , connectionSpy = ConnectionManager.prototype.connect = chai.spy(ConnectionManager.prototype.connect);

        var sequelize = Support.createSequelizeInstance({
          pool: {
            minConnections: 2
          }
        });
        expect(connectionSpy).to.have.been.called.twice;
      });
    }
Exemple #10
0
'use strict';

/* jshint -W030 */
var chai = require('chai')
  , expect = chai.expect
  , Support = require(__dirname + '/../support')
  , DataTypes = require(__dirname + '/../../../lib/data-types')
  , Sequelize = require(__dirname + '/../../../index')
  , Promise = Sequelize.Promise
  , _ = require('lodash');

describe(Support.getTestDialectTeaser('Self'), function() {
  it('supports freezeTableName', function() {
    var Group = this.sequelize.define('Group', {}, {
      tableName: 'user_group',
      timestamps: false,
      underscored: true,
      freezeTableName: true
    });

    Group.belongsTo(Group, { as: 'Parent', foreignKey: 'parent_id' });
    return Group.sync({force: true}).then(function() {
      return Group.findAll({
        include: [{
          model: Group,
          as: 'Parent'
        }]
      });
    });
  });
Exemple #11
0
'use strict';

const util = require('util');
const chai = require('chai');
const expect = chai.expect;
const Support   = require(__dirname + '/../support');
const DataTypes = require(__dirname + '/../../../lib/data-types');
const Model = require(__dirname + '/../../../lib/model');
const expectsql = Support.expectsql;
const current = Support.sequelize;
const sql = current.dialect.QueryGenerator;

// Notice: [] will be replaced by dialect specific tick/quote character when there is not dialect specific expectation but only a default expectation

describe(Support.getTestDialectTeaser('SQL'), () => {
  describe('order', () => {
    const testsql = (options, expectation) => {
      const model = options.model;

      it(util.inspect(options, {depth: 2}), () => {
        return expectsql(
          sql.selectQuery(
            options.table || model && model.getTableName(),
            options,
            options.model
          ),
          expectation
        );
      });
    };
Exemple #12
0
'use strict';

const chai = require('chai');
const expect = chai.expect;
const Support = require(__dirname + '/support');
const dialect = Support.getTestDialect();
const sinon = require('sinon');
const Sequelize = Support.Sequelize;

describe(Support.getTestDialectTeaser('Pooling'), function() {
  if (dialect === 'sqlite') return;

  beforeEach(() => {
    this.sinon = sinon.sandbox.create();
  });

  afterEach(() => {
    this.sinon.restore();
  });

  it('should reject when unable to acquire connection in given time', () => {
    this.testInstance = new Sequelize('localhost', 'ffd', 'dfdf', {
      dialect,
      databaseVersion: '1.2.3',
      pool: {
        acquire: 1000 //milliseconds
      }
    });

    this.sinon.stub(this.testInstance.connectionManager, '_connect')
      .returns(new Sequelize.Promise(() => {}));
Exemple #13
0
'use strict';

/* jshint camelcase: false */
/* jshint -W030 */
var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/support')
  , Sequelize = Support.Sequelize
  , Promise   = Sequelize.Promise
  , cls       = require('continuation-local-storage')
  , current = Support.sequelize;

if (current.dialect.supports.transactions) {
  describe(Support.getTestDialectTeaser('Continuation local storage'), function () {
    before(function () {
      Sequelize.cls = cls.createNamespace('sequelize');
    });

    after(function () {
      delete Sequelize.cls;
    });

    beforeEach(function () {
      return Support.prepareTransactionTest(this.sequelize).bind(this).then(function (sequelize) {
        this.sequelize = sequelize;

        this.ns = cls.getNamespace('sequelize');

        this.User = this.sequelize.define('user', {
          name: Sequelize.STRING
        });
'use strict';

const chai = require('chai'),
  expect = chai.expect,
  config = require(__dirname + '/../config/config'),
  Support = require(__dirname + '/support'),
  dialect = Support.getTestDialect(),
  Sequelize = Support.Sequelize,
  fs = require('fs'),
  path = require('path');

if (dialect === 'sqlite') {
  var sqlite3 = require('sqlite3'); // eslint-disable-line
}

describe(Support.getTestDialectTeaser('Configuration'), () => {
  describe('Connections problems should fail with a nice message', () => {
    it('when we don\'t have the correct server details', () => {
      const seq = new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, {storage: '/path/to/no/where/land', logging: false, host: '0.0.0.1', port: config[dialect].port, dialect});
      if (dialect === 'sqlite') {
        // SQLite doesn't have a breakdown of error codes, so we are unable to discern between the different types of errors.
        return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(seq.ConnectionError, 'SQLITE_CANTOPEN: unable to open database file');
      } else {
        return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith([seq.HostNotReachableError, seq.InvalidConnectionError]);
      }
    });

    it('when we don\'t have the correct login information', () => {
      if (dialect === 'mssql') {
        // NOTE: Travis seems to be having trouble with this test against the
        //       AWS instance. Works perfectly fine on a local setup.
'use strict';

/* jshint -W030 */
const chai = require('chai');
const expect = chai.expect;
const Support = require(__dirname + '/support');
const DataTypes = require(__dirname + '/../../lib/data-types');
const Utils = require(__dirname + '/../../lib/utils');

suite(Support.getTestDialectTeaser('Utils'), () => {
  suite('merge', () => {
    test('does not clone sequelize models', () => {
      const User = Support.sequelize.define('user');
      const merged = Utils.merge({}, { include: [{model : User }]});
      const merged2 = Utils.merge({}, { user: User });

      expect(merged.include[0].model).to.equal(User);
      expect(merged2.user).to.equal(User);
    });
  });

  suite('toDefaultValue', () => {
    test('return plain data types', () => {
      expect(Utils.toDefaultValue(DataTypes.UUIDV4)).to.equal('UUIDV4');
    });
    test('return uuid v1', () => {
      expect(/^[a-z0-9\-]{36}$/.test(Utils.toDefaultValue(DataTypes.UUIDV1()))).to.be.equal(true);
    });
    test('return uuid v4', () => {
      expect(/^[a-z0-9\-]{36}/.test(Utils.toDefaultValue(DataTypes.UUIDV4()))).to.be.equal(true);
    });
'use strict';

/* jshint -W030 */
var chai = require('chai')
  , expect = chai.expect
  , Support = require(__dirname + '/../support')
  , DataTypes = require(__dirname + '/../../../lib/data-types')
  , sinon = require('sinon');

describe(Support.getTestDialectTeaser('Hooks'), function() {
  beforeEach(function() {
    this.User = this.sequelize.define('User', {
      username: {
        type: DataTypes.STRING,
        allowNull: false
      },
      mood: {
        type: DataTypes.ENUM,
        values: ['happy', 'sad', 'neutral']
      }
    });
    return this.sequelize.sync({ force: true });
  });

  describe('#updateAttributes', function() {
    describe('on success', function() {
      it('should run hooks', function() {
        var beforeHook = sinon.spy()
          , afterHook = sinon.spy()
          , beforeSave = sinon.spy()
          , afterSave = sinon.spy();
Exemple #17
0
'use strict';

const chai = require('chai'),
  sinon = require('sinon'),
  Sequelize = require('../../../index'),
  Promise = Sequelize.Promise,
  expect = chai.expect,
  moment = require('moment'),
  Support = require(__dirname + '/../support'),
  dialect = Support.getTestDialect(),
  DataTypes = require(__dirname + '/../../../lib/data-types'),
  config = require(__dirname + '/../../config/config'),
  current = Support.sequelize;

describe(Support.getTestDialectTeaser('Model'), () => {
  beforeEach(function() {
    this.User = this.sequelize.define('User', {
      username: DataTypes.STRING,
      secretValue: DataTypes.STRING,
      data: DataTypes.STRING,
      intVal: DataTypes.INTEGER,
      theDate: DataTypes.DATE,
      aBool: DataTypes.BOOLEAN
    });

    return this.User.sync({ force: true });
  });

  describe('find', () => {
    if (current.dialect.supports.transactions) {
      it('supports transactions', function() {
Exemple #18
0
'use strict';

const Support = require(__dirname + '/../support'),
  DataTypes = require(__dirname + '/../../../lib/data-types'),
  expect = require('chai').expect,
  expectsql = Support.expectsql,
  Sequelize = Support.Sequelize,
  current = Support.sequelize,
  sql = current.dialect.QueryGenerator;

// Notice: [] will be replaced by dialect specific tick/quote character when there is not dialect specific expectation but only a default expectation

if (current.dialect.supports.JSON) {
  suite(Support.getTestDialectTeaser('SQL'), () => {
    suite('JSON', () => {
      suite('escape', () => {
        test('plain string', () => {
          expectsql(sql.escape('string', { type: new DataTypes.JSON() }), {
            default: '\'"string"\''
          });
        });

        test('plain int', () => {
          expectsql(sql.escape(0, { type: new DataTypes.JSON() }), {
            default: '\'0\''
          });
          expectsql(sql.escape(123, { type: new DataTypes.JSON() }), {
            default: '\'123\''
          });
        });
Exemple #19
0
'use strict';

const chai = require('chai'),
  expect = chai.expect,
  Support = require(__dirname + '/../support'),
  DataTypes = require(__dirname + '/../../../lib/data-types'),
  Sequelize = Support.Sequelize,
  dialect = Support.getTestDialect(),
  sinon = require('sinon'),
  Promise = require('bluebird');

describe(Support.getTestDialectTeaser('Hooks'), () => {
  beforeEach(function() {
    this.User = this.sequelize.define('User', {
      username: {
        type: DataTypes.STRING,
        allowNull: false
      },
      mood: {
        type: DataTypes.ENUM,
        values: ['happy', 'sad', 'neutral']
      }
    });

    this.ParanoidUser = this.sequelize.define('ParanoidUser', {
      username: DataTypes.STRING,
      mood: {
        type: DataTypes.ENUM,
        values: ['happy', 'sad', 'neutral']
      }
    }, {
Exemple #20
0
]).forEach(function (flag) {
  var prepare = function (callback, options) {
    options = _.assign({ config: {} }, options || {});

    var configPath    = 'config/';
    var migrationFile = options.migrationFile || 'createPerson';
    var config        = _.assign({}, helpers.getTestConfig(), options.config);
    var configContent = JSON.stringify(config);

    migrationFile = migrationFile + '.'  + ((flag.indexOf('coffee') === -1) ? 'js' : 'coffee');

    if (flag.match(/config\.js$/)) {
      configPath    = configPath + 'config.js';
      configContent = 'module.exports = ' + configContent;
    } else {
      configPath = configPath + 'config.json';
    }

    gulp
      .src(Support.resolveSupportPath('tmp'))
      .pipe(helpers.clearDirectory())
      .pipe(helpers.runCli('init'))
      .pipe(helpers.removeFile('config/config.json'))
      .pipe(helpers.copyMigration(migrationFile))
      .pipe(helpers.overwriteFile(configContent, configPath))
      .pipe(helpers.runCli(flag, { pipeStdout: true }))
      .pipe(helpers.teardown(callback));
  };

  describe(Support.getTestDialectTeaser(flag), function () {
    it('creates a SequelizeMeta table', function (done) {
      var self = this;

      prepare(function () {
        helpers.readTables(self.sequelize, function (tables) {
          expect(tables).to.have.length(2);
          expect(tables).to.contain('SequelizeMeta');
          done();
        });
      });
    });

    it('creates the respective table', function (done) {
      var self = this;

      prepare(function () {
        helpers.readTables(self.sequelize, function (tables) {
          expect(tables).to.have.length(2);
          expect(tables).to.contain('Person');
          done();
        });
      });
    });

    describe('the logging option', function () {
      it('does not print sql queries by default', function (done) {
        prepare(function (_, stdout) {
          expect(stdout).to.not.contain('Executing');
          done();
        });
      });

      it('interpretes a custom option', function (done) {
        prepare(function (_, stdout) {
          expect(stdout).to.contain('Executing');
          done();
        }, { config: { logging: true } });
      });
    });

    describe('promise based migrations', function () {
      it('correctly creates two tables', function (done) {
        var self = this;

        prepare(function () {
          helpers.readTables(self.sequelize, function (tables) {
            expect(tables.sort()).to.eql([
              'Person',
              'SequelizeMeta',
              'Task'
            ]);
            done();
          });
        }, {
          migrationFile: 'new/*createPerson',
          config:        { promisifyMigrations: false }
        });
      });
    });

    describe('custom meta table name', function () {
      it('correctly uses the defined table name', function (done) {
        var self = this;

        prepare(function () {
          helpers.readTables(self.sequelize, function (tables) {
            expect(tables.sort()).to.eql(['Person', 'Task', 'sequelize_meta']);
            done();
          });
        }, {
          migrationFile: 'new/*createPerson',
          config:        { migrationStorageTableName: 'sequelize_meta' }
        });
      });
    });
  });
});
'use strict';

/* jshint -W030 */
var chai = require('chai')
  , sinon = require('sinon')
  , expect = chai.expect
  , stub = sinon.stub
  , Support   = require(__dirname + '/../support')
  , DataTypes = require(__dirname + '/../../../lib/data-types')
  , BelongsTo = require(__dirname + '/../../../lib/associations/belongs-to')
  , HasMany = require(__dirname + '/../../../lib/associations/has-many')
  , HasOne = require(__dirname + '/../../../lib/associations/has-one')
  , current   = Support.sequelize
  , Promise   = current.Promise;

describe(Support.getTestDialectTeaser('belongsToMany'), function() {
  it('should not inherit scopes from parent to join table', function () {
    var A = current.define('a')
      , B = current.define('b', {}, {
        defaultScope: {
          where: {
            foo: 'bar'
          }
        },
        scopes: {
          baz: {
            where: {
              fooz: 'zab'
            }
          }
        }
Exemple #22
0
'use strict';

const chai = require('chai'),
  Sequelize = require('../../index'),
  expect = chai.expect,
  Support = require(__dirname + '/support'),
  sinon = require('sinon'),
  _ = require('lodash'),
  moment = require('moment'),
  current = Support.sequelize,
  uuid = require('uuid'),
  DataTypes = require('../../lib/data-types'),
  dialect = Support.getTestDialect(),
  semver = require('semver');

describe(Support.getTestDialectTeaser('DataTypes'), () => {
  afterEach(function() {
    // Restore some sanity by resetting all parsers
    this.sequelize.connectionManager._clearTypeParser();
    this.sequelize.connectionManager.refreshTypeParser(DataTypes[dialect]); // Reload custom parsers
  });

  it('allows me to return values from a custom parse function', () => {
    const parse = Sequelize.DATE.parse = sinon.spy(value => {
      return moment(value, 'YYYY-MM-DD HH:mm:ss');
    });

    const stringify = Sequelize.DATE.prototype.stringify = sinon.spy(function(value, options) {
      if (!moment.isMoment(value)) {
        value = this._applyTimezone(value, options);
      }
var chai        = require('chai')
  , expect      = chai.expect
  , Support     = require(__dirname + '/support')
  , Promise     = require(__dirname + '/../lib/promise')
  , Transaction = require(__dirname + '/../lib/transaction')

describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
  this.timeout(4000);

  describe('success', function() {
    it("gets triggered once a transaction has been successfully committed", function(done) {
      this
        .sequelize
        .transaction(function(t) { t.commit(); })
        .success(function() { done(); });
    });

    it("gets triggered once a transaction has been successfully rollbacked", function(done) {
      this
        .sequelize
        .transaction(function(t) { t.rollback(); })
        .success(function() { done(); });
    });

    if (Support.getTestDialect() !== 'sqlite') {
      it('works for long running transactions', function(done) {
        Support.prepareTransactionTest(this.sequelize, function(sequelize) {
          var User = sequelize.define('User', {
            name: Support.Sequelize.STRING
          }, { timestamps: false });
Exemple #24
0
'use strict';

/* jshint -W030 */
var chai = require('chai')
  , expect = chai.expect
  , Support = require(__dirname + '/support')
  , DataTypes = require(__dirname + '/../../lib/data-types')
  , SequelizePromise = require(__dirname + '/../../lib/promise')
  , sinon = require('sinon');

chai.config.includeStack = true;

describe(Support.getTestDialectTeaser('Promise'), function() {
  beforeEach(function() {
    return Support.prepareTransactionTest(this.sequelize).bind(this).then(function(sequelize) {
      this.sequelize = sequelize;
      this.User = this.sequelize.define('User', {
        username: { type: DataTypes.STRING },
        touchedAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
        aNumber: { type: DataTypes.INTEGER },
        bNumber: { type: DataTypes.INTEGER },

        validateTest: {
          type: DataTypes.INTEGER,
          allowNull: true,
          validate: {isInt: true}
        },
        validateCustom: {
          type: DataTypes.STRING,
          allowNull: true,
          validate: {len: {msg: 'Length failed.', args: [1, 20]}}
'use strict';

/* jshint -W030 */
var chai = require('chai')
  , expect = chai.expect
  , config = require(__dirname + '/../config/config')
  , Support = require(__dirname + '/support')
  , dialect = Support.getTestDialect()
  , Sequelize = Support.Sequelize
  , sqlite3 = require('sqlite3')
  , fs = require('fs')
  , path = require('path');



describe(Support.getTestDialectTeaser('Configuration'), function() {
  describe('Connections problems should fail with a nice message', function() {
    it('when we don\'t have the correct server details', function() {
      if (dialect === 'mariadb') {
        console.log('This dialect doesn\'t support me :(');
        expect(true).to.be.true; // Silence Buster
        return;
      }

      var seq = new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, {storage: '/path/to/no/where/land', logging: false, host: '0.0.0.1', port: config[dialect].port, dialect: dialect});
      if (dialect === 'sqlite') {
        // SQLite doesn't have a breakdown of error codes, so we are unable to discern between the different types of errors.
        return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(seq.ConnectionError, 'SQLITE_CANTOPEN: unable to open database file');
      } else {
        return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith([seq.HostNotReachableError, seq.InvalidConnectionError]);
      }
'use strict';

/* jshint -W030 */
var chai = require('chai')
  , sinon = require('sinon')
  , expect = chai.expect
  , Support = require(__dirname + '/../support')
  , DataTypes = require(__dirname + '/../../../lib/data-types')
  , Sequelize = require('../../../index')
  , Promise = Sequelize.Promise
  , current = Support.sequelize;

describe(Support.getTestDialectTeaser('BelongsTo'), function() {
  describe('Model.associations', function() {
    it('should store all assocations when associting to the same table multiple times', function() {
      var User = this.sequelize.define('User', {})
        , Group = this.sequelize.define('Group', {});

      Group.belongsTo(User);
      Group.belongsTo(User, { foreignKey: 'primaryGroupId', as: 'primaryUsers' });
      Group.belongsTo(User, { foreignKey: 'secondaryGroupId', as: 'secondaryUsers' });

      expect(Object.keys(Group.associations)).to.deep.equal(['User', 'primaryUsers', 'secondaryUsers']);
    });
  });

  describe('getAssociation', function() {

    if (current.dialect.supports.transactions) {
      it('supports transactions', function() {
        return Support.prepareTransactionTest(this.sequelize).then(function (sequelize) {
'use strict';

/* jshint -W030 */
var chai = require('chai')
  , Sequelize = require('../../../../index')
  , expect = chai.expect
  , Support = require(__dirname + '/../../support')
  , DataTypes = require(__dirname + '/../../../../lib/data-types');

describe(Support.getTestDialectTeaser('Model'), function() {
  describe('create', function() {
    describe('include', function() {
      it('should create data for BelongsTo relations', function() {
        var Product = this.sequelize.define('Product', {
          title: Sequelize.STRING
        });
        var User = this.sequelize.define('User', {
          first_name: Sequelize.STRING,
          last_name: Sequelize.STRING
        }, {
          hooks: {
            beforeCreate: function (user, options) {
              user.createOptions = options;
            }
          }
        });

        Product.belongsTo(User);

        return this.sequelize.sync({ force: true }).then(function() {
          return Product.create({
Exemple #28
0
'use strict';

/* jshint -W110 */
var Support   = require(__dirname + '/../support')
  , DataTypes = require(__dirname + '/../../../lib/data-types')
  , Model = require(__dirname + '/../../../lib/model')
  , util = require('util')
  , expectsql = Support.expectsql
  , current   = Support.sequelize
  , sql       = current.dialect.QueryGenerator;

// Notice: [] will be replaced by dialect specific tick/quote character when there is not dialect specific expectation but only a default expectation

suite(Support.getTestDialectTeaser('SQL'), function() {
  suite('select', function () {
    var testsql = function (options, expectation) {
      var model = options.model;

      test(util.inspect(options, {depth: 2}), function () {
        return expectsql(
          sql.selectQuery(
            options.table || model && model.getTableName(),
            options,
            options.model
          ),
          expectation
        );
      });
    };

    testsql({
Exemple #29
0
'use strict';

const chai = require('chai'),
  expect = chai.expect,
  Support = require(__dirname + '/../support'),
  DataTypes = require(__dirname + '/../../../lib/data-types'),
  Sequelize = require('../../../index'),
  Promise = Sequelize.Promise;

describe(Support.getTestDialectTeaser('associations'), () => {
  describe('scope', () => {
    beforeEach(function() {
      this.Post = this.sequelize.define('post', {});
      this.Image = this.sequelize.define('image', {});
      this.Question = this.sequelize.define('question', {});
      this.Comment = this.sequelize.define('comment', {
        title: Sequelize.STRING,
        commentable: Sequelize.STRING,
        commentable_id: Sequelize.INTEGER,
        isMain: {
          type: Sequelize.BOOLEAN,
          defaultValue: false
        }
      });

      this.Comment.prototype.getItem = function() {
        return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)]();
      };

      this.Post.addScope('withComments', {
        include: [this.Comment]
Exemple #30
0
'use strict';

const chai = require('chai'),
  expect = chai.expect,
  Support   = require(__dirname + '/../support'),
  current   = Support.sequelize,
  Sequelize = Support.Sequelize,
  sinon     = require('sinon');

describe(Support.getTestDialectTeaser('Instance'), () => {
  describe('save', () => {
    it('should disallow saves if no primary key values is present', () => {
      const Model = current.define('User', {

        }),
        instance = Model.build({}, {isNewRecord: false});

      expect(() => {
        instance.save();
      }).to.throw();
    });

    describe('options tests', () => {
      let stub, instance;
      const Model = current.define('User', {
        id: {
          type: Sequelize.BIGINT,
          primaryKey: true,
          autoIncrement: true
        }
      });