Skip to content

Commit

Permalink
Merge pull request #39 from steveukx/feature/tests-update
Browse files Browse the repository at this point in the history
Tests updated to use jest
  • Loading branch information
steveukx committed Dec 30, 2020
2 parents 9dc55e5 + a250c95 commit 79637cb
Show file tree
Hide file tree
Showing 13 changed files with 3,610 additions and 758 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
.idea/

coverage/
node_modules/
38 changes: 30 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,10 @@
}
],
"dependencies": {
"mkdirp": "~0.5.1"
"mkdirp": "^1.0.4"
},
"devDependencies": {
"@kwsites/file-exists": "^1.0.0",
"expect.js": "^0.3.1",
"mocha": "^6.1.4",
"rimraf": "^2.6.3",
"sinon": "^7.3.2"
"jest": "^26.6.3"
},
"keywords": [
"properties",
Expand All @@ -42,10 +38,36 @@
"scripts": {
"preversion": "npm test",
"postversion": "npm publish && git push && git push --tags",
"test": "mocha ./test/*.spec.js"
"test": "jest --coverage"
},
"engines": {
"node": ">=10"
},
"license": "MIT"
"license": "MIT",
"jest": {
"roots": [
"<rootDir>/src/",
"<rootDir>/test/"
],
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": 80
}
},
"coveragePathIgnorePatterns": [
"<rootDir>/test/"
],
"coverageReporters": [
"json",
"lcov",
"text",
"clover"
],
"testMatch": [
"**/test/**/*.spec.*"
]
}
}
18 changes: 10 additions & 8 deletions src/properties-reader.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const fs = require('fs');
const {readFileSync, statSync} = require('fs');
const propertyAppender = require('./property-appender').propertyAppender;
const propertyWriter = require('./property-writer').propertyWriter;

const SECTION = Symbol('SECTION');

function PropertiesReader (sourceFile, encoding, options = {}) {
this._encoding = typeof encoding === 'string' && encoding || 'utf-8';
this._properties = {};
Expand All @@ -16,7 +18,7 @@ function PropertiesReader (sourceFile, encoding, options = {}) {
* @type {String} The name of a section that should be prefixed on an property as it is added
* @ignore
*/
PropertiesReader.prototype._section = '';
PropertiesReader.prototype[SECTION] = '';

/**
* Gets the number of properties that have been read into this PropertiesReader.
Expand Down Expand Up @@ -93,7 +95,7 @@ PropertiesReader.prototype.writer = function (writer) {
PropertiesReader.prototype.append = function (sourceFile, encoding) {

if (sourceFile) {
this.read(fs.readFileSync(sourceFile, typeof encoding === 'string' && encoding || this._encoding));
this.read(readFileSync(sourceFile, typeof encoding === 'string' && encoding || this._encoding));
}

return this;
Expand All @@ -106,7 +108,7 @@ PropertiesReader.prototype.append = function (sourceFile, encoding) {
* @return {PropertiesReader} this instance
*/
PropertiesReader.prototype.read = function (input) {
delete this._section;
delete this[SECTION];
('' + input).split('\n').forEach(this._readLine, this);
return this;
};
Expand All @@ -121,10 +123,10 @@ PropertiesReader.prototype._readLine = function (propertyString) {
var property = !section && /^([^#=]+)(={0,1})(.*)$/.exec(propertyString);

if (section) {
this._section = section[1];
this[SECTION] = section[1];
}
else if (property) {
section = this._section ? this._section + '.' : '';
section = this[SECTION] ? this[SECTION] + '.' : '';
this.set(section + property[1].trim(), property[3].trim());
}
}
Expand Down Expand Up @@ -295,15 +297,15 @@ PropertiesReader.prototype.bindToExpress = function (app, basePath, makePaths) {

this.each(function (key, value) {
if (value && /\.(path|dir)$/.test(key)) {
value = Path.join(basePath, Path.relative(basePath, value));
value = Path.resolve(basePath, value);
this.set(key, value);

try {
var directoryPath = /dir$/.test(key) ? value : Path.dirname(value);
if (makePaths) {
require('mkdirp').sync(directoryPath);
}
else if (!fs.statSync(directoryPath).isDirectory()) {
else if (!statSync(directoryPath).isDirectory()) {
throw new Error("Path is not a directory that already exists");
}
}
Expand Down
41 changes: 41 additions & 0 deletions test/__fixtues__/create-test-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const {join} = require('path');
const {realpathSync} = require('fs');
const {io} = require('./io');

module.exports.createTestContext = async function createTestContext () {
const root = await io.mkdtemp();

const context = {
path (...segments) {
return join(root, ...segments);
},
async dir (...paths) {
if (!paths.length) {
return root;
}

return await io.mkdir(context.path(...paths));
},
async file (path, content = `File content ${ path }`) {
if (Array.isArray(path)) {
await context.dir(path[0]);
}

const pathArray = Array.isArray(path) ? path : [path];
return await io.writeFile(context.path(...pathArray), content);
},
async files (...paths) {
for (const path of paths) {
await context.file(path);
}
},
get root () {
return root;
},
get rootResolvedPath () {
return realpathSync(root);
},
};

return context;
}
42 changes: 42 additions & 0 deletions test/__fixtues__/io.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const {existsSync, mkdir, mkdtemp, readFile, statSync, writeFile} = require('fs');

module.exports.io = {
isdir (path) {
try {
return statSync(path).isDirectory();
}
catch (e) {
return false;
}
},
mkdir (path) {
return new Promise((done, fail) => {
if (existsSync(path)) {
return done(path);
}

mkdir(path, (err) => err ? fail(err) : done(path));
});
},
mkdtemp () {
return new Promise((done, fail) => {
mkdtemp((process.env.TMPDIR || '/tmp/') + 'properties-reader-test-', (err, path) => {
err ? fail(err) : done(path);
});
});
},
readFile (path, encoding = 'utf-8') {
return new Promise((done, fail) => {
readFile(path, encoding, (err, data) => {
err ? fail(err) : done(data);
})
});
},
writeFile (path, content, encoding = 'utf-8') {
return new Promise((done, fail) => {
writeFile(path, content, encoding, (err) => {
err ? fail(err) : done(path);
})
});
},
};
80 changes: 51 additions & 29 deletions test/bind-to-server.spec.js
Original file line number Diff line number Diff line change
@@ -1,54 +1,76 @@
const expect = require('expect.js');
const {spy} = require('sinon');
const {createTestContext} = require('./__fixtues__/create-test-context');
const {io} = require('./__fixtues__/io');

describe('bind-to-server', () => {

let properties;
const propertiesReader = require('../');

const tempFile = require('./utils/temporary-file');
const {givenFilePropertiesReader} = require('./utils/bdd');
describe('bind-to-server', () => {

function givenTheProperties (content) {
return properties = givenFilePropertiesReader(content);
}
let context;
let app;

beforeEach(() => {
beforeEach(async () => {
context = await createTestContext();
app = {
set: jest.fn(),
};
});
afterEach(() => jest.restoreAllMocks());

afterEach(() => tempFile.tearDown());
it('Creates directories when necessary - absolute paths', async () => {
const dirPath = context.path('foo');
const file = `
some.property.dir = ${ dirPath }
foo.bar = A Value
`;

it('Creates directories when necessary - absolute paths', () => {
const dirPath = tempFile.pushDir('/tmp/' + Math.floor(Math.random() * 1e10).toString(16));
const app = {set: spy()};
propertiesReader(await context.file('properties.ini', file))
.bindToExpress(app, null, true);

givenTheProperties(`
expect(io.isdir(dirPath)).toBe(true);
});

it('Does not create directories when already present', async () => {
const dirPath = await context.dir('foo');
const file = `
some.property.dir = ${ dirPath }
foo.bar = A Value
`;

`).bindToExpress(app, null, true);
propertiesReader(await context.file('properties.ini', file))
.bindToExpress(app, null, true);

expect(require('fs').statSync(dirPath).isDirectory()).to.be.ok();
expect(io.isdir(dirPath)).toBe(true);
});

it('Creates directories when necessary - relative paths', () => {
const dirName = Math.floor(Math.random() * 1e10).toString(16);
const dirBase = process.cwd();
const dirPath = tempFile.pushDir(dirBase + '/' + dirName);
const app = {set: spy()};

givenTheProperties(`
it('Creates directories when necessary - relative paths', async () => {
jest.spyOn(process, 'cwd').mockReturnValue(context.root);

const dirName = 'bar';
const dirPath = context.path(dirName);
const file = `
some.property.dir = ${ dirName }
foo.bar = A Value
`;

`).bindToExpress(app, dirBase, true);
propertiesReader(await context.file('properties.ini', file))
.bindToExpress(app, null, true);

expect(require('fs').statSync(dirPath).isDirectory()).to.be.ok();
expect(io.isdir(dirPath)).toBe(true);
});

it('Creates directories when necessary - relative path to explicit working directory', async () => {
const dirName = 'bar';
const dirPath = context.path(dirName);
const file = `
some.property.dir = ${ dirName }
foo.bar = A Value
`;

propertiesReader(await context.file('properties.ini', file))
.bindToExpress(app, context.root, true);

expect(io.isdir(dirPath)).toBe(true);
});

});

Loading

0 comments on commit 79637cb

Please sign in to comment.