Skip to content

Commit

Permalink
Test Unit Database Model
Browse files Browse the repository at this point in the history
  • Loading branch information
a632079 committed Jan 29, 2018
1 parent d3e58a5 commit 4c78331
Show file tree
Hide file tree
Showing 9 changed files with 266 additions and 38 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
node_modules/
config.json
logs/*.log
.nyc_output/
coverage/
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@
"scripts": {
"start": "node core --harmony",
"watch": "supervisor --watch \".\" --extensions \"js,json\" --exec \"node\" --harmony -- \"core.js\"",
"test": "mocha"
"mocha": "mocha test/unit",
"test": "nyc --reporter=html --reporter=text-summary mocha test\\unit",
"coverall": "nyc report --reporter=text-lcov | coveralls && rm -r coverage"
},
"repository": "https://github.com/a632079/teng-koa",
"author": "a632079 <a632079@qq.com>",
"license": "MIT",
"private": true,
"devDependencies": {
"chai": "^4.1.2",
"eslint": "^4.16.0",
"eslint-config-standard": "^11.0.0-beta.0",
"eslint-plugin-import": "^2.8.0",
Expand Down
81 changes: 45 additions & 36 deletions src/db.js
Original file line number Diff line number Diff line change
@@ -1,54 +1,63 @@
const Sequelize = require('sequelize')
const nconf = require('nconf')
const winston = require('winston')
const path = require('path')
const winston = require('winston')

class db {
constructor (model) {
this.connect()
return this.registerModel(model)
}
static async connect () {
const type = nconf.get('database')
const config = {
password: nconf.get(type + ':password'),
username: nconf.get(type + ':username'),
database: nconf.get(type + ':database'),
host: nconf.get(type + ':host'),
port: nconf.get(type + ':port')
}
const sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
port: config.port,
dialect: type,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
operatorsAliases: false
})
// Test Connection
await sequelize.authenticate()
.then(() => {
winston.verbose('Database Connection has been established successfully.')
})
.catch(err => {
winston.error(err)
process.exit(1)
if (this.sequelize) {
return this.sequelize
} else {
const type = nconf.get('database')
const config = {
password: nconf.get(type + ':password'),
username: nconf.get(type + ':username'),
database: nconf.get(type + ':database'),
host: nconf.get(type + ':host'),
port: nconf.get(type + ':port')
}
const sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
port: config.port,
dialect: type,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
operatorsAliases: false
})
// Test Connection
await sequelize.authenticate()
.then(() => {
winston.verbose('Database Connection has been established successfully.')
})
.catch(err => {
winston.error(err.message)
})

this.sequelize = sequelize
return true
this.sequelize = sequelize
return sequelize
}
}
static registerModel (model) {
this.connect()
this[model] = this.sequelize.define(model, require(path.join(__dirname, '../', './src/models/databases', model, '.js')))
return this[model]
static async registerModel (model) {
await this.connect()
if (this[model]) {
return this[model]
} else {
// Register Model
const modelArray = require(path.join(__dirname, '../', './src/models/databases', model))
this[model] = this.sequelize.define(model, modelArray[0], modelArray[1])
return this[model]
}
}

static load () {
static get () {
this.connect()
return this
}
Expand Down
23 changes: 23 additions & 0 deletions src/models/databases/hitokoto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Load Base Model
const model = require('./model')

// Define Database Model
module.exports = [{
id: {
type: model.INTEGER,
primaryKey: true,
autoIncrement: true
},
hitokoto: model.STRING,
type: model.STRING,
from: model.STRING,
from_who: model.STRING,
creator: model.STRING,
creator_uid: model.STRING,
assessor: model.STRING,
owner: model.STRING,
created_at: model.STRING,
}, {
// Sequelize Model config
timestamps: false
}]
65 changes: 65 additions & 0 deletions test/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const Sequelize = require('sequelize')
const nconf = require('nconf')
const path = require('path')

class db {
constructor (model) {
this.connect()
return this.registerModel(model)
}
static async connect () {
if (this.sequelize) {
return this.sequelize
} else {
const type = nconf.get('database')
const config = {
password: nconf.get(type + ':password'),
username: nconf.get(type + ':username'),
database: nconf.get(type + ':database'),
host: nconf.get(type + ':host'),
port: nconf.get(type + ':port')
}
const sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
port: config.port,
dialect: type,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
operatorsAliases: false
})
// Test Connection
await sequelize.authenticate()
.then(() => {
// console.log('Database Connection has been established successfully.')
})
.catch(err => {
console.error(err.message)
})

this.sequelize = sequelize
return sequelize
}
}
static async registerModel (model) {
await this.connect()
if (this[model]) {
return this[model]
} else {
// Register Model
const modelArray = require(path.join(__dirname, '../', './src/models/databases', model))
this[model] = this.sequelize.define(model, modelArray[0], modelArray[1])
return this[model]
}
}

static get () {
this.connect()
return this
}
}

module.exports = db
64 changes: 64 additions & 0 deletions test/prestart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict'
const winston = require('winston')
const config = require('../config')
const nconf = require('nconf')
const pkg = require('../package.json')
const path = require('path')
const fs = require('fs')
const dirname = path.join(__dirname, '../')

function setupWinston () {
const logFile = config.log_path || path.join(__dirname, '../', './logs/', pkg.name + '.log')
fs.existsSync(logFile) || fs.writeFileSync(logFile, '')
winston.remove(winston.transports.Console)
winston.add(winston.transports.File, {
filename: logFile,
level: config.log_level || (global.env === 'production' ? 'info' : 'verbose'),
handleExceptions: true,
maxsize: 5242880,
maxFiles: 10
})
winston.add(winston.transports.Console, {
colorize: nconf.get('log-colorize') !== 'false',
timestamp: function () {
var date = new Date()
return config.json_logging ? date.toJSON()
: date.toISOString() + ' [' + global.process.pid + ']'
},
level: config.log_level || (global.env === 'production' ? 'info' : 'verbose'),
json: !!config.json_logging,
stringify: !!config.json_logging
})
}

function loadConfig (configFile) {
winston.verbose('* using configuration stored in: %s', configFile)

nconf.file({
file: configFile
})

nconf.defaults({
base_dir: dirname,
version: pkg.version
})

if (!nconf.get('isCluster')) {
nconf.set('isPrimary', 'true')
nconf.set('isCluster', 'false')
}
}

function printCopyright () {
const colors = require('colors/safe')
const date = new Date()
console.log(colors.bgBlue(colors.black(' ' + pkg.name + ' v' + pkg.version + ' © ' + date.getFullYear() + ' All Rights Reserved. ')) + ' ' + colors.bgRed(colors.black(' Powered by teng-koa ')))
console.log('')
console.log(colors.bgCyan(colors.black(' 我们一路奋战,不是为了改变世界,而是为了不让世界改变我们。 ')))
}

module.exports = {
load: () => {
loadConfig(path.join(__dirname, '../', 'config.json'))
}
}
26 changes: 26 additions & 0 deletions test/unit/hitokoto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Test Hitokoto Database Connection
const expect = require('chai').expect
const path = require('path')
const srcDir = path.join(__dirname, '../../src/')
const testDir = path.join(__dirname, '../')
const prestart = require(testDir + 'prestart')
prestart.load()
describe('Hitokoto Datebase Test', () => {
const db = require(testDir + 'db')
it('DB Connection should be true', async () => {
const result = !!await db.connect()
expect(result).to.be.true
})
it('Register Model should be true', async() => {
const result = !!await db.registerModel('hitokoto')
expect(result).to.be.true
})
it('Try get data from database', async () => {
const hitokoto = await db.registerModel('hitokoto')
const data = await hitokoto.findOne()
expect(!!data).to.be.true
})
after(()=>{
process.exit()
})
})
1 change: 0 additions & 1 deletion test/unit/test.js

This file was deleted.

37 changes: 37 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ arrify@^1.0.0, arrify@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d"

assertion-error@^1.0.1:
version "1.1.0"
resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.1.0.tgz#e60b6b0e8f301bd97e5375215bda406c85118c0b"

async@^1.4.0:
version "1.5.2"
resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a"
Expand Down Expand Up @@ -305,6 +309,17 @@ center-align@^0.1.1:
align-text "^0.1.3"
lazy-cache "^1.0.3"

chai@^4.1.2:
version "4.1.2"
resolved "https://registry.yarnpkg.com/chai/-/chai-4.1.2.tgz#0f64584ba642f0f2ace2806279f4f06ca23ad73c"
dependencies:
assertion-error "^1.0.1"
check-error "^1.0.1"
deep-eql "^3.0.0"
get-func-name "^2.0.0"
pathval "^1.0.0"
type-detect "^4.0.0"

chalk@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98"
Expand All @@ -327,6 +342,10 @@ chardet@^0.4.0:
version "0.4.2"
resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.4.2.tgz#b5473b33dc97c424e5d98dc87d55d4d8a29c8bf2"

check-error@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/check-error/-/check-error-1.0.2.tgz#574d312edd88bb5dd8912e9286dd6c0aed4aac82"

circular-json@^0.3.1:
version "0.3.3"
resolved "https://registry.yarnpkg.com/circular-json/-/circular-json-0.3.3.tgz#815c99ea84f6809529d2f45791bdf82711352d66"
Expand Down Expand Up @@ -513,6 +532,12 @@ decamelize@^1.0.0, decamelize@^1.1.1:
version "1.2.0"
resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290"

deep-eql@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-3.0.1.tgz#dfc9404400ad1c8fe023e7da1df1c147c4b444df"
dependencies:
type-detect "^4.0.0"

deep-equal@~1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/deep-equal/-/deep-equal-1.0.1.tgz#f5d260292b660e084eff4cdbc9f08ad3247448b5"
Expand Down Expand Up @@ -913,6 +938,10 @@ get-caller-file@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.2.tgz#f702e63127e7e231c160a80c1554acb70d5047e5"

get-func-name@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/get-func-name/-/get-func-name-2.0.0.tgz#ead774abee72e20409433a066366023dd6887a41"

get-stream@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-3.0.0.tgz#8e943d1358dc37555054ecbe2edb05aa174ede14"
Expand Down Expand Up @@ -1902,6 +1931,10 @@ path-type@^2.0.0:
dependencies:
pify "^2.0.0"

pathval@^1.0.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/pathval/-/pathval-1.1.0.tgz#b942e6d4bde653005ef6b71361def8727d0645e0"

pify@^2.0.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c"
Expand Down Expand Up @@ -2439,6 +2472,10 @@ type-check@~0.3.2:
dependencies:
prelude-ls "~1.1.2"

type-detect@^4.0.0:
version "4.0.7"
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.7.tgz#862bd2cf6058ad92799ff5a5b8cf7b6cec726198"

type-is@^1.5.5, type-is@^1.6.14:
version "1.6.15"
resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.15.tgz#cab10fb4909e441c82842eafe1ad646c81804410"
Expand Down

0 comments on commit 4c78331

Please sign in to comment.