"use strict";

const chunker = require('..');
const assert = require('assert');
const fs = require('fs');
const co = require('co');
const os = require('os');

// TODO: test with 1MB chunk size over 10.5MB file

describe('chunker', function() {
	it('chunks a stream into smaller streams', co.wrap(function*() {
		const input = '\x00'.repeat(1024*1024);
		const chunkSize = 17*1024;

		const tempfname = `${os.tmpdir()}/chunker1mb`;
		const f = fs.openSync(tempfname, 'w');
		fs.writeSync(f, input);
		fs.closeSync(f);

		const inputStream = fs.createReadStream(tempfname);
		inputStream.setMaxListeners(4096);

		let count = 0;
		for(let chunkStream of chunker.chunk(inputStream, 17*1024)) {
			//console.log({count, chunkStream});
			let writeBuf = new Buffer(0);
			const doneReading = new Promise(function(resolve, reject) {
				chunkStream.on('data', function(data) {
					writeBuf = Buffer.concat([writeBuf, data]);
				});
				chunkStream.once('end', resolve);
			});
			yield doneReading;

			if(count == Math.floor(input.length / chunkSize)) {
				assert.equal('\x00'.repeat(input.length % chunkSize), writeBuf.toString("utf-8"));
			} else {
				assert.equal(writeBuf.length, chunkSize);
				assert.equal('\x00'.repeat(chunkSize), writeBuf.toString("utf-8"));
			}
			count += 1;
		}
	}));
});

@@ -151,16 +151,134 @@
 ('os');%0A
+const crypto = require('crypto');%0A%0A// TODO: test 0-byte input source%0A// TODO: test non-0-byte but 1-chunk input source
 %0A// TODO
@@ -437,29 +437,40 @@
 input = 
-'%5Cx00'.repeat
+crypto.pseudoRandomBytes
 (1024*10
@@ -617,16 +617,33 @@
 f, input
+, 0, input.length
 );%0A%09%09fs.
@@ -1205,43 +1205,30 @@
 ert.
-equal('%5Cx00'.repeat(input.length %25 
+deepEqual(input.slice(
 chun
@@ -1224,32 +1224,40 @@
 .slice(chunkSize
+ * count
 ), writeBuf.toSt
@@ -1251,34 +1251,16 @@
 writeBuf
-.toString(%22utf-8%22)
 );%0A%09%09%09%7D 
@@ -1327,28 +1327,69 @@
 ert.
-equal('%5Cx00'.repeat(
+deepEqual(input.slice(chunkSize * count, chunkSize * count + 
 chun
@@ -1408,26 +1408,8 @@
 eBuf
-.toString(%22utf-8%22)
 );%0A%09

Test with random bytes, not all NULL bytes