refactor(Variables): Testing purpose variable resolution util

This commit is contained in:
Mariusz Nowak 2021-04-08 13:13:18 +02:00 committed by Mariusz Nowak
parent 1e352962a4
commit a2f1808b2f
2 changed files with 90 additions and 0 deletions

View File

@ -0,0 +1,53 @@
// Resolves all non instance dependent variables in a provided configuraton
// This util is not used in Serveless process flow, but is handy for side resolution of variables
'use strict';
const ensureString = require('type/string/ensure');
const ensurePlainObject = require('type/plain-object/ensure');
const resolveMeta = require('./resolve-meta');
const resolve = require('./resolve');
const sources = {
env: require('./sources/env'),
file: require('./sources/file'),
opt: require('./sources/opt'),
self: require('./sources/self'),
strToBool: require('./sources/str-to-bool'),
};
const reportEventualErrors = (variablesMeta) => {
const resolutionErrors = new Set(
Array.from(variablesMeta.values(), ({ error }) => error).filter(Boolean)
);
if (!resolutionErrors.size) return;
throw new Error(
`Variables resolution errored with:${Array.from(
resolutionErrors,
(error) => `\n - ${error.message}`
)}`,
'VARIABLES_RESOLUTION_ERROR'
);
};
module.exports = async ({ servicePath, configuration, options }) => {
servicePath = ensureString(servicePath);
ensurePlainObject(configuration);
options = ensurePlainObject(options, { default: {} });
const variablesMeta = resolveMeta(configuration);
reportEventualErrors(variablesMeta);
await resolve({
servicePath,
configuration,
variablesMeta,
sources,
options,
fulfilledSources: new Set(['env', 'file', 'opt', 'self', 'strToBool']),
});
reportEventualErrors(variablesMeta);
};

View File

@ -0,0 +1,37 @@
'use strict';
const { expect } = require('chai');
const fs = require('fs').promises;
const resolve = require('../../../../../lib/configuration/variables');
describe('test/unit/lib/configuration/variables/index.test.js', () => {
let configuration;
before(async () => {
process.env.ENV_SOURCE_TEST = 'foobar';
await fs.writeFile('foo.json', JSON.stringify({ json: 'content' }));
configuration = {
env: '${env:ENV_SOURCE_TEST}',
file: '${file(foo.json)}',
opt: '${opt:option}',
self: '${self:opt}',
strToBool: "${strToBool('false')}",
};
await resolve({
servicePath: process.cwd(),
configuration,
options: { option: 'bar' },
});
});
after(() => {
delete process.env.ENV_SOURCE_TEST;
});
it('should resolve "env" source', () => expect(configuration.env).to.equal('foobar'));
it('should resolve "file" source', () =>
expect(configuration.file).to.deep.equal({ json: 'content' }));
it('should resolve "opt" source', () => expect(configuration.opt).to.equal('bar'));
it('should resolve "self" source', () => expect(configuration.self).to.equal('bar'));
it('should resolve "strToBool" source', () => expect(configuration.strToBool).to.equal(false));
});