From a725b962b67dff66554ced0b3dd037cff50f3272 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Mon, 18 Nov 2013 10:20:05 +0100 Subject: [PATCH] Created the test for the load and crash bug --- test/mocha.opts | 2 +- test/persistence.test.js | 31 +++++++++++++++++++++++++++++++ test_lac/loadAndCrash.test.js | 11 +++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 test_lac/loadAndCrash.test.js diff --git a/test/mocha.opts b/test/mocha.opts index 17eeddb..873f95c 100644 --- a/test/mocha.opts +++ b/test/mocha.opts @@ -1,2 +1,2 @@ --reporter spec ---timeout 2000 +--timeout 10000 diff --git a/test/persistence.test.js b/test/persistence.test.js index 122941c..41c9134 100644 --- a/test/persistence.test.js +++ b/test/persistence.test.js @@ -6,8 +6,10 @@ var should = require('chai').should() , _ = require('underscore') , async = require('async') , model = require('../lib/model') + , customUtils = require('../lib/customUtils') , Datastore = require('../lib/datastore') , Persistence = require('../lib/persistence') + , child_process = require('child_process') ; @@ -247,5 +249,34 @@ describe('Persistence', function () { }); }); }); + + + // This test is a bit complicated since it depends on the time actions take to execute + // It may not work as expected on all machines + // But it will not be seen as a failed test. The worst is that the timing is off and it would have worked on your machine regardless of the load failsafe + // It is timed for my dev machine + describe.only('Prevent dataloss when persisting data', function () { + + it('If system crashes during a loadDatabase, the former version is not lost', function (done) { + var cp, N = 150000, toWrite = "", i; + + // Creating a db file with 150k records (a bit long to load) + for (i = 0; i < N; i += 1) { + toWrite += model.serialize({ _id: customUtils.uid(16), hello: 'world' }) + '\n'; + } + fs.writeFileSync('workspace/rah.db', toWrite, 'utf8'); + + // Loading it in a separate process that'll crash before finishing the load + cp = child_process.fork('test_lac/loadAndCrash.test') + cp.on('message', function (msg) { + // Let the child process enough time to crash + setTimeout(function () { + fs.readFileSync('workspace/rah.db', 'utf8').length.should.not.equal(0); + done(); + }, 100); + }); + }); + + }); }); diff --git a/test_lac/loadAndCrash.test.js b/test_lac/loadAndCrash.test.js new file mode 100644 index 0000000..015ccbe --- /dev/null +++ b/test_lac/loadAndCrash.test.js @@ -0,0 +1,11 @@ +var Nedb = require('../lib/datastore.js') + , db = new Nedb({ filename: 'workspace/rah.db' }) + ; + +// Simulate a crash in 100ms +setTimeout(function() { + process.send('crash'); + process.exit(); +}, 100); + +db.loadDatabase(); \ No newline at end of file