Skip to content

Commit

Permalink
Add tests for Seeder
Browse files Browse the repository at this point in the history
- Fix incorrect handling of extension configuration property in knexfile
- Make this handling consistent between MigrationGenerator and Seeder
  • Loading branch information
lorefnon committed Oct 12, 2019
1 parent 181b139 commit 80fa2bf
Show file tree
Hide file tree
Showing 13 changed files with 471 additions and 38 deletions.
23 changes: 15 additions & 8 deletions bin/cli.js
Expand Up @@ -18,9 +18,10 @@ const {
success,
checkLocalModule,
getMigrationExtension,
getSeedExtension,
getStubPath,
} = require('./utils/cli-config-utils');
const { DEFAULT_EXT } = require('./utils/constants');

const { listMigrations } = require('./utils/migrationsLister');

function initKnex(env, opts) {
Expand Down Expand Up @@ -157,7 +158,7 @@ function invoke(env) {
const ext = getMigrationExtension(env, opts);
const configOverrides = { extension: ext };

const stub = getStubPath(env, opts);
const stub = getStubPath('migrations', env, opts);
if (stub) {
configOverrides.stub = stub;
}
Expand Down Expand Up @@ -292,17 +293,23 @@ function invoke(env) {
`-x [${filetypes.join('|')}]`,
'Specify the stub extension (default js)'
)
.option(
`--stub [<relative/path/from/knexfile>|<name>]`,
'Specify the seed stub to use. If using <name> the file must be located in config.seeds.directory'
)
.action((name) => {
const opts = commander.opts();
opts.client = opts.client || 'sqlite3'; // We don't really care about client when creating seeds
const instance = initKnex(env, opts);
const ext = (
argv.x ||
env.configuration.ext ||
DEFAULT_EXT
).toLowerCase();
const ext = getSeedExtension(env, opts);
const configOverrides = { extension: ext };
const stub = getStubPath('seeds', env, opts);
if (stub) {
configOverrides.stub = stub;
}

pending = instance.seed
.make(name, { extension: ext })
.make(name, configOverrides)
.then((name) => {
success(color.green(`Created seed file: ${name}`));
})
Expand Down
23 changes: 19 additions & 4 deletions bin/utils/cli-config-utils.js
Expand Up @@ -119,9 +119,23 @@ function getMigrationExtension(env, opts) {
return ext.toLowerCase();
}

function getStubPath(env, opts) {
function getSeedExtension(env, opts) {
const config = resolveEnvironmentConfig(opts, env.configuration);
const stubDirectory = config.migrations && config.migrations.directory;

let ext = DEFAULT_EXT;
if (argv.x) {
ext = argv.x;
} else if (config.seeds && config.seeds.extension) {
ext = config.seeds.extension;
} else if (config.ext) {
ext = config.ext;
}
return ext.toLowerCase();
}

function getStubPath(configKey, env, opts) {
const config = resolveEnvironmentConfig(opts, env.configuration);
const stubDirectory = config[configKey] && config[configKey].directory;

const { stub } = argv;
if (!stub) {
Expand All @@ -131,10 +145,10 @@ function getStubPath(env, opts) {
return stub;
}

// using stub <name> must have config.migrations.directory defined
// using stub <name> must have config[configKey].directory defined
if (!stubDirectory) {
console.log(color.red('Failed to load stub'), color.magenta(stub));
exit('config.migrations.directory in knexfile must be defined');
exit(`config.${configKey}.directory in knexfile must be defined`);
}

return path.join(stubDirectory, stub);
Expand All @@ -147,6 +161,7 @@ module.exports = {
exit,
success,
checkLocalModule,
getSeedExtension,
getMigrationExtension,
getStubPath,
};
22 changes: 12 additions & 10 deletions lib/migrate/MigrationGenerator.js
@@ -1,7 +1,7 @@
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const bluebird = require('bluebird');
const {promisify} = require('util');
const { writeJsFileUsingTemplate } = require('../util/template');
const { getMergedConfig } = require('./configuration-merger');

Expand All @@ -18,8 +18,9 @@ class MigrationGenerator {
new Error('A name must be specified for the generated migration')
);
}
await this._ensureFolder(config);
await this._writeNewMigration(name, config);
await this._ensureFolder();
const createdMigrationFilePath = await this._writeNewMigration(name);
return createdMigrationFilePath;
}

// Ensures a folder for the migrations exist, dependent on the migration
Expand All @@ -28,9 +29,8 @@ class MigrationGenerator {
const dirs = this._absoluteConfigDirs();

const promises = dirs.map((dir) => {
return bluebird
.promisify(fs.stat, { context: fs })(dir)
.catch(() => bluebird.promisify(mkdirp)(dir));
return promisify(fs.stat, { context: fs })(dir)
.catch(() => promisify(mkdirp)(dir));
});

return Promise.all(promises);
Expand All @@ -55,13 +55,15 @@ class MigrationGenerator {

// Write a new migration to disk, using the config and generated filename,
// passing any `variables` given in the config to the template.
_writeNewMigration(name, config) {
return writeJsFileUsingTemplate(
this._getNewMigrationPath(name),
async _writeNewMigration(name) {
const migrationPath = this._getNewMigrationPath(name);
await writeJsFileUsingTemplate(
migrationPath,
this._getStubPath(),
{ variable: 'd' },
config.variables || {}
this.config.variables || {}
);
return migrationPath;
}

_absoluteConfigDirs() {
Expand Down
11 changes: 7 additions & 4 deletions lib/seed/Seeder.js
Expand Up @@ -42,7 +42,8 @@ class Seeder {
if (!name)
throw new Error('A name must be specified for the generated seed');
await this._ensureFolder(config);
await this._writeNewSeed(name);
const seedPath = await this._writeNewSeed(name);
return seedPath;
}

// Lists all available seed files as a sorted array.
Expand Down Expand Up @@ -121,13 +122,15 @@ class Seeder {

// Write a new seed to disk, using the config and generated filename,
// passing any `variables` given in the config to the template.
_writeNewSeed(name) {
return writeJsFileUsingTemplate(
this._getNewStubFilePath(name),
async _writeNewSeed(name) {
const seedPath = this._getNewStubFilePath(name);
await writeJsFileUsingTemplate(
seedPath,
this._getStubPath(),
{ variable: 'd' },
this.config.variables || {}
);
return seedPath;
}

// Runs a batch of seed files.
Expand Down
36 changes: 31 additions & 5 deletions test/cli/cli-test-utils.js
Expand Up @@ -29,15 +29,40 @@ function migrationStubOptionSetup(fileHelper) {
return { migrationGlobPath };
}

function expectMigrationMatchesStub(stubPath, migrationGlobPath, fileHelper) {
function seedStubOptionSetup(fileHelper) {
const seedGlobPath = 'test/jake-util/knexfile_seeds/*.js';

fileHelper.registerGlobForCleanup(seedGlobPath);
fileHelper.createFile(
process.cwd() + '/knexfile.js',
`
module.exports = {
development: {
client: 'sqlite3',
connection: {
filename: __dirname + '/test/jake-util/test.sqlite3',
},
seeds: {
directory: __dirname + '/test/jake-util/knexfile_seeds',
},
}
};
`,
{ isPathAbsolute: true }
);

return { seedGlobPath };
}

function expectContentMatchesStub(stubPath, globPath, fileHelper) {
// accepts full or relative stub path
const relativeStubPath = stubPath.replace('test/jake-util/', '');
const stubContent = fileHelper.getFileTextContent(relativeStubPath);
const [migrationContent] = fileHelper.getFileGlobTextContent(
migrationGlobPath
const [content] = fileHelper.getFileGlobTextContent(
globPath
);

expect(migrationContent).equals(stubContent);
expect(content).equals(stubContent);
}

function setupFileHelper() {
Expand All @@ -51,7 +76,8 @@ function setupFileHelper() {
}

module.exports = {
expectMigrationMatchesStub,
expectContentMatchesStub,
migrationStubOptionSetup,
seedStubOptionSetup,
setupFileHelper,
};
8 changes: 4 additions & 4 deletions test/cli/migrate-make.spec.js
Expand Up @@ -7,7 +7,7 @@ const { expect } = require('chai');
const KNEX = path.normalize(__dirname + '/../../bin/cli.js');
const {
migrationStubOptionSetup,
expectMigrationMatchesStub,
expectContentMatchesStub,
setupFileHelper,
} = require('./cli-test-utils');

Expand Down Expand Up @@ -252,7 +252,7 @@ development: {
'test/jake-util/knexfile_migrations/*_somename.js'
);
expect(fileCount).to.equal(1);
expectMigrationMatchesStub(stubPath, migrationGlobPath, fileHelper);
expectContentMatchesStub(stubPath, migrationGlobPath, fileHelper);
});

it('Create a new migration with stub parameter in knexfile', async () => {
Expand All @@ -273,7 +273,7 @@ development: {
const stubName = 'table.stub';
const stubPath = `test/jake-util/knexfile-stubs/${stubName}`;
expect(fileCount).to.equal(1);
expectMigrationMatchesStub(stubPath, migrationGlobPath, fileHelper);
expectContentMatchesStub(stubPath, migrationGlobPath, fileHelper);
});

it('Create a new migration with --stub <name> in config.migrations.directory', async () => {
Expand All @@ -293,7 +293,7 @@ development: {
'test/jake-util/knexfile_migrations/*_somename.js'
);
expect(fileCount).to.equal(1);
expectMigrationMatchesStub(stubPath, migrationGlobPath, fileHelper);
expectContentMatchesStub(stubPath, migrationGlobPath, fileHelper);
});

it('Create a new migration with --stub <name> when file does not exist', async () => {
Expand Down

0 comments on commit 80fa2bf

Please sign in to comment.