Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow isolated refixturing #24

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 86 additions & 46 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,110 +11,145 @@ const debugSetup = DebugGenerator('loopback:component:fixtures:setup:verbose:')
const debugTeardown = DebugGenerator('loopback:component:fixtures:teardown:verbose:')

let models
let fixtures
let fixtureNames
let fixturePath
let cachedFixtures
let config

const loadFixture = (fixture, done) => {
debugSetup('Loading fixture', fixture)
const defaults = {
loadFixturesOnStartup: false,
errorOnSetupFailure: false,
environments: 'test',
fixturesPath: '/server/test-fixtures/'
}

const createFixtureList = () => {
const fixtureFolderContents = fs.readdirSync(fixturePath)
return fixtureFolderContents.filter(fileName => fileName.match(/\.json$/))
.map(fileName => fileName.replace('.json', ''))
}

const addToCache = (fixtureName) => {
const fixtureData = require(fixturePath + fixtureName)
cachedFixtures[fixtureName] = fixtureData
}

if (!cachedFixtures[fixture]) {
debugSetup('Fixture not cached loading from disk')
const fixtureData = require(fixturePath + fixture)
cachedFixtures[fixture] = fixtureData
const loadFixture = (fixtureName, done) => {
debugSetup('Loading fixture', fixtureName)

/* istanbul ignore else */
if (!cachedFixtures[fixtureName]) {
debugSetup('Fixture not cached, loading from disk')
addToCache(fixtureName)
}

const fixtureName = fixture.replace('.json', '')
debugSetup('Loading fixtures for', fixtureName)
models[fixtureName].create(cachedFixtures[fixture], (err) => {
models[fixtureName].create(cachedFixtures[fixtureName], (err) => {
if (err) {
debugSetup('Error when attempting to add fixtures for', fixture)
debugSetup('Error when attempting to add fixtures for', fixtureName)
debugSetup(err)
}

done(err)
})
}

const loadFixtures = (fixturesPath, cb) => {
const loadFixtures = (fixtures, cb) => {
/* istanbul ignore else */
if (!cachedFixtures) {
debugSetup('No cached fixtures loading fixture files from', fixturePath)
cachedFixtures = {}
fixturePath = path.join(appRoot, fixturesPath)
const fixtureFolderContents = fs.readdirSync(fixturePath)
fixtures = fixtureFolderContents.filter(fileName => fileName.match(/\.json$/))
fixtureNames = createFixtureList()
}

async.each(fixtures, loadFixture, cb)
if (!cb) {
cb = fixtures
async.each(fixtureNames, loadFixture, cb)
} else {
async.each(fixtures, loadFixture, cb)
}
}

const setupTestFixtures = (app, options) => {
options = merge({
loadFixturesOnStartup: false,
errorOnSetupFailure: false,
environments: 'test',
fixturesPath: '/server/test-fixtures/'
}, options)

debug('Loading fixtures with options', options)

const init = (app, options) => {
models = app.models
config = merge(defaults, options)
fixturePath = path.join(appRoot, config.fixturesPath)

debug('Initializing component with options', config)

const environment = app.settings && app.settings.env
? app.settings.env : process.env.NODE_ENV

const match = Array.isArray(options.environments)
? options.environments.indexOf(environment) !== -1
: environment === options.environments
const match = Array.isArray(config.environments)
? config.environments.indexOf(environment) !== -1
: environment === config.environments

if (!match) {
debug('Skipping fixtures because environment', environment, 'is not in options.environments')
return
}

if (options.loadFixturesOnStartup) {
loadFixtures(options.fixturesPath, (err) => {
if (config.loadFixturesOnStartup) {
loadFixtures((err) => {
if (err) debug('Error when loading fixtures on startup:', err)
if (err && options.errorOnSetupFailure) {
if (err && config.errorOnSetupFailure) {
throw new Error('Failed to load fixtures on startup:', err)
}
})
}
}

const Fixtures = app.model('Fixtures', {
const setupInterface = (app) => {
const Fixtures = app.registry.createModel({name: 'Fixtures', base: 'Model'})

app.model(Fixtures, {
dataSource: false,
base: 'Model'
})

Fixtures.setupFixtures = app.setupFixtures = (opts, cb) => {
/* istanbul ignore else */
if (!cb) cb = opts
Fixtures.setupFixtures = app.setupFixtures = (select, cb) => {
if (typeof select === 'function') cb = select
debug('Loading fixtures')
loadFixtures(options.fixturesPath, (errors) => {
const setupCallback = (errors) => {
if (errors) debug('Fixtures failed to load:', errors)
if (errors && options.errorOnSetupFailure) return cb(errors)
if (errors && config.errorOnSetupFailure) return cb(errors)

cb(null, 'setup complete')
})
}
if (typeof select !== 'string') {
debugSetup('Loading all fixtures in folder')
loadFixtures(setupCallback)
} else {
/* istanbul ignore else */
if (!Array.isArray(select)) select = select.split(',')
debugSetup('Loading following fixtures: ', select)
loadFixtures(select, setupCallback)
}
}

Fixtures.teardownFixtures = app.teardownFixtures = (opts, cb) => {
/* istanbul ignore else */
if (!cb) cb = opts
Fixtures.teardownFixtures = app.teardownFixtures = (select, cb) => {
if (typeof select === 'function') cb = select
let fixturesToTeardown
if (typeof select !== 'string') {
fixturesToTeardown = fixtureNames
} else {
/* istanbul ignore else */
if (!Array.isArray(select)) select = select.split(',')
fixturesToTeardown = select
}
debugTeardown('Tearing down fixtures for', Object.keys(app.datasources))
const dataSourceNames = Object.keys(app.datasources)
const migrateDataSource = (dataSourceName, done) => {
debugTeardown('Tearing down fixtures for', dataSourceName)
const dataSource = app.datasources[dataSourceName]

if (Array.isArray(fixtures)) {
if (Array.isArray(fixtureNames)) {
// build modelNames and modelNamesLower as a bit of hack to ensure we
// migrate the correct model name. its not possible to figure out
// which is the correct (lower or upper case) and automigrate doesn't
// do anything if the case is incorrect.
const modelNames = fixtures.map(fixture => fixture.replace('.json', ''))
const modelNamesLower = modelNames.map(modelName => modelName.toLowerCase())
const modelNamesBothCases = modelNames.concat(modelNamesLower)
const modelNamesLower = fixturesToTeardown.map(modelName => modelName.toLowerCase())
const modelNamesBothCases = fixturesToTeardown.concat(modelNamesLower)
const remigrateModel = (model, done) => {
debugTeardown('Dropping model', model, 'from', dataSourceName)
dataSource.automigrate(model, (err) => {
Expand Down Expand Up @@ -153,15 +188,20 @@ const setupTestFixtures = (app, options) => {

Fixtures.remoteMethod('setupFixtures', {
description: 'Setup fixtures',
accepts: {arg: 'select', type: 'string', http: { source: 'query' }},
returns: {arg: 'fixtures', type: 'string'},
http: {path: '/setup', verb: 'get'}
})

Fixtures.remoteMethod('teardownFixtures', {
description: 'Teardown fixtures',
accepts: {arg: 'select', type: 'string', http: { source: 'query' }},
returns: {arg: 'fixtures', type: 'string'},
http: {path: '/teardown', verb: 'get'}
})
}

module.exports = setupTestFixtures
module.exports = (app, options) => {
init(app, options)
setupInterface(app)
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@
"app-root-path": "^2.0.1",
"async": "^1.4.2",
"debug": "^2.2.0",
"loopback": "^2.22.2",
"loopback-datasource-juggler": "^2.41.0",
"merge": "^1.2.0"
},
"devDependencies": {
"chai": "^3.3.0",
"istanbul": "^0.4.4",
"loopback": "^2.22.2",
"loopback-datasource-juggler": "^2.41.0",
"mocha": "^2.3.3",
"supertest": "^1.1.0"
}
Expand Down
3 changes: 3 additions & 0 deletions test/test-fixtures-undefined/NoModel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[
{"name": "No Model", "description": "For testing what happens if there is no model for a fixture"}
]
4 changes: 4 additions & 0 deletions test/test-fixtures/Item2.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[
{"name": "First Item Name", "requiredStuff": "asdf", "description": "Describes the first item."},
{"name": "Second Item Name", "requiredStuff": "asdf", "description": "Describes the second item."}
]
Loading