Skip to content

Commit

Permalink
1.5.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikhail.Angelov committed Nov 30, 2019
1 parent 1163567 commit 06d131f
Show file tree
Hide file tree
Showing 8 changed files with 327 additions and 382 deletions.
12 changes: 8 additions & 4 deletions examples/app/service.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
const mongoose = require('mongoose')
const mongoUrl = process.env.MONGO_URL || 'mongodb://localhost:27017/example'
mongoose.connect(mongoUrl)
const TaskSchema = new mongoose.Schema({

let client
mongoose.connect(mongoUrl).then(c => {
client = c
})
const Task = mongoose.model('tasks', {
name: String,
started: Date,
completed: Boolean,
})
const Task = mongoose.model('tasks', TaskSchema)

module.exports = {
getTasks: () => Task.find(),
addTask: data => new Task(data).save(),
deleteTask: taskId => Task.findByIdAndRemove(taskId)
deleteTask: taskId => Task.findOneAndDelete({ _id: taskId }),
getClient: () => client,
}
8 changes: 0 additions & 8 deletions examples/it_helper.js

This file was deleted.

4 changes: 2 additions & 2 deletions examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "basic.js",
"scripts": {
"test": "mocha --require ./it_helper.js --recursive ./*.it.js",
"test": "mocha ./test.it.js --delay",
"e2e": "node e2e-runner.js",
"start": "node ./app"
},
Expand All @@ -19,7 +19,7 @@
"devDependencies": {
"chai": "^4.1.2",
"co": "^4.6.0",
"hermione": "^0.58.0",
"mocha": "^6.2.2",
"mocha-prepare": "^0.1.0",
"selenium-standalone": "^6.12.0"
}
Expand Down
19 changes: 16 additions & 3 deletions examples/test.it.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
const expect = require('chai').expect
const mongoose = require('mongoose')
const mongoUnit = require('../index')
const service = require('./app/service')
const testMongoUrl = process.env.MONGO_URL
const testData = require('./fixtures/testData.json')

let service
mongoUnit.start({dbName:'example'}).then(() => {
run() // this line start mocha tests
})

after(async () => {
const client = service.getClient()
await client.disconnect()
await mongoUnit.stop()
})

describe('service', () => {
const testData = require('./fixtures/testData.json')
before(() =>{
// create it after DB is started
service = require('./app/service')
})
beforeEach(() => mongoUnit.initDb(testMongoUrl, testData))
afterEach(() => mongoUnit.drop())

Expand Down
156 changes: 78 additions & 78 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';
'use strict'
const Debug = require('debug')
const portfinder = require('portfinder')
const client = require('mongodb').MongoClient
const MongoClient = require('mongodb').MongoClient
const fs = require('fs')
const ps = require('ps-node')
const debug = Debug('mongo-unit')
Expand All @@ -16,28 +16,32 @@ const defaultMongoOpts = {
}

var mongodHelper
var dbUrl
var dbUrl = null
var client
var dbName

function runMogo(opts, port) {
const MongodHelper = require('mongodb-prebuilt').MongodHelper
opts.port = port
mongodHelper = new MongodHelper([
'--port', port,
'--dbpath', opts.dbpath,
'--storageEngine', 'ephemeralForTest'
], {
mongodHelper = new MongodHelper(['--port', port, '--dbpath', opts.dbpath, '--storageEngine', 'ephemeralForTest'], {
version: opts.version,
});
return mongodHelper.run()
})
return mongodHelper
.run()
.then(() => {
dbUrl = 'mongodb://localhost:' + port + '/' + opts.dbName
dbName = opts.dbName
dbUrl = 'mongodb://localhost:' + port + '/' + dbName
debug(`mongo is started on ${dbUrl}`)
return dbUrl
})
.then(url => MongoClient.connect(url))
.then(dbClient => {
client = dbClient
})
}

function start(opts) {
const mongo_opts = Object.assign(defaultMongoOpts, (opts || {}))
const mongo_opts = Object.assign(defaultMongoOpts, opts || {})
if (mongo_opts.verbose) {
Debug.enable('mongo-unit')
Debug.enable('*')
Expand All @@ -56,9 +60,11 @@ function delay(time) {
return new Promise(resolve => setTimeout(resolve, time))
}
function stop() {
mongodHelper && mongodHelper.mongoBin.childProcess.kill()
dbUrl = null;
return delay(100) //this is small delay to make sure kill signal is sent
return client.close(true).then(() => {
mongodHelper && mongodHelper.mongoBin.childProcess.kill()
dbUrl = null
return delay(100) //this is small delay to make sure kill signal is sent
})
}

function getUrl() {
Expand All @@ -70,99 +76,93 @@ function getUrl() {
}

function load(data) {
return client.connect(getUrl())
.then(db => {
const queries = Object.keys(data).map(col => {
const collection = db.collection(col)
return collection.insert(data[col])
})
return Promise.all(queries).then(() => db.close())
})
const db = client.db(dbName)
const queries = Object.keys(data).map(col => {
const collection = db.collection(col)
return collection.insertMany(data[col])
})
return Promise.all(queries)
}

function clean(data) {
return client.connect(getUrl())
.then(db => {
const queries = Object.keys(data).map(col => {
const collection = db.collection(col)
return collection.drop()
})
return Promise.all(queries).then(() => db.close())
})
const db = client.db(dbName)
const queries = Object.keys(data).map(col => {
const collection = db.collection(col)
return collection.drop()
})
return Promise.all(queries)
}

function drop() {
return client.connect(getUrl())
.then(db => db.dropDatabase().then(() => db.close()))
return client.db(dbName).dropDatabase()
}

function getFreePort(possiblePort) {
portfinder.basePort = possiblePort
return new Promise((resolve, reject) => portfinder.getPort((err, port) => {
if (err) {
debug(`cannot get free port: ${err}`)
reject(err)
} else {
resolve(port)
}
}))
return new Promise((resolve, reject) =>
portfinder.getPort((err, port) => {
if (err) {
debug(`cannot get free port: ${err}`)
reject(err)
} else {
resolve(port)
}
})
)
}

function makeSureTempDirExist(dir) {
try {
fs.mkdirSync(dir);
fs.mkdirSync(dir)
} catch (e) {
if (e.code !== "EEXIST") {
if (e.code !== 'EEXIST') {
console.log('cannot create db folder', dir, e)
throw e;
throw e
}
}
}

function makeSureOtherMongoProcessesKilled(dataFolder) {
return new Promise((resolve, reject) => {
ps.lookup({
psargs: ['-A'],
command: 'mongod',
arguments: dataFolder
}, (err, resultList) => {
if (err) {
console.log('ps-node error', err)
return reject(err)
}

resultList.forEach(process => {
if (process) {
console.log('KILL PID: %s, COMMAND: %s, ARGUMENTS: %s', process.pid, process.command, process.arguments)
ps.kill(process.pid)
ps.lookup(
{
psargs: ['-A'],
command: 'mongod',
arguments: dataFolder,
},
(err, resultList) => {
if (err) {
console.log('ps-node error', err)
return reject(err)
}
});
return resolve()
})

resultList.forEach(process => {
if (process) {
console.log('KILL PID: %s, COMMAND: %s, ARGUMENTS: %s', process.pid, process.command, process.arguments)
ps.kill(process.pid)
}
})
return resolve()
}
)
})
}

function initDb(url, data) {
return client.connect(url)
.then(db => {
const requests = Object.keys(data).map(col => {
const collection = db.collection(col)
return collection.insert(data[col])
})
return Promise.all(requests).then(() => db.close())
})
const db = client.db(dbName)
const requests = Object.keys(data).map(col => {
const collection = db.collection(col)
return collection.insertMany(data[col])
})
return Promise.all(requests)
}

function dropDb(url) {
return client.connect(url)
.then(db => {
return db.collections()
.then(collections => {
const requests = collections.map(col => col.drop())
return Promise.all(requests)
})
.then(() => db.close())
})
const db = client.db(dbName)
return db.collections().then(collections => {
const requests = collections.map(col => col.drop())
return Promise.all(requests)
})
}

module.exports = {
Expand Down
Loading

0 comments on commit 06d131f

Please sign in to comment.