Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nathanoehlman committed Oct 31, 2012
1 parent f02bc8f commit 65c8297
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
@@ -1,4 +1,4 @@
mockstream
==========

Mock stream is a really simply utility stream for generating data for test streams
Mockstream is a very simple utility library for testing streams.
61 changes: 61 additions & 0 deletions mockstream.js
@@ -0,0 +1,61 @@
var stream = require('stream'),
util = require('util');

/**
The MockDataStream merely emits blocks of data in chunks of a given size
up until a stream length is reached
**/
function MockDataStream(opts) {
opts = opts || {};
this.chunkSize = opts.chunkSize || 1024; // Default 1K chunk size
this.streamLength = opts.streamLength || 1048576; // Default 1MB stream length
this.written = 0;
this.paused = false;
}
util.inherits(MockDataStream, stream);

/**
Starts pumping on mock data
**/
MockDataStream.prototype.start = function() {
process.nextTick(this._writeData.bind(this));
return this;
}

/**
Pause the stream
**/
MockDataStream.prototype.pause = function() {
this.paused = true;
}

/**
Resume the stream
**/
MockDataStream.prototype.resume = function() {
this.start();
}

MockDataStream.prototype._writeData = function() {

if (this.paused) return;

var remainder = this.streamLength - this.written,
dataLength = (remainder > this.chunkSize ? this.chunkSize : remainder),
data = new Array(dataLength + 1).join("0"),
buf = new Buffer(data);

this.emit('data', buf);

this.written += dataLength;

if (this.written >= this.streamLength) {
this.emit('end');
} else {
process.nextTick(this._writeData.bind(this));
}
}

module.exports = {
MockDataStream: MockDataStream
}
18 changes: 18 additions & 0 deletions package.json
@@ -0,0 +1,18 @@
{
"name": "mockstream",
"version": "0.0.0",
"description": "A very simple test library for working with streams",
"main": "mockstream.js",
"scripts": {
"test": "mocha"
},
"repository": {
"type": "git",
"url": "git://github.com/nathanoehlman/mockstream.git"
},
"author": "Nathan Oehlman",
"license": "BSD",
"devDependencies": {
"mocha": "~1.6.0"
}
}
25 changes: 25 additions & 0 deletions test/mockstream.js
@@ -0,0 +1,25 @@
var assert = require('assert'),
mockstream = require('..');

describe('Mock data stream', function() {

it('should emit mock data', function(done) {
var chunkSize = 1024,
streamLength = 2048,
stream = new mockstream.MockDataStream({
chunkSize: chunkSize,
streamLength: streamLength
}),
read = 0;

stream
.start()
.on('data', function(data) {
read += data.length;
})
.on('end', function() {
assert.equal(streamLength, read);
done();
});
});
});

0 comments on commit 65c8297

Please sign in to comment.