format_options.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict';
  2. const path = require('path');
  3. const mm = require('mm');
  4. const debug = require('debug')('mm');
  5. const utils = require('egg-utils');
  6. /**
  7. * format the options
  8. * @param {Objct} options - options
  9. * @return {Object} options
  10. */
  11. module.exports = function formatOptions(options) {
  12. const defaults = {
  13. baseDir: process.cwd(),
  14. cache: true,
  15. coverage: true,
  16. clean: true,
  17. };
  18. options = Object.assign({}, defaults, options);
  19. // relative path to test/fixtures
  20. // ```js
  21. // formatOptions({ baseDir: 'app' }); // baseDir => $PWD/test/fixtures/app
  22. // ```
  23. if (!path.isAbsolute(options.baseDir)) {
  24. options.baseDir = path.join(process.cwd(), 'test/fixtures', options.baseDir);
  25. }
  26. let framework = options.framework || options.customEgg;
  27. // test for framework
  28. if (framework === true) {
  29. framework = process.cwd();
  30. // diable plugin test when framwork test
  31. options.plugin = false;
  32. } else {
  33. // it will throw when framework is not found
  34. framework = utils.getFrameworkPath({ framework, baseDir: options.baseDir });
  35. }
  36. options.customEgg = options.framework = framework;
  37. const plugins = options.plugins = options.plugins || {};
  38. // add self as a plugin
  39. plugins['egg-mock'] = {
  40. enable: true,
  41. path: path.join(__dirname, '..'),
  42. };
  43. // test for plugin
  44. if (options.plugin !== false) {
  45. // add self to plugin list
  46. const pkgPath = path.join(process.cwd(), 'package.json');
  47. const pluginName = getPluginName(pkgPath);
  48. if (options.plugin && !pluginName) {
  49. throw new Error(`should set eggPlugin in ${pkgPath}`);
  50. }
  51. if (pluginName) {
  52. plugins[pluginName] = {
  53. enable: true,
  54. path: process.cwd(),
  55. };
  56. }
  57. }
  58. // mock HOME as baseDir, but ignore if it has been mocked
  59. const env = process.env.EGG_SERVER_ENV;
  60. if (!mm.isMocked(process.env, 'HOME') &&
  61. (env === 'default' || env === 'test' || env === 'prod')) {
  62. mm(process.env, 'HOME', options.baseDir);
  63. }
  64. // disable cache after call mm.env(),
  65. // otherwise it will use cache and won't load again.
  66. if (process.env.EGG_MOCK_SERVER_ENV) {
  67. options.cache = false;
  68. }
  69. debug('format options: %j', options);
  70. return options;
  71. };
  72. function getPluginName(pkgPath) {
  73. try {
  74. const pkg = require(pkgPath);
  75. if (pkg.eggPlugin && pkg.eggPlugin.name) {
  76. return pkg.eggPlugin.name;
  77. }
  78. } catch (_) {
  79. // ignore
  80. }
  81. }