UNPKG

3.41 kBJavaScriptView Raw
1/*
2 * file-maxfiles-test.js: Tests for instances of the File transport setting the max file size,
3 * and setting a number for max files created.
4 * maxSize * maxFiles = total storage used by winston.
5 *
6 * (C) 2011 Daniel Aristizabal
7 * MIT LICENSE
8 *
9 */
10
11var assert = require('assert'),
12 exec = require('child_process').exec,
13 fs = require('fs'),
14 path = require('path'),
15 vows = require('vows'),
16 winston = require('../../lib/winston'),
17 helpers = require('../helpers');
18
19var maxfilesTransport = new winston.transports.File({
20 timestamp: false,
21 json: false,
22 filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles.log'),
23 maxsize: 4096,
24 maxFiles: 3
25});
26
27vows.describe('winston/transports/file/maxfiles').addBatch({
28 "An instance of the File Transport": {
29 "when passed a valid filename": {
30 topic: maxfilesTransport,
31 "should be a valid transporter": function (transportTest) {
32 helpers.assertFile(transportTest);
33 },
34 "should set the maxFiles option correctly": function (transportTest) {
35 assert.isNumber(transportTest.maxFiles);
36 }
37 },
38 "when delete old test files": {
39 topic: function () {
40 exec('rm -rf ' + path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles*'), this.callback);
41 },
42 "and when passed more files than the maxFiles": {
43 topic: function () {
44 var that = this,
45 created = 0;
46
47 function data(ch) {
48 return new Array(1018).join(String.fromCharCode(65 + ch));
49 };
50
51 function logKbytes(kbytes, txt) {
52 //
53 // With no timestamp and at the info level,
54 // winston adds exactly 7 characters:
55 // [info](4)[ :](2)[\n](1)
56 //
57 for (var i = 0; i < kbytes; i++) {
58 maxfilesTransport.log('info', data(txt), null, function () { });
59 }
60 }
61
62 maxfilesTransport.on('logged', function () {
63 if (++created === 6) {
64 return that.callback();
65 }
66
67 logKbytes(4, created);
68 });
69
70 logKbytes(4, created);
71 },
72 "should be only 3 files called 5.log, 4.log and 3.log": function () {
73 for (var num = 0; num < 6; num++) {
74 var file = !num ? 'testmaxfiles.log' : 'testmaxfiles' + num + '.log',
75 fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file);
76
77 // There should be no files with that name
78 if (num >= 0 && num < 3) {
79 assert.throws(function () {
80 fs.statSync(fullpath);
81 }, Error);
82 } else {
83 // The other files should be exist
84 assert.doesNotThrow(function () {
85 fs.statSync(fullpath);
86 }, Error);
87 }
88 }
89 },
90 "should have the correct content": function () {
91 ['D', 'E', 'F'].forEach(function (name, inx) {
92 var counter = inx + 3,
93 logsDir = path.join(__dirname, '..', 'fixtures', 'logs'),
94 content = fs.readFileSync(path.join(logsDir, 'testmaxfiles' + counter + '.log'), 'utf-8');
95 // The content minus the 7 characters added by winston
96 assert.lengthOf(content.match(new RegExp(name, 'g')), 4068);
97 });
98 }
99 }
100 }
101 }
102}).export(module);