3 var assert = require('assert');
4 var crypto = require('crypto');
5 var fs = require('fs');
6 var http = require('http');
7 var path = require('path');
8 var vm = require('vm');
10 function connect(keepAlive) {
11 var pg = require('pg');
12 var database = config('database');
13 var connectionString = 'tcp://' + database.username + ':' + database.password + '@' + database.host + ':' + database.port
14 + '/' + database.name;
16 var client = new pg.Client(connectionString);
18 client.on('drain', function () {
28 function pathToDatabseSQL(relativePath) {
29 return path.resolve(__dirname, 'init-database.sql');
32 function pathToTests(testName) {
33 return testName ? path.resolve(__dirname, 'tests', testName) : path.resolve(__dirname, 'tests');
36 var configurationJSON = require('./config.json');
37 function config(key) {
38 return configurationJSON[key];
41 function TaskQueue() {
43 var numberOfRemainingTasks = 0;
44 var emptyQueueCallback;
46 function startTasksInQueue() {
48 return emptyQueueCallback();
50 var swappedQueue = queue;
53 // Increase the counter before the loop in the case taskCallback is called synchronously.
54 numberOfRemainingTasks += swappedQueue.length;
55 for (var i = 0; i < swappedQueue.length; ++i)
56 swappedQueue[i](null, taskCallback);
59 function taskCallback(error) {
60 // FIXME: Handle error.
61 console.assert(numberOfRemainingTasks > 0);
62 numberOfRemainingTasks--;
63 if (!numberOfRemainingTasks)
64 setTimeout(startTasksInQueue, 0);
67 this.addTask = function (task) { queue.push(task); }
68 this.start = function (callback) {
69 emptyQueueCallback = callback;
74 function SerializedTaskQueue() {
77 function executeNextTask(error) {
78 // FIXME: Handle error.
79 var callback = queue.pop();
80 setTimeout(function () { callback(null, executeNextTask); }, 0);
83 this.addTask = function (task) { queue.push(task); }
84 this.start = function (callback) {
92 var client = connect(true);
93 confirmUserWantsDatabaseToBeInitializedIfNeeded(client, function (error, shouldContinue) {
97 if (error || !shouldContinue) {
103 initializeDatabase(client, function (error) {
105 console.error('Failed to initialize the database', error);
110 var testCaseQueue = new SerializedTaskQueue();
111 var testFileQueue = new SerializedTaskQueue();
112 fs.readdirSync(pathToTests()).map(function (testFile) {
113 if (!testFile.match(/.js$/))
115 testFileQueue.addTask(function (error, callback) {
116 var testContent = fs.readFileSync(pathToTests(testFile), 'utf-8');
117 var environment = new TestEnvironment(testCaseQueue);
118 vm.runInNewContext(testContent, environment, pathToTests(testFile));
122 testFileQueue.start(function () {
124 testCaseQueue.start(function () {
132 function confirmUserWantsDatabaseToBeInitializedIfNeeded(client, callback) {
133 function fetchTableNames(error, callback) {
135 return callback(error);
137 client.query('SELECT table_name FROM information_schema.tables WHERE table_type = \'BASE TABLE\' and table_schema = \'public\'', function (error, result) {
139 return callback(error);
140 callback(null, result.rows.map(function (row) { return row['table_name']; }));
144 function findNonEmptyTable(error, list, callback) {
145 if (error || !list.length)
146 return callback(error);
148 var tableName = list.shift();
149 client.query('SELECT COUNT(*) FROM ' + tableName + ' LIMIT 1', function (error, result) {
151 return callback(error);
153 if (result.rows[0]['count'])
154 return callback(null, tableName);
156 findNonEmptyTable(null, list, callback);
160 fetchTableNames(null, function (error, tableNames) {
162 return callback(error, false);
164 findNonEmptyTable(null, tableNames, function (error, nonEmptyTable) {
166 return callback(error, false);
169 return callback(null, true);
171 console.warn('Table ' + nonEmptyTable + ' is not empty but running tests will drop all tables.');
172 askYesOrNoQuestion(null, 'Do you really want to continue?', callback);
177 function askYesOrNoQuestion(error, question, callback) {
179 return callback(error);
181 process.stdout.write(question + ' (y/n):');
182 process.stdin.resume();
183 process.stdin.setEncoding('utf-8');
184 process.stdin.on('data', function (line) {
187 process.stdin.pause();
188 callback(null, true);
189 } else if (line === 'n') {
190 process.stdin.pause();
191 callback(null, false);
193 console.warn('Invalid input:', line);
197 function initializeDatabase(client, callback) {
198 var commaSeparatedSqlStatements = fs.readFileSync(pathToDatabseSQL(), "utf8");
201 var queue = new TaskQueue();
202 commaSeparatedSqlStatements.split(/;\s*/).forEach(function (statement) {
203 queue.addTask(function (error, callback) {
204 client.query(statement, function (error) {
205 if (error && !firstError)
212 queue.start(function () { callback(firstError); });
215 var currentTestContext;
216 function TestEnvironment(testCaseQueue) {
217 var currentTestGroup;
219 this.assert = assert;
220 this.console = console;
222 // describe("~", function () {
223 // it("~", function () { assert(true); });
225 this.describe = function (testGroup, callback) {
226 currentTestGroup = testGroup;
230 this.it = function (testCaseDescription, testCase) {
231 testCaseQueue.addTask(function (error, callback) {
232 currentTestContext = new TestContext(currentTestGroup, testCaseDescription, function () {
233 currentTestContext = null;
234 initializeDatabase(connect(), callback);
240 this.postJSON = function (path, content, callback) {
241 sendHttpRequest(path, 'POST', 'application/json', JSON.stringify(content), function (error, response) {
242 assert.ifError(error);
247 this.httpGet = function (path, callback) {
248 sendHttpRequest(path, 'GET', null, '', function (error, response) {
249 assert.ifError(error);
254 this.httpPost= function (path, content, callback) {
255 var contentType = null;
256 if (typeof(content) != "string") {
257 contentType = 'application/x-www-form-urlencoded';
259 for (var key in content)
260 components.push(key + '=' + escape(content[key]));
261 content = components.join('&');
263 sendHttpRequest(path, 'POST', contentType, content, function (error, response) {
264 assert.ifError(error);
269 this.queryAndFetchAll = function (query, parameters, callback) {
270 var client = connect();
271 client.query(query, parameters, function (error, result) {
272 setTimeout(function () {
273 assert.ifError(error);
274 callback(result.rows);
279 this.sha256 = function (data) {
280 var hash = crypto.createHash('sha256');
282 return hash.digest('hex');
285 this.notifyDone = function () { currentTestContext.done(); }
288 process.on('uncaughtException', function (error) {
289 if (!currentTestContext)
291 currentTestContext.logError('Uncaught exception', error);
292 currentTestContext.done();
295 function sendHttpRequest(path, method, contentType, content, callback) {
296 var options = config('testServer');
298 options.method = method;
300 var request = http.request(options, function (response) {
301 var responseText = '';
302 response.setEncoding('utf8');
303 response.on('data', function (chunk) { responseText += chunk; });
304 response.on('end', function () {
305 setTimeout(function () {
306 callback(null, {statusCode: response.statusCode, responseText: responseText});
310 request.on('error', callback);
312 request.setHeader('Content-Type', contentType);
314 request.write(content);
318 function TestContext(testGroup, testCase, callback) {
321 this.description = function () {
322 return testGroup + ' ' + testCase;
324 this.done = function () {
329 this.logError = function (error, details) {
331 console.error(error, details);
334 process.stdout.write(this.description() + ': ');