added unit testing, and started implementing unit tests...phew

This commit is contained in:
Josh Burman
2019-03-12 22:28:02 -04:00
parent 74aad4a957
commit e8c2539f1b
3489 changed files with 464813 additions and 88 deletions

View File

@ -0,0 +1,153 @@
'use strict';
/*
* file-stress.test.js: Tests for stressing File transport: volume, ambient event loop lag.
*
* (C) 2016 Charlie Robbins
* MIT LICENSE
*
*/
const fs = require('fs');
const os = require('os');
const path = require('path');
const assume = require('assume');
const helpers = require('../helpers');
const split = require('split2');
const winston = require('../../lib/winston');
describe('File (stress)', function () {
this.timeout(30 * 1000);
const logPath = path.resolve(__dirname, '../fixtures/logs/file-stress-test.log');
beforeEach(function () {
try {
fs.unlinkSync(logPath);
} catch (ex) {
if (ex && ex.code !== 'ENOENT') { return done(ex); }
}
});
it('should handle a high volume of writes', function (done) {
const logger = winston.createLogger({
transports: [new winston.transports.File({
filename: logPath
})]
});
const counters = {
write: 0,
read: 0
};
const interval = setInterval(function () {
logger.info(++counters.write);
}, 0);
setTimeout(function () {
clearInterval(interval);
helpers.tryRead(logPath)
.on('error', function (err) {
assume(err).false();
logger.close();
done();
})
.pipe(split())
.on('data', function (d) {
const json = JSON.parse(d);
assume(json.level).equal('info');
assume(json.message).equal(++counters.read);
})
.on('end', function () {
assume(counters.write).equal(counters.read);
logger.close();
done();
});
}, 10000);
});
it('should handle a high volume of large writes', function (done) {
const logger = winston.createLogger({
transports: [new winston.transports.File({
filename: logPath
})]
});
const counters = {
write: 0,
read: 0
};
const interval = setInterval(function () {
const msg = {
counter: ++counters.write,
message: 'a'.repeat(16384 - os.EOL.length - 1)
};
logger.info(msg);
}, 0);
setTimeout(function () {
clearInterval(interval);
helpers.tryRead(logPath)
.on('error', function (err) {
assume(err).false();
logger.close();
done();
})
.pipe(split())
.on('data', function (d) {
const json = JSON.parse(d);
assume(json.level).equal('info');
assume(json.message).equal('a'.repeat(16384 - os.EOL.length - 1));
assume(json.counter).equal(++counters.read);
})
.on('end', function () {
assume(counters.write).equal(counters.read);
logger.close();
done();
});
}, 10000);
});
it('should handle a high volume of large writes synchronous', function (done) {
const logger = winston.createLogger({
transports: [new winston.transports.File({
filename: logPath
})]
});
const counters = {
write: 0,
read: 0
};
const msgs = new Array(10).fill().map(() => ({
counter: ++counters.write,
message: 'a'.repeat(16384 - os.EOL.length - 1)
}));
msgs.forEach(msg => logger.info(msg));
setTimeout(function () {
helpers.tryRead(logPath)
.on('error', function (err) {
assume(err).false();
logger.close();
done();
})
.pipe(split())
.on('data', function (d) {
const json = JSON.parse(d);
assume(json.level).equal('info');
assume(json.message).equal('a'.repeat(16384 - os.EOL.length - 1));
assume(json.counter).equal(++counters.read);
})
.on('end', function () {
assume(counters.write).equal(counters.read);
logger.close();
done();
});
}, 10000);
});
});

View File

@ -0,0 +1,121 @@
/*
* file-test.js: Tests for instances of the File transport
*
* (C) 2010 Charlie Robbins
* MIT LICENSE
*
*/
const rimraf = require('rimraf');
const fs = require('fs');
const path = require('path');
const assume = require('assume');
const winston = require('../../');
const MESSAGE = Symbol.for('message');
//
// Remove all log fixtures
//
function removeFixtures(done) {
rimraf(path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxsize*'), done);
}
describe('File (maxsize)', function () {
this.timeout(10000);
let testDone = false;
before(removeFixtures);
after(done => {
testDone = true;
removeFixtures(done);
});
it('should create multiple files correctly when passed more than the maxsize', function (done) {
const fillWith = ['a', 'b', 'c', 'd', 'e'];
const maxsizeTransport = new winston.transports.File({
level: 'info',
format: winston.format.printf(info => info.message),
filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxsize.log'),
maxsize: 4096
})
//
// Have to wait for `fs.stats` to be done in `maxsizeTransport.open()`.
// Otherwise the maxsizeTransport._dest is undefined. See https://github.com/winstonjs/winston/issues/1174
//
setTimeout(() => logKbytes(4), 100);
//
// Setup a list of files which we will later stat.
//
const files = [];
//
// Assets all the files have been created with the
// correct filesize
//
function assumeFilesCreated() {
files.map(function (file, i) {
let stats;
try {
stats = fs.statSync(file);
} catch (ex) {
assume(stats).is.an('object', `${file} failed to open: ${ex.message}`);
}
const text = fs.readFileSync(file, 'utf8');
assume(text[0]).equals(fillWith[i]);
// Either 4096 on Unix or 4100 on Windows
// because of the eol.
if (process.platform === 'win32') {
assume(stats.size).equals(4100);
} else {
assume(stats.size).equals(4096);
}
});
done();
}
//
// Log the specified kbytes to the transport
//
function logKbytes(kbytes) {
//
// Shift the next fill char off the array then push it back
// to rotate the chars.
//
const filler = fillWith.shift();
fillWith.push(filler);
//
//
// To not make each file not fail the assertion of the filesize we can
// make the array 1023 characters long.
//
const kbStr = Array(1023).fill(filler).join('');
//
// With printf format that displays the message only
// winston adds exactly 0 characters.
//
for (var i = 0; i < kbytes; i++) {
maxsizeTransport.log({ level: 'info', [MESSAGE]: kbStr });
}
}
maxsizeTransport.on('open', function (file) {
if (testDone) return; // ignore future notifications
const match = file.match(/(\d+)\.log$/);
const count = match ? match[1] : 0;
if (files.length === 5) {
return assumeFilesCreated();
}
files.push(file);
setImmediate(() => logKbytes(4));
});
});
});

188
node_modules/winston/test/transports/console.test.js generated vendored Normal file
View File

@ -0,0 +1,188 @@
'use strict';
/*
* console-test.js: Tests for instances of the Console transport
*
* (C) 2010 Charlie Robbins
* MIT LICENSE
*
*/
const path = require('path');
const assume = require('assume');
const { LEVEL, MESSAGE } = require('triple-beam');
const winston = require('../../lib/winston');
const helpers = require('../helpers');
const stdMocks = require('std-mocks');
const defaultLevels = winston.config.npm.levels;
const transports = {
defaults: new winston.transports.Console(),
noStderr: new winston.transports.Console({ stderrLevels: [] }),
stderrLevels: new winston.transports.Console({
stderrLevels: ['info', 'error']
}),
consoleWarnLevels: new winston.transports.Console({
consoleWarnLevels: ['warn', 'debug']
}),
eol: new winston.transports.Console({ eol: 'X' }),
syslog: new winston.transports.Console({
levels: winston.config.syslog.levels
}),
customLevelStderr: new winston.transports.Console({
levels: {
alpha: 0,
beta: 1,
gamma: 2,
delta: 3,
epsilon: 4,
},
stderrLevels: ['delta', 'epsilon']
})
};
/**
* Returns a function that asserts the `transport` has the specified
* logLevels values in the appropriate logLevelsName member.
*
* @param {TransportStream} transport Transport to assert against
* @param {Array} logLevels Set of levels assumed to exist for the specified map
* @param {String} logLevelsName The name of the array/map that holdes the log leveles values (ie: 'stderrLevels', 'consoleWarnLevels')
* @return {function} Assertion function to execute comparison
*/
function assertLogLevelsValues(transport, logLevels, logLevelsName = 'stderrLevels') {
return function () {
assume(JSON.stringify(Object.keys(transport[logLevelsName]).sort()))
.equals(JSON.stringify(logLevels.sort()));
};
}
describe('Console transport', function () {
describe('with defaults', function () {
it('logs all levels to stdout', function () {
stdMocks.use();
transports.defaults.levels = defaultLevels;
Object.keys(defaultLevels)
.forEach(function (level) {
const info = {
[LEVEL]: level,
message: `This is level ${level}`,
level
};
info[MESSAGE] = JSON.stringify(info);
transports.defaults.log(info);
});
stdMocks.restore();
var output = stdMocks.flush();
assume(output.stderr).is.an('array');
assume(output.stderr).length(0);
assume(output.stdout).is.an('array');
assume(output.stdout).length(7);
});
it("should set stderrLevels to [] by default", assertLogLevelsValues(
transports.defaults,
[],
'stderrLevels'
));
});
describe('throws an appropriate error when', function () {
it("if stderrLevels is set, but not an Array { stderrLevels: 'Not an Array' }", function () {
assume(function () {
let throwing = new winston.transports.Console({
stderrLevels: 'Not an Array'
})
}).throws(/Cannot make set from type other than Array of string elements/);
});
it("if stderrLevels contains non-string elements { stderrLevels: ['good', /^invalid$/, 'valid']", function () {
assume(function () {
let throwing = new winston.transports.Console({
stderrLevels: ['good', /^invalid$/, 'valid']
})
}).throws(/Cannot make set from type other than Array of string elements/);
});
});
it("{ stderrLevels: ['info', 'error'] } logs to them appropriately", assertLogLevelsValues(
transports.stderrLevels,
['info', 'error'],
'stderrLevels'
));
it("{ consoleWarnLevels: ['warn', 'debug'] } logs to them appropriately", assertLogLevelsValues(
transports.consoleWarnLevels,
['warn', 'debug'],
'consoleWarnLevels'
));
it('{ eol } adds a custom EOL delimiter', function (done) {
stdMocks.use();
transports.eol.log({ [MESSAGE]: 'info: testing. 1 2 3...' }, function () {
stdMocks.restore();
var output = stdMocks.flush(),
line = output.stdout[0];
assume(line).equal('info: testing. 1 2 3...X');
done();
});
});
});
require('abstract-winston-transport')({
name: 'Console',
Transport: winston.transports.Console
});
// vows.describe('winston/transports/console').addBatch({
// "An instance of the Console Transport": {
// "with syslog levels": {
// "should have the proper methods defined": function () {
// helpers.assertConsole(syslogTransport);
// },
// "the log() method": helpers.testSyslogLevels(syslogTransport, "should respond with true", function (ign, err, logged) {
// assert.isNull(err);
// assert.isTrue(logged);
// })
// }
// }
// }).addBatch({
// "An instance of the Console Transport with no options": {
// "should log only 'error' and 'debug' to stderr": helpers.testLoggingToStreams(
// winston.config.npm.levels, defaultTransport, ['debug', 'error'], stdMocks
// )
// }
// }).addBatch({
// "An instance of the Console Transport with debugStdout set": {
// "should set stderrLevels to 'error' by default": helpers.assertStderrLevels(
// debugStdoutTransport,
// ['error']
// ),
// "should log only the 'error' level to stderr": helpers.testLoggingToStreams(
// winston.config.npm.levels, debugStdoutTransport, ['error'], stdMocks
// )
// }
// }).addBatch({
// "An instance of the Console Transport with stderrLevels set": {
// "should log only the levels in stderrLevels to stderr": helpers.testLoggingToStreams(
// winston.config.npm.levels, stderrLevelsTransport, ['info', 'warn'], stdMocks
// )
// }
// }).addBatch({
// "An instance of the Console Transport with stderrLevels set to an empty array": {
// "should log only to stdout, and not to stderr": helpers.testLoggingToStreams(
// winston.config.npm.levels, noStderrTransport, [], stdMocks
// )
// }
// }).addBatch({
// "An instance of the Console Transport with custom levels and stderrLevels set": {
// "should log only the levels in stderrLevels to stderr": helpers.testLoggingToStreams(
// customLevels, customLevelsAndStderrTransport, ['delta', 'epsilon'], stdMocks
// )
// }
// }).export(module);

View File

@ -0,0 +1,93 @@
/*
* file-archive-test.js: Tests for instances of the File transport setting the archive option,
*
* (C) 2015 Nimrod Becker
* MIT LICENSE
*
*/
/* eslint-disable no-sync */
const assert = require('assert');
const rimraf = require('rimraf');
const fs = require('fs');
const path = require('path');
const winston = require('../../lib/winston');
const { MESSAGE } = require('triple-beam');
//
// Remove all log fixtures
//
function removeFixtures(done) {
rimraf(path.join(__dirname, '..', 'fixtures', 'logs', 'testarchive*'), done);
}
let archiveTransport = null;
describe('winston/transports/file/zippedArchive', function () {
describe('An instance of the File Transport with tailable true', function () {
before(removeFixtures);
after(removeFixtures);
it('init logger AFTER cleaning up old files', function () {
archiveTransport = new winston.transports.File({
timestamp: true,
json: false,
zippedArchive: true,
tailable: true,
filename: 'testarchive.log',
dirname: path.join(__dirname, '..', 'fixtures', 'logs'),
maxsize: 4096,
maxFiles: 3
});
});
it('when created archived files are rolled', function (done) {
let created = 0;
let loggedTotal = 0;
function data(ch, kb) {
return String.fromCharCode(65 + ch).repeat(kb * 1024 - 1);
}
function logKbytes(kbytes, txt) {
const toLog = {};
toLog[MESSAGE] = data(txt, kbytes);
archiveTransport.log(toLog);
}
archiveTransport.on('logged', function (info) {
loggedTotal += info[MESSAGE].length + 1;
if (loggedTotal >= 14 * 1024) { // just over 3 x 4kb files
return done();
}
if (loggedTotal % 4096 === 0) {
created++;
}
// eslint-disable-next-line max-nested-callbacks
setTimeout(() => logKbytes(1, created), 1);
});
logKbytes(1, created);
});
it('should be only 3 files called testarchive.log, testarchive1.log.gz and testarchive2.log.gz', function () {
for (var num = 0; num < 4; num++) {
const file = !num ? 'testarchive.log' : 'testarchive' + num + '.log.gz';
const fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file);
if (num === 3) {
return assert.throws(function () {
fs.statSync(fullpath);
}, Error);
}
assert.doesNotThrow(function () {
fs.statSync(fullpath);
}, Error);
}
});
});
});

View File

@ -0,0 +1,43 @@
'use strict';
const fs = require('fs');
const assert = require('assert');
const path = require('path');
const winston = require('../../lib/winston');
/* eslint-disable no-sync */
describe('winston/transports/file/createLogDir', function () {
const logDir = path.resolve(__dirname, '../fixtures/temp_logs');
beforeEach(function () {
fs.rmdirSync(logDir);
});
it('should create directory if it does not exist', function () {
winston.createLogger({
transports: [
new winston.transports.File({
filename: path.join(logDir, 'file.log')
})
]
});
assert(fs.existsSync(logDir));
});
it('should create directory if it does not exist when write to the stream', function () {
const streamfile = path.join(logDir, 'simple-stream.log');
const stream = fs.createWriteStream(streamfile);
winston.createLogger({
transports: [
new winston.transports.File({
stream: stream
})
]
});
assert(fs.existsSync(logDir));
});
});

View File

@ -0,0 +1,99 @@
/*
* file-maxfiles-test.js: Tests for instances of the File transport setting the max file size,
* and setting a number for max files created.
* maxSize * maxFiles = total storage used by winston.
*
* (C) 2011 Daniel Aristizabal
* MIT LICENSE
*
*/
var assert = require('assert'),
exec = require('child_process').exec,
fs = require('fs'),
path = require('path'),
vows = require('vows'),
winston = require('../../lib/winston'),
helpers = require('../helpers');
var maxfilesTransport = new winston.transports.File({
timestamp: false,
json: false,
filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles.log'),
maxsize: 4096,
maxFiles: 3
});
vows.describe('winston/transports/file/maxfiles').addBatch({
"An instance of the File Transport": {
"when passed a valid filename": {
topic: maxfilesTransport,
"should set the maxFiles option correctly": function (transportTest) {
assert.isNumber(transportTest.maxFiles);
}
},
"when delete old test files": {
topic: function () {
exec('rm -rf ' + path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles*'), this.callback);
},
"and when passed more files than the maxFiles": {
topic: function () {
var that = this,
created = 0;
function data(ch) {
return new Array(1018).join(String.fromCharCode(65 + ch));
};
function logKbytes(kbytes, txt) {
//
// With no timestamp and at the info level,
// winston adds exactly 7 characters:
// [info](4)[ :](2)[\n](1)
//
for (var i = 0; i < kbytes; i++) {
maxfilesTransport.log('info', data(txt), null, function () { });
}
}
maxfilesTransport.on('logged', function () {
if (++created === 6) {
return that.callback();
}
logKbytes(4, created);
});
logKbytes(4, created);
},
"should be only 3 files called 5.log, 4.log and 3.log": function () {
for (var num = 0; num < 6; num++) {
var file = !num ? 'testmaxfiles.log' : 'testmaxfiles' + num + '.log',
fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file);
// There should be no files with that name
if (num >= 0 && num < 3) {
assert.throws(function () {
fs.statSync(fullpath);
}, Error);
} else {
// The other files should be exist
assert.doesNotThrow(function () {
fs.statSync(fullpath);
}, Error);
}
}
},
"should have the correct content": function () {
['D', 'E', 'F'].forEach(function (name, inx) {
var counter = inx + 3,
logsDir = path.join(__dirname, '..', 'fixtures', 'logs'),
content = fs.readFileSync(path.join(logsDir, 'testmaxfiles' + counter + '.log'), 'utf-8');
// The content minus the 7 characters added by winston
assert.lengthOf(content.match(new RegExp(name, 'g')), 4068);
});
}
}
}
}
}).export(module);

View File

@ -0,0 +1,93 @@
/* eslint-disable no-sync */
const assert = require('assert');
const rimraf = require('rimraf');
const fs = require('fs');
const path = require('path');
const winston = require('../../lib/winston');
const { MESSAGE } = require('triple-beam');
//
// Remove all log fixtures
//
function removeFixtures(done) {
rimraf(path.join(__dirname, '..', 'fixtures', 'logs', 'testtailrollingfiles*'), done);
}
let tailrollTransport = null;
describe('winston/transports/file/tailrolling', function () {
describe('An instance of the File Transport', function () {
before(removeFixtures);
after(removeFixtures);
it('init logger AFTER cleaning up old files', function () {
tailrollTransport = new winston.transports.File({
timestamp: false,
json: false,
filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testtailrollingfiles.log'),
maxsize: 4096,
maxFiles: 3,
tailable: true
})
.on('open', console.log); // eslint-disable-line no-console
});
it('and when passed more files than the maxFiles', function (done) {
let created = 0;
let loggedTotal = 0;
function data(ch, kb) {
return String.fromCharCode(65 + ch).repeat(kb * 1024 - 1);
}
function logKbytes(kbytes, txt) {
const toLog = {};
toLog[MESSAGE] = data(txt, kbytes);
tailrollTransport.log(toLog);
}
tailrollTransport.on('logged', function (info) {
loggedTotal += info[MESSAGE].length + 1;
if (loggedTotal >= 14 * 1024) { // just over 3 x 4kb files
return done();
}
if (loggedTotal % 4096 === 0) {
created++;
}
// eslint-disable-next-line max-nested-callbacks
setTimeout(() => logKbytes(1, created), 1);
});
logKbytes(1, created);
});
it('should be 3 log files, base to maxFiles - 1', function () {
for (var num = 0; num < 4; num++) {
const file = !num ? 'testtailrollingfiles.log' : 'testtailrollingfiles' + num + '.log';
const fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file);
if (num === 3) {
return assert.ok(!fs.existsSync(fullpath));
}
assert.ok(fs.existsSync(fullpath));
}
return false;
});
it('should have files in correct order', function () {
['D', 'C', 'B'].forEach(function (letter, i) {
const file = !i ? 'testtailrollingfiles.log' : 'testtailrollingfiles' + i + '.log';
let content = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'logs', file), 'ascii');
content = content.replace(/\s+/g, '');
assert(content.match(new RegExp(letter, 'g'))[0].length, content.length);
});
});
});
});

122
node_modules/winston/test/transports/file.test.js generated vendored Normal file
View File

@ -0,0 +1,122 @@
'use strict';
const path = require('path');
const winston = require('../../');
const helpers = require('../helpers');
const fs = require('fs');
const { MESSAGE } = require('triple-beam');
const split = require('split2');
const assume = require('assume');
function noop() {};
describe('File({ filename })', function () {
this.timeout(10 * 1000);
it('should write to the file when logged to with expected object', function (done) {
var filename = path.join(__dirname, '..', 'fixtures', 'file', 'simple.log');
var transport = new winston.transports.File({
filename: filename
});
var info = { [MESSAGE]: 'this is my log message' };
var logged = 0;
var read = 0
function cleanup() {
fs.unlinkSync(filename);
}
transport.log(info, noop);
setImmediate(function () {
helpers.tryRead(filename)
.on('error', function (err) {
assume(err).false();
cleanup();
done();
})
.pipe(split())
.on('data', function (d) {
assume(++read).lte(logged);
assume(d).to.equal(info[MESSAGE]);
})
.on('end', function () {
cleanup();
done();
});
});
transport.once('logged', function () {
logged++;
});
});
//
// TODO: Rewrite these tests in mocha
//
// "Error object in metadata #610": {
// topic: function () {
// var myErr = new Error("foo");
//
// fileTransport.log('info', 'test message', myErr, this.callback.bind(this, null, myErr));
// },
// "should not be modified": function (err, myErr) {
// assert.equal(myErr.message, "foo");
// // Not sure if this is the best possible way to check if additional props appeared
// assert.deepEqual(Object.getOwnPropertyNames(myErr), Object.getOwnPropertyNames(new Error("foo")));
// }
// }
//
// "Date object in metadata": {
// topic: function () {
// var obj = new Date(1000);
// fileTransport.log('info', 'test message', obj, this.callback.bind(this, null, obj));
// },
// "should not be modified": function (err, obj) {
// // Not sure if this is the best possible way to check if additional props appeared
// assert.deepEqual(Object.getOwnPropertyNames(obj), Object.getOwnPropertyNames(new Date()));
// }
// }
//
// "Plain object in metadata": {
// topic: function () {
// var obj = { message: "foo" };
// fileTransport.log('info', 'test message', obj, this.callback.bind(this, null, obj));
// },
// "should not be modified": function (err, obj) {
// assert.deepEqual(obj, { message: "foo" });
// }
// }
//
// "An instance of the File Transport": require('./transport')(winston.transports.File, {
// filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testfile.log')
// })
});
describe('File({ stream })', function () {
it('should display the deprecation notice');
it('should write to the stream when logged to with expected object', function (done) {
var streamfile = path.join(__dirname, '..', 'fixtures', 'file', 'simple-stream.log');
var stream = fs.createWriteStream(streamfile);
var streamTransport = new winston.transports.File({
stream: stream
});
done();
//
// TODO: Flesh out these assertions
//
});
});
require('abstract-winston-transport')({
name: 'File',
Transport: winston.transports.File,
construct: {
filename: path.join(__dirname, '..', 'fixtures', 'file', 'abstract.log')
},
after(opts, done) {
const abstractFile = opts.construct.filename;
fs.unlink(abstractFile, done.bind(null, null));
}
});

77
node_modules/winston/test/transports/http.test.js generated vendored Normal file
View File

@ -0,0 +1,77 @@
/*
* http-test.js: Tests for instances of the HTTP transport
*
* MIT LICENSE
*/
var path = require('path'),
http = require('http'),
fs = require('fs'),
hock = require('hock'),
assume = require('assume'),
Http = require('../../lib/winston/transports/http'),
helpers = require('../helpers');
var host = '127.0.0.1';
function mockHttpServer(opts, done) {
if (!done && typeof opts === 'function') {
done = opts;
opts = {};
}
var mock = hock.createHock();
opts.path = opts.path || 'log';
opts.payload = opts.payload || {
level: 'info',
message: 'hello',
meta: {}
};
mock
.post('/' + opts.path, opts.payload)
.min(1)
.max(1)
.reply(200);
var server = http.createServer(mock.handler);
server.listen(0, '0.0.0.0', done);
return { server, mock };
}
describe('Http({ host, port, path })', function () {
var context;
var server;
beforeEach(function (done) {
context = mockHttpServer(done);
server = context.server;
});
it('should send logs over HTTP', function (done) {
var port = server.address().port;
var httpTransport = new Http({
host: host,
port: port,
path: 'log'
}).on('error', function (err) {
assume(err).falsy();
}).on('logged', function () {
context.mock.done(function (err) {
if (err) { assume(err).falsy(); }
done();
});
});
httpTransport.log({
level: 'info',
message: 'hello',
meta: {}
}, function (err) {
if (err) { assume(err).falsy(); }
});
});
afterEach(function (done) {
server.close(done.bind(null, null));
});
});

48
node_modules/winston/test/transports/stream.test.js generated vendored Normal file
View File

@ -0,0 +1,48 @@
'use strict';
const path = require('path');
const writeable = require('../helpers').writeable;
const { MESSAGE } = require('triple-beam');
const os = require('os');
const winston = require('../../');
const split = require('split2');
const assume = require('assume');
describe('Stream({ stream })', function () {
it('should support objectMode streams', function (done) {
const expected = {
level: 'info',
message: 'lolwut testing!'
};
const stream = writeable(function (info) {
assume(info).equals(expected);
done();
});
const transport = new winston.transports.Stream({ stream });
transport.log(expected);
});
it('should support UTF8 encoding streams', function (done) {
const expected = {
level: 'info',
message: 'lolwut testing!',
[MESSAGE]: 'info: lolwut testing!'
};
const stream = writeable(function (raw) {
assume(raw.toString()).equals(`${expected[MESSAGE]}${os.EOL}`);
done();
}, false);
const transport = new winston.transports.Stream({ stream });
transport.log(expected);
});
it('should throw when not passed a stream', function () {
assume(function () {
const stream = new winston.transports.Stream()
}).throws('options.stream is required.');''
});
});