<commit_before>#!/usr/bin/env node

/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2017 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

/* cdp-driver -- A command-line JSON input/output wrapper around
 * chrome-remote-interface (Chrome Debug Protocol).
 * See https://chromedevtools.github.io/devtools-protocol/
 * This needs support for protocol version 1.3.
 *
 * Set $TEST_CDP_DEBUG environment variable to enable additional
 * frame/execution context debugging.
 */

const CDP = require('chrome-remote-interface');

var enable_debug = false;

function debug(msg) {
    if (enable_debug)
        process.stderr.write("CDP: " + msg + "\n");
}

/**
 * Format response to the client
 */

function fatal() {
    console.error.apply(console.error, arguments);
    process.exit(1);
}

function fail(err) {
    if (typeof err === 'undefined')
        err = null;
    process.stdout.write(JSON.stringify({"error": err}) + '\n');
}

function success(result) {
    if (typeof result === 'undefined')
        result = null;
    process.stdout.write(JSON.stringify({"result": result}) + '\n');
}

/**
 * Record console.*() calls and Log messages so that we can forward them to
 * stderr and dump them on test failure
 */
var messages = [];
var logPromiseResolver;
var nReportedLogMessages = 0;
var unhandledExceptions = [];

// when encountering a log message that contains any of these strings, fail the test
const fatalLogs = [
    /^Warning: Failed prop type:/,
    /^Warning: Component.*declared.*instead of.*propTypes.*/,
    /^Warning: Invalid DOM property/,
    /^Warning: Received the .* for the .* attribute/,
    /^Warning: validateDOMNesting/,
];

function setupLogging(client) {
    client.Runtime.enable();

    client.Runtime.consoleAPICalled(info => {
        let msg = info.args.map(v => (v.value || "").toString()).join(" ");
        messages.push([ info.type, msg ]);
        process.stderr.write("> " + info.type + ": " + msg + "\n")

        if (fatalLogs.find(pattern => pattern.test(msg)))
            unhandledExceptions.push(msg);

        resolveLogPromise();
    });

    client.Runtime.exceptionThrown(info => {
        let details = info.exceptionDetails;
        // don't log test timeouts, they already get handled
        if (details.exception && details.exception.className === "PhWaitCondTimeout")
            return;

        process.stderr.write(details.description || JSON.stringify(details) + "\n");

        // ignore c3 crashes (https://github.com/c3js/c3/issues/2187)
        if (details.exception && details.exception.description &&
            details.exception.description.indexOf("TypeError: Cannot read property 'data_types' of null") >= 0 &&
            details.exception.description.indexOf("/kubernetes.js") >= 0)
            return;

        unhandledExceptions.push(details.exception.message ||
                                 details.exception.description ||
                                 details.exception.value ||
                                 JSON.stringify(details.exception));
    });

    client.Log.enable();
    client.Log.entryAdded(entry => {
        let msg = entry["entry"];
        messages.push([ "cdp", msg ]);
        /* Ignore authentication failure log lines that don't denote failures */
        if (!(msg.url || "").endsWith("/login") || (msg.text || "").indexOf("401") === -1)
            process.stderr.write("CDP: " + JSON.stringify(msg) + "\n");
        resolveLogPromise();
    });
}

/**
 * Resolve the log promise created with waitLog().
 */
function resolveLogPromise() {
    if (logPromiseResolver) {
        logPromiseResolver(messages.slice(nReportedLogMessages));
        nReportedLogMessages = messages.length;
        logPromiseResolver = undefined;
    }
}

/**
 * Returns a promise that resolves when log messages are available. If there
 * are already some unreported ones in the global messages variable, resolves
 * immediately.
 *
 * Only one such promise can be active at a given time. Once the promise is
 * resolved, this function can be called again to wait for further messages.
 */
function waitLog() {
    console.assert(logPromiseResolver === undefined);

    return new Promise((resolve, reject) => {
        logPromiseResolver = resolve;

        if (nReportedLogMessages < messages.length)
            resolveLogPromise();
    });
}

/**
 * Frame tracking
 *
 * For tests to be able to select the current frame (by its name) and make
 * subsequent queries apply to that, we need to track frame name → frameId →
 * executionContextId. Frame and context IDs can even change through page
 * operations (e. g. in systemd/logs.js when reporting a crash is complete),
 * so we also need a helper function to explicitly wait for a particular frame
 * to load. This is very laborious, see this issue for discussing improvements:
 * https://github.com/ChromeDevTools/devtools-protocol/issues/72
 */
var frameIdToContextId = {};
var frameNameToFrameId = {};

// set these to wait for a frame to be loaded
var frameWaitName = null;
var frameWaitPromiseResolve = null;
// set this to wait for a page load
var pageLoadPromise = null;
var pageLoadResolve = null;
var pageLoadReject = null;

function setupFrameTracking(client) {
    client.Page.enable();

    // map frame names to frame IDs; root frame has no name, no need to track that
    client.Page.frameNavigated(info => {
        debug("frameNavigated " + JSON.stringify(info));
        if (info.frame.name)
            frameNameToFrameId[info.frame.name] = info.frame.id;

        // were we waiting for this frame to be loaded?
        if (frameWaitPromiseResolve && frameWaitName === info.frame.name) {
            frameWaitPromiseResolve();
            frameWaitPromiseResolve = null;
        }
    });

    client.Page.loadEventFired(() => {
        if (pageLoadResolve) {
            debug("loadEventFired (waited for)");
            pageLoadResolve();
            pageLoadResolve = null;
            pageLoadReject = null;
        } else {
            debug("loadEventFired (no listener)");
        }
    });

    // track execution contexts so that we can map between context and frame IDs
    client.Runtime.executionContextCreated(info => {
        debug("executionContextCreated " + JSON.stringify(info));
        frameIdToContextId[info.context.auxData.frameId] = info.context.id;
    });

    client.Runtime.executionContextDestroyed(info => {
        debug("executionContextDestroyed " + info.executionContextId);
        for (let frameId in frameIdToContextId) {
            if (frameIdToContextId[frameId] == info.executionContextId) {
                delete frameIdToContextId[frameId];
                break;
            }
        }
    });
}

// helper functions for testlib.py which are too unwieldy to be poked in from Python
function getFrameExecId(frame) {
    var frameId = frameNameToFrameId[frame];
    if (!frameId)
        throw Error(`Frame ${frame} is unknown`);
    var execId = frameIdToContextId[frameId];
    if (!execId)
        throw Error(`Frame ${frame} (${frameId}) has no executionContextId`);
    return execId;
}

function expectLoad(timeout) {
    var tm = setTimeout( () => pageLoadReject("timed out waiting for page load"), timeout);
    pageLoadPromise.then( () => { clearTimeout(tm); pageLoadPromise = null; });
    return pageLoadPromise;
}

function expectLoadFrame(name, timeout) {
    return new Promise((resolve, reject) => {
        let tm = setTimeout( () => reject("timed out waiting for frame load"), timeout );

        // we can only have one Page.frameNavigated() handler, so let our handler above resolve this promise
        frameWaitName = name;
        new Promise((fwpResolve, fwpReject) => { frameWaitPromiseResolve = fwpResolve })
            .then(() => {
                // For the frame to be fully valid for queries, it also needs the corresponding
                // executionContextCreated() signal. This might happen before or after frameNavigated(), so wait in case
                // it happens afterwards.
               function pollExecId() {
                    if (frameIdToContextId[frameNameToFrameId[name]]) {
                        clearTimeout(tm);
                        resolve();
                    } else {
                        setTimeout(pollExecId, 100);
                    }
                }
                pollExecId();
            });
    });
}

/**
 * SSL handling
 */

// secure by default; tests can override to "continue"
// https://chromedevtools.github.io/devtools-protocol/1-3/Security/#type-CertificateErrorAction
var ssl_bad_certificate_action = "cancel";

function setupSSLCertHandling(client) {
    client.Security.enable();

    client.Security.setOverrideCertificateErrors({override: true});
    client.Security.certificateError(info => {
        process.stderr.write(`CDP: Security.certificateError ${JSON.stringify(info)}; action: ${ssl_bad_certificate_action}\n`);
        client.Security.handleCertificateError({ eventId: info.eventId, action: ssl_bad_certificate_action });
    });
}

/**
 * Main input/process loop
 *
 * Read one line with a JS expression, eval() it, and respond with the result:
 *    success <JSON formatted return value>
 *    fail <JSON formatted error>
 * EOF shuts down the client.
 */
process.stdin.setEncoding('utf8');

if (process.env["TEST_CDP_DEBUG"])
    enable_debug = true;

options = { };
if (process.argv.length >= 3) {
    options.port = parseInt(process.argv[2]);
    if (!options.port) {
        process.stderr.write("Usage: cdp-driver.js [port]\n");
        process.exit(1);
    }
}

CDP.New(options)
    .then(target => {
        target.port = options.port;
        CDP({target: target})
            .then(client => {
                setupLogging(client);
                setupFrameTracking(client);
                setupSSLCertHandling(client);

                let input_buf = '';
                process.stdin
                    .on('data', chunk => {
                        input_buf += chunk;
                        while (true) {
                            let i = input_buf.indexOf('\n');
                            if (i < 0)
                                break;
                            let command = input_buf.slice(0, i);

                            // initialize loadEventFired promise for every command except expectLoad() itself (as that
                            // waits for a load event from the *previous* command); but if the previous command already
                            // was an expectLoad(), reinitialize also, as there are sometimes two consecutive expectLoad()s
                            if (!pageLoadPromise || !command.startsWith("expectLoad("))
                                pageLoadPromise = new Promise((resolve, reject) => { pageLoadResolve = resolve; pageLoadReject = reject; });

                            // run the command
                            eval(command).then(reply => {
                                if (unhandledExceptions.length === 0) {
                                    success(reply);
                                } else {
                                    let message = unhandledExceptions[0];
                                    fail(message.split("\n")[0]);
                                    unhandledExceptions.length = 0;
                                }
                            }, fail);

                            input_buf = input_buf.slice(i+1);
                        }

                    })
                   .on('end', () => {
                       CDP.Close(target)
                           .then(() => process.exit(0))
                           .catch(fatal);
                   });
            })
            .catch(fatal);
    })
    .catch(fatal);
<commit_msg>test: Fail tests on React "unique key" warning<commit_after>#!/usr/bin/env node

/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2017 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

/* cdp-driver -- A command-line JSON input/output wrapper around
 * chrome-remote-interface (Chrome Debug Protocol).
 * See https://chromedevtools.github.io/devtools-protocol/
 * This needs support for protocol version 1.3.
 *
 * Set $TEST_CDP_DEBUG environment variable to enable additional
 * frame/execution context debugging.
 */

const CDP = require('chrome-remote-interface');

var enable_debug = false;

function debug(msg) {
    if (enable_debug)
        process.stderr.write("CDP: " + msg + "\n");
}

/**
 * Format response to the client
 */

function fatal() {
    console.error.apply(console.error, arguments);
    process.exit(1);
}

function fail(err) {
    if (typeof err === 'undefined')
        err = null;
    process.stdout.write(JSON.stringify({"error": err}) + '\n');
}

function success(result) {
    if (typeof result === 'undefined')
        result = null;
    process.stdout.write(JSON.stringify({"result": result}) + '\n');
}

/**
 * Record console.*() calls and Log messages so that we can forward them to
 * stderr and dump them on test failure
 */
var messages = [];
var logPromiseResolver;
var nReportedLogMessages = 0;
var unhandledExceptions = [];

// when encountering a log message that contains any of these strings, fail the test
const fatalLogs = [
    /^Warning: Failed prop type:/,
    /^Warning: Component.*declared.*instead of.*propTypes.*/,
    /^Warning: Invalid DOM property/,
    /^Warning: Received the .* for the .* attribute/,
    /^Warning: validateDOMNesting/,
    /^Warning: .*unique "key" prop.*/,
];

function setupLogging(client) {
    client.Runtime.enable();

    client.Runtime.consoleAPICalled(info => {
        let msg = info.args.map(v => (v.value || "").toString()).join(" ");
        messages.push([ info.type, msg ]);
        process.stderr.write("> " + info.type + ": " + msg + "\n")

        if (fatalLogs.find(pattern => pattern.test(msg)))
            unhandledExceptions.push(msg);

        resolveLogPromise();
    });

    client.Runtime.exceptionThrown(info => {
        let details = info.exceptionDetails;
        // don't log test timeouts, they already get handled
        if (details.exception && details.exception.className === "PhWaitCondTimeout")
            return;

        process.stderr.write(details.description || JSON.stringify(details) + "\n");

        // ignore c3 crashes (https://github.com/c3js/c3/issues/2187)
        if (details.exception && details.exception.description &&
            details.exception.description.indexOf("TypeError: Cannot read property 'data_types' of null") >= 0 &&
            details.exception.description.indexOf("/kubernetes.js") >= 0)
            return;

        unhandledExceptions.push(details.exception.message ||
                                 details.exception.description ||
                                 details.exception.value ||
                                 JSON.stringify(details.exception));
    });

    client.Log.enable();
    client.Log.entryAdded(entry => {
        let msg = entry["entry"];
        messages.push([ "cdp", msg ]);
        /* Ignore authentication failure log lines that don't denote failures */
        if (!(msg.url || "").endsWith("/login") || (msg.text || "").indexOf("401") === -1)
            process.stderr.write("CDP: " + JSON.stringify(msg) + "\n");
        resolveLogPromise();
    });
}

/**
 * Resolve the log promise created with waitLog().
 */
function resolveLogPromise() {
    if (logPromiseResolver) {
        logPromiseResolver(messages.slice(nReportedLogMessages));
        nReportedLogMessages = messages.length;
        logPromiseResolver = undefined;
    }
}

/**
 * Returns a promise that resolves when log messages are available. If there
 * are already some unreported ones in the global messages variable, resolves
 * immediately.
 *
 * Only one such promise can be active at a given time. Once the promise is
 * resolved, this function can be called again to wait for further messages.
 */
function waitLog() {
    console.assert(logPromiseResolver === undefined);

    return new Promise((resolve, reject) => {
        logPromiseResolver = resolve;

        if (nReportedLogMessages < messages.length)
            resolveLogPromise();
    });
}

/**
 * Frame tracking
 *
 * For tests to be able to select the current frame (by its name) and make
 * subsequent queries apply to that, we need to track frame name → frameId →
 * executionContextId. Frame and context IDs can even change through page
 * operations (e. g. in systemd/logs.js when reporting a crash is complete),
 * so we also need a helper function to explicitly wait for a particular frame
 * to load. This is very laborious, see this issue for discussing improvements:
 * https://github.com/ChromeDevTools/devtools-protocol/issues/72
 */
var frameIdToContextId = {};
var frameNameToFrameId = {};

// set these to wait for a frame to be loaded
var frameWaitName = null;
var frameWaitPromiseResolve = null;
// set this to wait for a page load
var pageLoadPromise = null;
var pageLoadResolve = null;
var pageLoadReject = null;

function setupFrameTracking(client) {
    client.Page.enable();

    // map frame names to frame IDs; root frame has no name, no need to track that
    client.Page.frameNavigated(info => {
        debug("frameNavigated " + JSON.stringify(info));
        if (info.frame.name)
            frameNameToFrameId[info.frame.name] = info.frame.id;

        // were we waiting for this frame to be loaded?
        if (frameWaitPromiseResolve && frameWaitName === info.frame.name) {
            frameWaitPromiseResolve();
            frameWaitPromiseResolve = null;
        }
    });

    client.Page.loadEventFired(() => {
        if (pageLoadResolve) {
            debug("loadEventFired (waited for)");
            pageLoadResolve();
            pageLoadResolve = null;
            pageLoadReject = null;
        } else {
            debug("loadEventFired (no listener)");
        }
    });

    // track execution contexts so that we can map between context and frame IDs
    client.Runtime.executionContextCreated(info => {
        debug("executionContextCreated " + JSON.stringify(info));
        frameIdToContextId[info.context.auxData.frameId] = info.context.id;
    });

    client.Runtime.executionContextDestroyed(info => {
        debug("executionContextDestroyed " + info.executionContextId);
        for (let frameId in frameIdToContextId) {
            if (frameIdToContextId[frameId] == info.executionContextId) {
                delete frameIdToContextId[frameId];
                break;
            }
        }
    });
}

// helper functions for testlib.py which are too unwieldy to be poked in from Python
function getFrameExecId(frame) {
    var frameId = frameNameToFrameId[frame];
    if (!frameId)
        throw Error(`Frame ${frame} is unknown`);
    var execId = frameIdToContextId[frameId];
    if (!execId)
        throw Error(`Frame ${frame} (${frameId}) has no executionContextId`);
    return execId;
}

function expectLoad(timeout) {
    var tm = setTimeout( () => pageLoadReject("timed out waiting for page load"), timeout);
    pageLoadPromise.then( () => { clearTimeout(tm); pageLoadPromise = null; });
    return pageLoadPromise;
}

function expectLoadFrame(name, timeout) {
    return new Promise((resolve, reject) => {
        let tm = setTimeout( () => reject("timed out waiting for frame load"), timeout );

        // we can only have one Page.frameNavigated() handler, so let our handler above resolve this promise
        frameWaitName = name;
        new Promise((fwpResolve, fwpReject) => { frameWaitPromiseResolve = fwpResolve })
            .then(() => {
                // For the frame to be fully valid for queries, it also needs the corresponding
                // executionContextCreated() signal. This might happen before or after frameNavigated(), so wait in case
                // it happens afterwards.
               function pollExecId() {
                    if (frameIdToContextId[frameNameToFrameId[name]]) {
                        clearTimeout(tm);
                        resolve();
                    } else {
                        setTimeout(pollExecId, 100);
                    }
                }
                pollExecId();
            });
    });
}

/**
 * SSL handling
 */

// secure by default; tests can override to "continue"
// https://chromedevtools.github.io/devtools-protocol/1-3/Security/#type-CertificateErrorAction
var ssl_bad_certificate_action = "cancel";

function setupSSLCertHandling(client) {
    client.Security.enable();

    client.Security.setOverrideCertificateErrors({override: true});
    client.Security.certificateError(info => {
        process.stderr.write(`CDP: Security.certificateError ${JSON.stringify(info)}; action: ${ssl_bad_certificate_action}\n`);
        client.Security.handleCertificateError({ eventId: info.eventId, action: ssl_bad_certificate_action });
    });
}

/**
 * Main input/process loop
 *
 * Read one line with a JS expression, eval() it, and respond with the result:
 *    success <JSON formatted return value>
 *    fail <JSON formatted error>
 * EOF shuts down the client.
 */
process.stdin.setEncoding('utf8');

if (process.env["TEST_CDP_DEBUG"])
    enable_debug = true;

options = { };
if (process.argv.length >= 3) {
    options.port = parseInt(process.argv[2]);
    if (!options.port) {
        process.stderr.write("Usage: cdp-driver.js [port]\n");
        process.exit(1);
    }
}

CDP.New(options)
    .then(target => {
        target.port = options.port;
        CDP({target: target})
            .then(client => {
                setupLogging(client);
                setupFrameTracking(client);
                setupSSLCertHandling(client);

                let input_buf = '';
                process.stdin
                    .on('data', chunk => {
                        input_buf += chunk;
                        while (true) {
                            let i = input_buf.indexOf('\n');
                            if (i < 0)
                                break;
                            let command = input_buf.slice(0, i);

                            // initialize loadEventFired promise for every command except expectLoad() itself (as that
                            // waits for a load event from the *previous* command); but if the previous command already
                            // was an expectLoad(), reinitialize also, as there are sometimes two consecutive expectLoad()s
                            if (!pageLoadPromise || !command.startsWith("expectLoad("))
                                pageLoadPromise = new Promise((resolve, reject) => { pageLoadResolve = resolve; pageLoadReject = reject; });

                            // run the command
                            eval(command).then(reply => {
                                if (unhandledExceptions.length === 0) {
                                    success(reply);
                                } else {
                                    let message = unhandledExceptions[0];
                                    fail(message.split("\n")[0]);
                                    unhandledExceptions.length = 0;
                                }
                            }, fail);

                            input_buf = input_buf.slice(i+1);
                        }

                    })
                   .on('end', () => {
                       CDP.Close(target)
                           .then(() => process.exit(0))
                           .catch(fatal);
                   });
            })
            .catch(fatal);
    })
    .catch(fatal);
<|endoftext|>


<commit_before>'use strict'

let async = require('async')

var AWS = require('aws-sdk')
// AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN

let Harcon = require('harcon')
let Barrel = Harcon.Barrel
let Communication = Harcon.Communication

function SqsBarrel ( ) { }
SqsBarrel.prototype = new Barrel()
let sqsbarrel = SqsBarrel.prototype

let Proback = require('proback.js')

sqsbarrel.sendToQueue = function ( division, message, callback ) {
	this.sqs.sendMessage({ MessageBody: message, QueueUrl: this.queues[division], DelaySeconds: 0 }, function (err, data) {
		console.log('::::::::', err, data)
		callback( err, data )
	} )
}

sqsbarrel.createQueue = function ( division, listening, callback ) {
	let self = this

	if (self.queues[division]) return callback()

	self.sqs.createQueue( { QueueName: division }, function (err, data) {
		if (err) return callback(err)

		self.logger.harconlog( null, 'SQS queue is made.', { division: division, queue: data }, 'info' )

		self.queues[division] = data.QueueUrl

		if (listening)
			self.sqs.receiveMessage({ QueueUrl: self.queues[division] }, function (err, data) {
				if (err) self.logger.harconlog(err)

				data.Messages.forEach( (message) => {
					try {
						let comm = JSON.parse( message.Body )

						let reComm = Communication.importCommunication( comm.comm )
						let reResComm = comm.response ? (comm.responseComms.length > 0 ? Communication.importCommunication( comm.responseComms[0] ) : reComm.twist( self.systemFirestarter.name, comm.err ) ) : null

						let interested = (!reResComm && self.matching( reComm ).length !== 0) || (reResComm && self.matchingResponse( reResComm ).length !== 0)

						if ( !interested )
							self.sqs.changeMessageVisibility({ QueueUrl: self.queues[division], ReceiptHandle: message.ReceiptHandle, VisibilityTimeout: 0 }, function (err, data) { if (err) self.logger.harconlog(err) } )
						else
							self.sqs.deleteMessage({ QueueUrl: self.queues[division], ReceiptHandle: message.ReceiptHandle }, (err) => { self.logger.harconlog(err) } )

						self.innerProcessAmqp( comm )
					} catch (err) { self.logger.harconlog(err) }
				} )
			})

		callback()
	} )
}

sqsbarrel.createIn = function ( division, callback ) {
	this.createQueue( division, true, callback )
}

sqsbarrel.createOut = function ( division, callback ) {
	this.createQueue( division, false, callback )
}

sqsbarrel.extendedInit = function ( config, callback ) {
	let self = this

	return new Promise( (resolve, reject) => {
		self.messages = {}
		self.queues = {}

		self.nodeSeqNo = config.nodeSeqNo || 1
		self.nodeCount = config.nodeCount || 1

		// AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION
		AWS.config.update({
			accessKeyId: config.accessKeyId,
			secretAccessKey: config.secretAccessKey,
			region: config.region
		})
		self.sqs = new AWS.SQS()

		self.timeout = config.timeout || 0

		self.connect( Proback.handler( callback, resolve, reject ) )
	} )
}

sqsbarrel.cleanupMessages = function () {
	let self = this

	let time = Date.now()
	for ( let key of Object.keys( self.messages ) ) {
		if ( time - self.messages[key].timestamp > self.timeout ) {
			let callbackFn = self.messages[key].callback
			delete self.messages[ key ]
			callbackFn( new Error('Response timeout') )
		}
	}
}

sqsbarrel.newDivision = function ( division, callback ) {
	var self = this
	if ( self.queues[division] ) return Proback.quicker( 'ok', callback )
	return new Promise( (resolve, reject) => {
		self.createOut( division, Proback.handler( callback, resolve, reject ) )
	} )
}

sqsbarrel.removeEntity = function ( division, context, name, callback) {
	return Proback.quicker( 'ok', callback )
}

sqsbarrel.newEntity = function ( division, context, name, callback) {
	var self = this

	return new Promise( (resolve, reject) => {
		async.series( [
			(cb) => {
				self.createIn( division, cb )
			}
		], Proback.handler( callback, resolve, reject ) )
	} )
}

sqsbarrel.innerProcessAmqp = function ( comm ) {
	let self = this

	self.logger.harconlog( null, 'Received from bus...', comm, 'silly' )

	let realComm = Communication.importCommunication( comm.comm )
	realComm.nodeSeqNo = comm.nodeSeqNo || 1

	if ( !comm.response ) {
		// console.log( comm.callback )
		if ( comm.callback )
			realComm.callback = function () { }
		self.logger.harconlog( null, 'Request received from bus...', realComm, 'silly' )
		self.parentIntoxicate( realComm )
	} else {
		if ( self.messages[ comm.id ] ) {
			realComm.callback = self.messages[ comm.id ].callback
			delete self.messages[ comm.id ]
		}
		let responses = comm.responseComms.map(function (c) { return Communication.importCommunication( c ) })

		self.parentAppease( realComm, comm.err ? new Error(comm.err) : null, responses )
	}
}

sqsbarrel.parentAppease = sqsbarrel.appease
sqsbarrel.appease = function ( comm, err, responseComms ) {
	let self = this
	if ( !comm.expose && self.isSystemEvent( comm.event ) )
		return this.parentAppease( comm, err, responseComms )

	if ( !self.queues[ comm.division ] )
		return self.logger.harconlog( new Error('Division is not ready yet: ' + comm.division) )

	let packet = JSON.stringify( { id: comm.id, comm: comm, nodeSeqNo: self.nodeSeqNo, err: err ? err.message : null, response: true, responseComms: responseComms || [] } )

	self.logger.harconlog( null, 'Appeasing...', {comm: comm, err: err ? err.message : null, responseComms: responseComms}, 'silly' )
	try {
		self.sendToQueue( comm.sourceDivision, packet, (err, data) => {
			if (err) self.logger.harconlog(err)
		} )
	} catch (err) {
		self.logger.harconlog( err )
	}
}

sqsbarrel.parentIntoxicate = sqsbarrel.intoxicate
sqsbarrel.intoxicate = function ( comm ) {
	let self = this
	if ( self.isSystemEvent( comm.event ) ) return this.parentIntoxicate( comm )

	if ( !self.queues[ comm.division ] )
		return self.logger.harconlog( new Error('Division is not ready yet: ' + comm.division) )

	self.logger.harconlog( null, 'Intoxicating to bus...', comm, 'silly' )

	if ( self.messages[ comm.id ] )
		return self.logger.harconlog( new Error('Duplicate message delivery!'), comm.id )

	if ( comm.callback )
		self.messages[ comm.id ] = { callback: comm.callback, timestamp: Date.now() }

	let packet = JSON.stringify( { id: comm.id, comm: comm, nodeSeqNo: self.nodeSeqNo, callback: !!comm.callback } )
	try {
		self.sendToQueue( comm.division, packet, (err, data) => {
			if (err) self.logger.harconlog(err)
		} )
	} catch (err) {
		self.logger.harconlog( err )
	}
}

sqsbarrel.clearClearer = function ( ) {
	if ( this.cleaner ) {
		clearInterval( this.cleaner )
		this.cleaner = null
	}
}

sqsbarrel.connect = function ( callback ) {
	let self = this

	self.sqs = new AWS.SQS({region: 'ap-southeast-2', maxRetries: 15})

	self.logger.harconlog( null, 'SQS creation is made.', self.connectURL, 'warn' )

	self.setupDomains( function () {
		if ( callback )
			callback()
	} )

	self.clearClearer()
	if ( self.timeout > 0 ) {
		self.cleaner = setInterval( function () {
			self.cleanupMessages()
		}, self.timeout )
	}
}

sqsbarrel.setupDomains = function ( callback ) {
	let self = this

	let fns = []
	Object.keys(self.queues).forEach( function (domain) {
		fns.push( function (cb) { self.createIn( domain, cb ) } )
	} )
	Object.keys(self.queues).forEach( function (division) {
		fns.push( function (cb) { self.createOut( division, cb ) } )
	} )
	async.series( fns, callback )
}

sqsbarrel.extendedClose = function ( callback ) {
	let self = this
	return new Promise( (resolve, reject) => {
		self.finalised = true
		self.clearClearer()

		let fns = []
		Object.keys(self.queues).forEach( function (domain) {
			fns.push( function (cb) { self.sqs.purgeQueue( { QueueUrl: self.queues[domain] }, () => { cb() } ) } )
		} )
		async.series( fns, () => {
			Proback.resolver('ok', callback, resolve)
		} )
	} )
}

module.exports = SqsBarrel
<commit_msg>barrell fixes<commit_after>'use strict'

let async = require('async')

var AWS = require('aws-sdk')
// AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN

let Harcon = require('harcon')
let Barrel = Harcon.Barrel
let Communication = Harcon.Communication

function SqsBarrel ( ) { }
SqsBarrel.prototype = new Barrel()
let sqsbarrel = SqsBarrel.prototype

let Proback = require('proback.js')

sqsbarrel.sendToQueue = function ( division, message, callback ) {
	this.sqs.sendMessage({ MessageBody: message, QueueUrl: this.queues[division], DelaySeconds: 0 }, function (err, data) {
		console.log('>>>>>>>>>', err, data)
		callback( err, data )
	} )
}

sqsbarrel.createQueue = function ( division, listening, callback ) {
	let self = this

	if (self.queues[division]) return callback()

	self.sqs.createQueue( { QueueName: division }, function (err, data) {
		if (err) return callback(err)

		self.logger.harconlog( null, 'SQS queue is made.', { division: division, queue: data }, 'info' )

		self.queues[division] = data.QueueUrl

		if (listening)
			self.sqs.receiveMessage({ QueueUrl: self.queues[division] }, function (err, data) {
				console.log('<<<<<<<<<', err, data)

				if (err) self.logger.harconlog(err)

				data.Messages.forEach( (message) => {
					try {
						let comm = JSON.parse( message.Body )

						let reComm = Communication.importCommunication( comm.comm )
						let reResComm = comm.response ? (comm.responseComms.length > 0 ? Communication.importCommunication( comm.responseComms[0] ) : reComm.twist( self.systemFirestarter.name, comm.err ) ) : null

						let interested = (!reResComm && self.matching( reComm ).length !== 0) || (reResComm && self.matchingResponse( reResComm ).length !== 0)

						if ( !interested )
							self.sqs.changeMessageVisibility({ QueueUrl: self.queues[division], ReceiptHandle: message.ReceiptHandle, VisibilityTimeout: 0 }, function (err, data) { if (err) self.logger.harconlog(err) } )
						else
							self.sqs.deleteMessage({ QueueUrl: self.queues[division], ReceiptHandle: message.ReceiptHandle }, (err) => { self.logger.harconlog(err) } )

						self.innerProcessAmqp( comm )
					} catch (err) { self.logger.harconlog(err) }
				} )
			})

		callback()
	} )
}

sqsbarrel.createIn = function ( division, callback ) {
	this.createQueue( division, true, callback )
}

sqsbarrel.createOut = function ( division, callback ) {
	this.createQueue( division, false, callback )
}

sqsbarrel.extendedInit = function ( config, callback ) {
	let self = this

	return new Promise( (resolve, reject) => {
		self.messages = {}
		self.queues = {}

		self.nodeSeqNo = config.nodeSeqNo || 1
		self.nodeCount = config.nodeCount || 1

		// AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION
		AWS.config.update({
			accessKeyId: config.accessKeyId,
			secretAccessKey: config.secretAccessKey,
			region: config.region
		})
		self.sqs = new AWS.SQS()

		self.timeout = config.timeout || 0

		self.connect( Proback.handler( callback, resolve, reject ) )
	} )
}

sqsbarrel.cleanupMessages = function () {
	let self = this

	let time = Date.now()
	for ( let key of Object.keys( self.messages ) ) {
		if ( time - self.messages[key].timestamp > self.timeout ) {
			let callbackFn = self.messages[key].callback
			delete self.messages[ key ]
			callbackFn( new Error('Response timeout') )
		}
	}
}

sqsbarrel.newDivision = function ( division, callback ) {
	var self = this
	if ( self.queues[division] ) return Proback.quicker( 'ok', callback )
	return new Promise( (resolve, reject) => {
		self.createOut( division, Proback.handler( callback, resolve, reject ) )
	} )
}

sqsbarrel.removeEntity = function ( division, context, name, callback) {
	return Proback.quicker( 'ok', callback )
}

sqsbarrel.newEntity = function ( division, context, name, callback) {
	var self = this

	return new Promise( (resolve, reject) => {
		async.series( [
			(cb) => {
				self.createIn( division, cb )
			}
		], Proback.handler( callback, resolve, reject ) )
	} )
}

sqsbarrel.innerProcessAmqp = function ( comm ) {
	let self = this

	self.logger.harconlog( null, 'Received from bus...', comm, 'silly' )

	let realComm = Communication.importCommunication( comm.comm )
	realComm.nodeSeqNo = comm.nodeSeqNo || 1

	if ( !comm.response ) {
		// console.log( comm.callback )
		if ( comm.callback )
			realComm.callback = function () { }
		self.logger.harconlog( null, 'Request received from bus...', realComm, 'silly' )
		self.parentIntoxicate( realComm )
	} else {
		if ( self.messages[ comm.id ] ) {
			realComm.callback = self.messages[ comm.id ].callback
			delete self.messages[ comm.id ]
		}
		let responses = comm.responseComms.map(function (c) { return Communication.importCommunication( c ) })

		self.parentAppease( realComm, comm.err ? new Error(comm.err) : null, responses )
	}
}

sqsbarrel.parentAppease = sqsbarrel.appease
sqsbarrel.appease = function ( comm, err, responseComms ) {
	let self = this
	if ( !comm.expose && self.isSystemEvent( comm.event ) )
		return this.parentAppease( comm, err, responseComms )

	if ( !self.queues[ comm.division ] )
		return self.logger.harconlog( new Error('Division is not ready yet: ' + comm.division) )

	let packet = JSON.stringify( { id: comm.id, comm: comm, nodeSeqNo: self.nodeSeqNo, err: err ? err.message : null, response: true, responseComms: responseComms || [] } )

	self.logger.harconlog( null, 'Appeasing...', {comm: comm, err: err ? err.message : null, responseComms: responseComms}, 'silly' )
	try {
		self.sendToQueue( comm.sourceDivision, packet, (err, data) => {
			if (err) self.logger.harconlog(err)
		} )
	} catch (err) {
		self.logger.harconlog( err )
	}
}

sqsbarrel.parentIntoxicate = sqsbarrel.intoxicate
sqsbarrel.intoxicate = function ( comm ) {
	let self = this
	if ( self.isSystemEvent( comm.event ) ) return this.parentIntoxicate( comm )

	if ( !self.queues[ comm.division ] )
		return self.logger.harconlog( new Error('Division is not ready yet: ' + comm.division) )

	self.logger.harconlog( null, 'Intoxicating to bus...', comm, 'silly' )

	if ( self.messages[ comm.id ] )
		return self.logger.harconlog( new Error('Duplicate message delivery!'), comm.id )

	if ( comm.callback )
		self.messages[ comm.id ] = { callback: comm.callback, timestamp: Date.now() }

	let packet = JSON.stringify( { id: comm.id, comm: comm, nodeSeqNo: self.nodeSeqNo, callback: !!comm.callback } )
	try {
		self.sendToQueue( comm.division, packet, (err, data) => {
			if (err) self.logger.harconlog(err)
		} )
	} catch (err) {
		self.logger.harconlog( err )
	}
}

sqsbarrel.clearClearer = function ( ) {
	if ( this.cleaner ) {
		clearInterval( this.cleaner )
		this.cleaner = null
	}
}

sqsbarrel.connect = function ( callback ) {
	let self = this

	self.sqs = new AWS.SQS({region: 'ap-southeast-2', maxRetries: 15})

	self.logger.harconlog( null, 'SQS creation is made.', self.connectURL, 'warn' )

	self.setupDomains( function () {
		if ( callback )
			callback()
	} )

	self.clearClearer()
	if ( self.timeout > 0 ) {
		self.cleaner = setInterval( function () {
			self.cleanupMessages()
		}, self.timeout )
	}
}

sqsbarrel.setupDomains = function ( callback ) {
	let self = this

	let fns = []
	Object.keys(self.queues).forEach( function (domain) {
		fns.push( function (cb) { self.createIn( domain, cb ) } )
	} )
	Object.keys(self.queues).forEach( function (division) {
		fns.push( function (cb) { self.createOut( division, cb ) } )
	} )
	async.series( fns, callback )
}

sqsbarrel.extendedClose = function ( callback ) {
	let self = this
	return new Promise( (resolve, reject) => {
		self.finalised = true
		self.clearClearer()

		let fns = []
		Object.keys(self.queues).forEach( function (domain) {
			fns.push( function (cb) { self.sqs.purgeQueue( { QueueUrl: self.queues[domain] }, () => { cb() } ) } )
		} )
		async.series( fns, () => {
			Proback.resolver('ok', callback, resolve)
		} )
	} )
}

module.exports = SqsBarrel
<|endoftext|>


<commit_before>var equal = require('assert').equal,
    puts = require('sys').puts,
    Message = require('../lib').Message,
    mongodb = require('mongodb'),
    Db = mongodb.Db,
    Connection = mongodb.Connection,
    Server = mongodb.Server;

exports.tests = {
    'should punch variables onto message when initialized with a dictionary': function(finished, prefix) {
        var message = new Message({
            'foo': 99,
            'inner_dictionary': {
               'bar': 10
            }
        });
        equal(99, message.foo, prefix + 'foo not equal to 99');
        equal(10, message.inner_dictionary.bar, prefix + 'bar not equal to 10');
        finished();
    },

    'should serialize appropriate variables when toObject is called': function(finished, prefix) {

        var object = {
            'apple': 7,
            'banana': 5,
            'inner_dictionary': {
                'foo': 2,
                'bar': 4
            }
        };
        var message = new Message(object);
        var rawMessage = message.toObject();

        var count = 0;
        for (var key in rawMessage) {
            if (rawMessage.hasOwnProperty(key)) {
                count += 1;
            }
        }

        equal(2, rawMessage.inner_dictionary.foo, prefix + 'foo had wrong value');
        equal(3, count, prefix + 'wrong number of keys serialized.');
        finished();
    }
};<commit_msg>Continuing to build out message tests.<commit_after>var equal = require('assert').equal,
    puts = require('sys').puts,
    Message = require('../lib').Message,
    mongodb = require('mongodb'),
    Db = mongodb.Db,
    Connection = mongodb.Connection,
    Server = mongodb.Server;

exports.tests = {
    'should punch variables onto message when initialized with a dictionary': function(finished, prefix) {
        var message = new Message({
            'foo': 99,
            'inner_dictionary': {
               'bar': 10
            }
        });
        equal(99, message.foo, prefix + 'foo not equal to 99');
        equal(10, message.inner_dictionary.bar, prefix + 'bar not equal to 10');
        finished();
    },

    'should serialize appropriate variables when toObject is called': function(finished, prefix) {
        var object = {
            'apple': 7,
            'banana': 5,
            'inner_dictionary': {
                'foo': 2,
                'bar': 4
            }
        };
        var message = new Message(object);
        var rawMessage = message.toObject();

        var count = 0;
        for (var key in rawMessage) {
            if (rawMessage.hasOwnProperty(key)) {
                count += 1;
            }
        }

        equal(2, rawMessage.inner_dictionary.foo, prefix + 'foo had wrong value');
        equal(3, count, prefix + 'wrong number of keys serialized.');
        finished();
    },

    'should not serialize black listed keys when toObject is called': function(finished, prefix) {
        var object = {
            '_id': 'foobar',
            '_meta': {
                'foo': 2
            },
            'foo': 5
        };
        var message = new Message(object);
        var rawMessage = message.toObject();
        equal(null, rawMessage._id, '_id was serialized');
        equal(null, rawMessage._meta, '_meta was serialized');
        equal(5, rawMessage.foo, 'foo was not serialized');
    }
};<|endoftext|>


<commit_before>const depthLimit = require('graphql-depth-limit')
const responseCachePlugin = require('apollo-server-plugin-response-cache')
const { unparse } = require('uuid-parse')
const typeDefs = require('./types')
const resolvers = require('./resolvers')
const schemaDirectives = {
  constraint: require('graphql-constraint-directive'),
  allowIf: require('./directives/allow-if'),
  allowIfLoggedIn: require('./directives/allow-if-logged-in')
}
const findOriginalError = (error) => {
  if (error.originalError) return findOriginalError(error.originalError)

  return error
}

module.exports = ({ logger }) => {
  return {
    debug: false,
    typeDefs,
    resolvers,
    schemaDirectives,
    validationRules: [depthLimit(10)],
    context: ({ ctx: { log, session, state } }) => ({
      log,
      session,
      state
    }),
    formatError (error) {
      const originalError = findOriginalError(error)

      if (originalError.exposed) {
        return originalError
      }

      if (originalError.code === 'ERR_GRAPHQL_CONSTRAINT_VALIDATION') {
        const { fieldName, message } = originalError

        return { ...originalError, message: `${fieldName} ${message}` }
      }

      logger.error(originalError)

      return { message: 'Internal Server Error' }
    },
    plugins: [
      {
        requestDidStart ({ request, context }) {
          context.log.debug(request.query)
        }
      },
      responseCachePlugin({
        sessionId: ({ context }) => {
          if (context.session.playerId) {
            return unparse(context.session.playerId)
          }

          return null
        }
      })
    ]
  }
}
<commit_msg>fix: session lookup<commit_after>const depthLimit = require('graphql-depth-limit')
const responseCachePlugin = require('apollo-server-plugin-response-cache')
const { unparse } = require('uuid-parse')
const typeDefs = require('./types')
const resolvers = require('./resolvers')
const schemaDirectives = {
  constraint: require('graphql-constraint-directive'),
  allowIf: require('./directives/allow-if'),
  allowIfLoggedIn: require('./directives/allow-if-logged-in')
}
const findOriginalError = (error) => {
  if (error.originalError) return findOriginalError(error.originalError)

  return error
}

module.exports = ({ logger }) => {
  return {
    debug: false,
    typeDefs,
    resolvers,
    schemaDirectives,
    validationRules: [depthLimit(10)],
    context: ({ ctx: { log, session, state } }) => ({
      log,
      session,
      state
    }),
    formatError (error) {
      const originalError = findOriginalError(error)

      if (originalError.exposed) {
        return originalError
      }

      if (originalError.code === 'ERR_GRAPHQL_CONSTRAINT_VALIDATION') {
        const { fieldName, message } = originalError

        return { ...originalError, message: `${fieldName} ${message}` }
      }

      logger.error(originalError)

      return { message: 'Internal Server Error' }
    },
    plugins: [
      {
        requestDidStart ({ request, context }) {
          context.log.debug(request.query)
        }
      },
      responseCachePlugin({
        sessionId: ({ context }) => {
          if (context.session && context.session.playerId) {
            return unparse(context.session.playerId)
          }

          return null
        }
      })
    ]
  }
}
<|endoftext|>


<commit_before>import Eureka from '../src/index';
import { expect } from 'chai';

describe('Integration Test', () => {
  let client;
  let config;
  before(() => {
    config = {
      instance: {
        app: 'jqservice',
        hostName: 'localhost',
        ipAddr: '127.0.0.1',
        port: 8080,
        vipAddress: 'jq.test.something.com',
        dataCenterInfo: {
          name: 'MyOwn',
        },
      },
      eureka: {
        fetchRegistry: true,
        host: 'localhost',
        port: 8080,
      },
    };
    client = new Eureka(config);
  });

  it('should register one instance with Eureka', (done) => {
    client.start(done);
  });

  it('should be able to get instance by the app id', () => {
    const instances = client.getInstancesByAppId(config.instance.app);
    expect(instances.length).to.equal(1);
  });

  it('should be able to get instance by the vipAddress', () => {
    const instances = client.getInstancesByVipAddress(config.instance.vipAddress);
    expect(instances.length).to.equal(1);
  });

  it('should be able to deregister with Eureka server', (done) => {
    client.stop(done);
  });
});
<commit_msg>Updating integration configuration to include defaults<commit_after>import Eureka from '../src/index';
import { expect } from 'chai';

describe('Integration Test', () => {
  let client;
  let config;
  before(() => {
    config = {
      instance: {
        app: 'jqservice',
        hostName: 'localhost',
        ipAddr: '127.0.0.1',
        port: 8080,
        vipAddress: 'jq.test.something.com',
        dataCenterInfo: {
          name: 'MyOwn',
        },
      },
      eureka: {
        heartbeatInterval: 30000,
        registryFetchInterval: 30000,
        fetchRegistry: true,
        servicePath: '/eureka/v2/apps/',
        ssl: false,
        useDns: false,
        fetchMetadata: true,
        host: 'localhost',
        port: 8080,
      },
    };
    client = new Eureka(config);
  });

  it('should register one instance with Eureka', (done) => {
    client.start(done);
  });

  it('should be able to get instance by the app id', () => {
    const instances = client.getInstancesByAppId(config.instance.app);
    expect(instances.length).to.equal(1);
  });

  it('should be able to get instance by the vipAddress', () => {
    const instances = client.getInstancesByVipAddress(config.instance.vipAddress);
    expect(instances.length).to.equal(1);
  });

  it('should be able to deregister with Eureka server', (done) => {
    client.stop(done);
  });
});
<|endoftext|>


<commit_before>/**
 * Fondi
 * An open courses platform.
 *
 * @author Theodore Keloglou
 * @file Main application boot file.
 */

var path = require('path');

var express = require('express');
// var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var SequelizeStore = require('connect-session-sequelize')(session.Store);
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('config');

var routes = require('./routes/index');
var helpers = require('./util/helpers');
var listeners = require('./util/listeners');
var models = require('./models/index');
var authMidd = require('./middleware/auth.midd');

var app = express();

app.set('views', path.join(__dirname, '../front/views'));
app.set('view engine', 'pug');

// Enable CORS
app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

// app.use(favicon(path.join(__dirname, '../front/static', 'favicon.ico')));
app.use(logger('dev'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(cookieParser());

app.use(session({
  secret: config.webserver.sessionSecret,
  resave: false,
  saveUninitialized: false,
  store: new SequelizeStore({
    db: models.sequelize,
  }),
}));

app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy({
  usernameField: 'username',
  passwordField: 'password',
}, function (username, password, done) {
  models.User.findOne({
    where: {
      username: username,
    },
  }).then(function (user) {
    if (!user) {
      return done(null, false, {
        message: 'Incorrect username.',
      });
    }
    return user.validPassword(password)
      .then(function (isMatch) {
        if (isMatch) {
          return done(null, user);
        } else {
          return done(null, false, {
            message: 'Incorrect password.',
          });
        }
      });
  });
}));

passport.serializeUser(function (user, done) {
  done(null, user.username);
});

passport.deserializeUser(function (username, done) {
  models.User.findOne({
    where: {
      username: username,
    },
  }).then(function (user) {
    done(null, user);
  });
});

app.use(express.static(path.join(__dirname, '../front/static')));

app.use(authMidd.check);

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// development error handler, will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err,
    });
  });
}

// production error handler, no stacktraces leaked to user
app.use(function (err, req, res) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {},
  });
});

var port = config.webserver.port;
if (process.env.PORT) {
  port = process.env.PORT;
}
app.set('port', port);

// models.sequelize.sync({ force: true })
models.sequelize.sync()
  .then(function () {
    app.listen(port);
    app.on('error', listeners.onError);
    app.on('listening', listeners.onListening);
    console.log('Server running on http://localhost:' + port + '/');
  });

module.exports = app;
<commit_msg>logging<commit_after>/**
 * Fondi
 * An open courses platform.
 *
 * @author Theodore Keloglou
 * @file Main application boot file.
 */

var path = require('path');

var express = require('express');
// var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var SequelizeStore = require('connect-session-sequelize')(session.Store);
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('config');

var routes = require('./routes/index');
var helpers = require('./util/helpers');
var listeners = require('./util/listeners');
var models = require('./models/index');
var authMidd = require('./middleware/auth.midd');

var app = express();

app.set('views', path.join(__dirname, '../front/views'));
app.set('view engine', 'pug');

// Enable CORS
app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

// app.use(favicon(path.join(__dirname, '../front/static', 'favicon.ico')));
// app.use(logger('dev')); // FIXME

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(cookieParser());

app.use(session({
  secret: config.webserver.sessionSecret,
  resave: false,
  saveUninitialized: false,
  store: new SequelizeStore({
    db: models.sequelize,
  }),
}));

app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy({
  usernameField: 'username',
  passwordField: 'password',
}, function (username, password, done) {
  models.User.findOne({
    where: {
      username: username,
    },
  }).then(function (user) {
    if (!user) {
      return done(null, false, {
        message: 'Incorrect username.',
      });
    }
    return user.validPassword(password)
      .then(function (isMatch) {
        if (isMatch) {
          return done(null, user);
        } else {
          return done(null, false, {
            message: 'Incorrect password.',
          });
        }
      });
  });
}));

passport.serializeUser(function (user, done) {
  done(null, user.username);
});

passport.deserializeUser(function (username, done) {
  models.User.findOne({
    where: {
      username: username,
    },
  }).then(function (user) {
    done(null, user);
  });
});

app.use(express.static(path.join(__dirname, '../front/static')));

app.use(authMidd.check);

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// development error handler, will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err,
    });
  });
}

// TODO: production error handler, no stacktraces leaked to user
app.use(function (err, req, res) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {},
  });
});

var port = config.webserver.port;
if (process.env.PORT) {
  port = process.env.PORT;
}
app.set('port', port);

// models.sequelize.sync({ force: true })
models.sequelize.sync()
  .then(function () {
    app.listen(port);
    app.on('error', listeners.onError);
    app.on('listening', listeners.onListening);
    console.log('Server running on http://localhost:' + port + '/');
  });

module.exports = app;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ReactNativeTextComponent
 */

'use strict';

var ReactNativeTagHandles = require('ReactNativeTagHandles');
var RCTUIManager = require('NativeModules').UIManager;

var assign = require('Object.assign');

var ReactNativeTextComponent = function(props) {
  // This constructor and its argument is currently used by mocks.
};

assign(ReactNativeTextComponent.prototype, {

  construct: function(text) {
    // This is really a ReactText (ReactNode), not a ReactElement
    this._currentElement = text;
    this._stringText = '' + text;
    this._rootNodeID = null;
  },

  mountComponent: function(rootID, transaction, context) {
    this._rootNodeID = rootID;
    var tag = ReactNativeTagHandles.allocateTag();
    var nativeTopRootID = ReactNativeTagHandles.getNativeTopRootIDFromNodeID(rootID);
    RCTUIManager.createView(
      tag,
      'RCTRawText',
      nativeTopRootID ? ReactNativeTagHandles.rootNodeIDToTag[nativeTopRootID] : null,
      {text: this._stringText}
    );
    return {
      rootNodeID: rootID,
      tag: tag,
    };
  },

  receiveComponent: function(nextText, transaction, context) {
    if (nextText !== this._currentElement) {
      this._currentElement = nextText;
      var nextStringText = '' + nextText;
      if (nextStringText !== this._stringText) {
        this._stringText = nextStringText;
        RCTUIManager.updateView(
          ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(
            this._rootNodeID
          ),
          'RCTRawText',
          {text: this._stringText}
        );
      }
    }
  },

  unmountComponent: function() {
    this._currentElement = null;
    this._stringText = null;
    this._rootNodeID = null;
  }

});

module.exports = ReactNativeTextComponent;
<commit_msg>Better error message for RawText outside <Text><commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ReactNativeTextComponent
 */

'use strict';

var ReactNativeTagHandles = require('ReactNativeTagHandles');
var RCTUIManager = require('NativeModules').UIManager;

var assign = require('Object.assign');
var invariant = require('invariant');

var ReactNativeTextComponent = function(props) {
  // This constructor and its argument is currently used by mocks.
};

assign(ReactNativeTextComponent.prototype, {

  construct: function(text) {
    // This is really a ReactText (ReactNode), not a ReactElement
    this._currentElement = text;
    this._stringText = '' + text;
    this._rootNodeID = null;
  },

  mountComponent: function(rootID, transaction, context) {
    invariant(
      context.isInAParentText,
      'RawText "' + this._stringText + '" must be wrapped in an explicit ' +
        '<Text> component.'
    );
    this._rootNodeID = rootID;
    var tag = ReactNativeTagHandles.allocateTag();
    var nativeTopRootID = ReactNativeTagHandles.getNativeTopRootIDFromNodeID(rootID);
    RCTUIManager.createView(
      tag,
      'RCTRawText',
      nativeTopRootID ? ReactNativeTagHandles.rootNodeIDToTag[nativeTopRootID] : null,
      {text: this._stringText}
    );
    return {
      rootNodeID: rootID,
      tag: tag,
    };
  },

  receiveComponent: function(nextText, transaction, context) {
    if (nextText !== this._currentElement) {
      this._currentElement = nextText;
      var nextStringText = '' + nextText;
      if (nextStringText !== this._stringText) {
        this._stringText = nextStringText;
        RCTUIManager.updateView(
          ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(
            this._rootNodeID
          ),
          'RCTRawText',
          {text: this._stringText}
        );
      }
    }
  },

  unmountComponent: function() {
    this._currentElement = null;
    this._stringText = null;
    this._rootNodeID = null;
  }

});

module.exports = ReactNativeTextComponent;
<|endoftext|>


<commit_before>'use strict';

let request = require('request');
let path    = require('path');
let Error   = require('./Error');

/**
 * Transport
 *
 * Response for making requests to Philips Hue API
 */
class Transport {
  /**
   * Constructor
   *
   * @param {Client} client Client
   */
  constructor(client) {
    this.client = client;
  }

  /**
   * Send request
   *
   * @param {Object} options Options for request
   *
   * @return {Promise} Promise for chaining
   */
  sendRequest(options) {
    options = Object.assign(
      {
        host:   `http://${this.client.host}:${this.client.port}`,
        method: 'GET',
        path:   '',
        query:  {},
        body:   {},
        raw:    false
      },
      options
    );

    // Wrap request in a promise
    return new Promise(
      (resolve, reject) => {
        request(
          {
            method: options.method,
            uri:    options.host + path.join('/', options.path),
            qs:     options.query,
            headers: {
              'Content-Type': 'application/json'
            },
            form:   JSON.stringify(options.body)
          },
          (error, response, body) => {
            return this.handleResponse(options, resolve, reject, error, response, body);
          }
        );
      }
    );
  }

  /**
   * Handle response
   *
   * @param {Object}   options  Request options
   * @param {Function} resolve  Resolve for promise
   * @param {Function} reject   Reject for promise
   * @param {mixed}    error    Request error if available
   * @param {mixed}    response Response details
   * @param {mixed}    body     Response body
   *
   * @return {mixed} Result within resolve/reject
   */
  handleResponse(options, resolve, reject, error, response, body) {
    if (error) {
      return reject(
        new Error({
          description: 'Failed to make the request: ' + error
        })
      );
    }

    let statusCode  = response.statusCode;
    let contentType = response.headers['content-type'];

    // Reject if neither 200 or json result
    if (statusCode !== 200 || contentType !== 'application/json') {
      return reject(
        new Error({
          description: 'Connection failure'
        })
      );
    }

    let result = JSON.parse(body);

    // Immediately return result if raw toggled
    if (options.raw) {
      return resolve(result);
    }

    // Use first array index if available
    if (result[0] !== undefined) {
      result = result[0];
    }

    // Reject if an error is returned
    if (result.error !== undefined) {
      return reject(
        new Error({
          type:        result.error.type,
          description: result.error.description
        })
      );
    }

    // Use value returned in success if available
    if (result.success !== undefined) {
      result = result.success;
    }

    return resolve(result);
  }
}

module.exports = Transport;
<commit_msg>GitHub #35 - Add multi option for endpoints that return multiple success/error<commit_after>'use strict';

let request = require('request');
let path    = require('path');
let Error   = require('./Error');

/**
 * Transport
 *
 * Response for making requests to Philips Hue API
 */
class Transport {
  /**
   * Constructor
   *
   * @param {Client} client Client
   */
  constructor(client) {
    this.client = client;
  }

  /**
   * Send request
   *
   * @param {Object} options Options for request
   *
   * @return {Promise} Promise for chaining
   */
  sendRequest(options) {
    options = Object.assign(
      {
        host:   `http://${this.client.host}:${this.client.port}`,
        method: 'GET',
        path:   '',
        query:  {},
        body:   {},
        raw:    false,
        multi:  false,
      },
      options
    );

    // Wrap request in a promise
    return new Promise(
      (resolve, reject) => {
        request(
          {
            method: options.method,
            uri:    options.host + path.join('/', options.path),
            qs:     options.query,
            headers: {
              'Content-Type': 'application/json'
            },
            form:   JSON.stringify(options.body)
          },
          (error, response, body) => {
            return this.handleResponse(options, resolve, reject, error, response, body);
          }
        );
      }
    );
  }

  /**
   * Handle response
   *
   * @param {Object}   options  Request options
   * @param {Function} resolve  Resolve for promise
   * @param {Function} reject   Reject for promise
   * @param {mixed}    error    Request error if available
   * @param {mixed}    response Response details
   * @param {mixed}    body     Response body
   *
   * @return {mixed} Result within resolve/reject
   */
  handleResponse(options, resolve, reject, error, response, body) {
    if (error) {
      return reject(
        new Error({
          description: 'Failed to make the request: ' + error
        })
      );
    }

    let statusCode  = response.statusCode;
    let contentType = response.headers['content-type'];

    // Reject if neither 200 or json result
    if (statusCode !== 200 || contentType !== 'application/json') {
      return reject(
        new Error({
          description: 'Connection failure'
        })
      );
    }

    let result = JSON.parse(body);

    // Immediately return result if raw toggled
    if (options.raw) {
      return resolve(result);
    }

    // Handle multiple results
    if (options.multi) {
      let results = {};

      for (let i in result) {
        if (result[i].error !== undefined) {
          return reject(
            new Error({
              type:        result[i].error.type,
              description: result[i].error.description
            })
          );
        }

        Object.assign(results, result[i].success);
      }

      return resolve(results);
    }

    // Use first array index if available
    if (result[0] !== undefined) {
      result = result[0];
    }

    // Reject if an error is returned
    if (result.error !== undefined) {
      return reject(
        new Error({
          type:        result.error.type,
          description: result.error.description
        })
      );
    }

    // Use value returned in success if available
    if (result.success !== undefined) {
      result = result.success;
    }

    return resolve(result);
  }
}

module.exports = Transport;
<|endoftext|>


<commit_before>var _ = require('underscore')._,
    Backbone = require('./modules/backbone/backbone.js'),
    settings = require('./settings'),
    rmrf = require('./rm-rf'),
    fs = require('fs'),
    events = require('events'),
    Step = require('step'),
    path = require('path');

Backbone.sync = function(method, model, success, error) {
    switch (method) {
    case 'read':
        if (model.id) {
            find(model, success, error);
        } else {
            findAll(success, error);
        }
        break;
    case 'create':
        create(model, success, error);
        break;
    case 'update':
        update(model, success, error);
        break;
    case 'delete':
        destroy(model, success, error);
        break;
    }
};

function find(model, success, error) {
    var projectPath = path.join(settings.files, 'project', model.id);
    fs.readFile(path.join(projectPath, model.id + '.mml'), 'utf-8',
    function(err, data) {
        if (err || !data) {
            return error(new Error('Error reading project file.'));
        }
        var object = JSON.parse(data);
        if (data && object) {
            // Set the object ID explicitly for multiple-load scenarios where
            // model parse()/set() is bypassed.
            object.id = model.id;
            if (object.Stylesheet && object.Stylesheet.length > 0) {
                var queue = new events.EventEmitter;
                var queueLength = object.Stylesheet.length;
                _.each(object.Stylesheet, function(filename, key) {
                    fs.readFile(path.join(projectPath, filename),
                    'utf-8',
                    function(err, data) {
                        object.Stylesheet[key] = {
                            id: filename,
                            data: data
                        };
                        queueLength--;
                        if (queueLength === 0) {
                            queue.emit('complete');
                        }
                    });
                });
                queue.on('complete', function() {
                    return success(object);
                });
            }
            else {
                return success(object);
            }
        }
        else {
            return error(new Error('Error parsing project JSON.'));
        }
    });
};

function findAll(success, error) {
    var loaded = [];
    var queue = new events.EventEmitter;
    var basepath = path.join(settings.files, 'project');
    path.exists(basepath, function(exists) {
        if (!exists) fs.mkdirSync(basepath, 0777);
        fs.readdir(basepath, function(err, files) {
            if (err) {
                return error(new Error('Error reading projects directory.'));
            }
            else if (files.length === 0) {
                return success(loaded);
            }
            var queueLength = files.length;
            for (var i = 0; i < files.length; i++) {
                find(
                    {id: files[i]},
                    function(model) {
                        loaded.push(model);
                        queueLength--;
                        if (queueLength === 0) {
                            queue.emit('complete');
                        }
                    },
                    function(err) {
                        queueLength--;
                        if (queueLength === 0) {
                            queue.emit('complete');
                        }
                    }
                );
            }
        });
    });
    queue.on('complete', function() {
        success(loaded);
    });
};

function create(model, success, error) {
    // @TODO assign a model id if not present.
    save(model, success, error);
};

function update(model, success, error) {
    save(model, success, error);
};

function destroy(model, success, error) {
    var projectPath = path.join(settings.files, 'project', model.id);
    rmrf(projectPath, function() {
        return success(model);
    });
};

function save(model, success, error) {
    var projectPath = path.join(settings.files, 'project', model.id);

    /*
    @TODO: this is validation logic.
    if (!this.Stylesheet) {
        callback(new Error('No stylesheets found'));
        return
    } else {
        _.reduce(_.pluck(this.Stylesheet, 'id'), function(memo, val) {
            if (memo[val]) {
                callback(new Error('Stylesheet ids must be unique.'));
                return;
            } else {
                memo[val] = true;
                return memo;
            }
        }, {});
    }
    */

    rmrf(projectPath, function() {
        fs.mkdir(projectPath, 0777, function() {
            // Hard clone the model JSON before doing adjustments to the data
            // based on writing separate stylesheets.
            var data = JSON.parse(JSON.stringify(model.toJSON()));
            var files = [];
            if (data.id) {
                delete data.id;
            }
            if (data.Stylesheet) {
                _.each(data.Stylesheet, function(stylesheet, key) {
                    if (stylesheet.id) {
                        files.push({
                            filename: stylesheet.id,
                            data: stylesheet.data
                        });
                        data.Stylesheet[key] = stylesheet.id;
                    }
                });
            }
            files.push({
                filename: model.id + '.mml',
                data: JSON.stringify(data)
            });

            var queue = new events.EventEmitter;
            var queueLength = files.length;
            for (var i = 0; i < files.length; i++) {
                // @TODO work through stylesheet queue and save each one individually.
                fs.writeFile(path.join(projectPath, files[i].filename),
                    files[i].data,
                    function(err) {
                    queueLength--;
                    if (queueLength === 0) {
                        queue.emit('complete');
                    }
                });
            }
            queue.on('complete', function() {
                success(model);
            });
        });
    });
}

module.exports = Backbone;

<commit_msg>Document backbone.js.<commit_after>/**
 * Server-side Backbone implementation for TileMill. This module should be
 * required instead of directly requiring Backbone.
 */
var _ = require('underscore')._,
    Backbone = require('./modules/backbone/backbone.js'),
    settings = require('./settings'),
    rmrf = require('./rm-rf'),
    fs = require('fs'),
    events = require('events'),
    Step = require('step'),
    path = require('path');

/**
 * Override Backbone.sync() for the server-side context. Uses TileMill-specific
 * file storage methods for model CRUD operations.
 */
Backbone.sync = function(method, model, success, error) {
    switch (method) {
    case 'read':
        if (model.id) {
            load(model, success, error);
        } else {
            loadAll(success, error);
        }
        break;
    case 'create':
        create(model, success, error);
        break;
    case 'update':
        update(model, success, error);
        break;
    case 'delete':
        destroy(model, success, error);
        break;
    }
};

/**
 * Load a single model. Requires that model.id be populated.
 */
function load(model, success, error) {
    var projectPath = path.join(settings.files, 'project', model.id);
    fs.readFile(path.join(projectPath, model.id + '.mml'), 'utf-8',
    function(err, data) {
        if (err || !data) {
            return error(new Error('Error reading project file.'));
        }
        var object = JSON.parse(data);
        if (data && object) {
            // Set the object ID explicitly for multiple-load scenarios where
            // model parse()/set() is bypassed.
            object.id = model.id;
            if (object.Stylesheet && object.Stylesheet.length > 0) {
                var queue = new events.EventEmitter;
                var queueLength = object.Stylesheet.length;
                _.each(object.Stylesheet, function(filename, key) {
                    fs.readFile(path.join(projectPath, filename),
                    'utf-8',
                    function(err, data) {
                        object.Stylesheet[key] = {
                            id: filename,
                            data: data
                        };
                        queueLength--;
                        if (queueLength === 0) {
                            queue.emit('complete');
                        }
                    });
                });
                queue.on('complete', function() {
                    return success(object);
                });
            }
            else {
                return success(object);
            }
        }
        else {
            return error(new Error('Error parsing project JSON.'));
        }
    });
};

/**
 * Load an array of all models.
 */
function loadAll(success, error) {
    var loaded = [];
    var queue = new events.EventEmitter;
    var basepath = path.join(settings.files, 'project');
    path.exists(basepath, function(exists) {
        if (!exists) fs.mkdirSync(basepath, 0777);
        fs.readdir(basepath, function(err, files) {
            if (err) {
                return error(new Error('Error reading projects directory.'));
            }
            else if (files.length === 0) {
                return success(loaded);
            }
            var queueLength = files.length;
            for (var i = 0; i < files.length; i++) {
                load(
                    {id: files[i]},
                    function(model) {
                        loaded.push(model);
                        queueLength--;
                        if (queueLength === 0) {
                            queue.emit('complete');
                        }
                    },
                    function(err) {
                        queueLength--;
                        if (queueLength === 0) {
                            queue.emit('complete');
                        }
                    }
                );
            }
        });
    });
    queue.on('complete', function() {
        success(loaded);
    });
};

/**
 * Create a new model.
 */
function create(model, success, error) {
    // @TODO assign a model id if not present.
    save(model, success, error);
};

/**
 * Update an existing model.
 */
function update(model, success, error) {
    save(model, success, error);
};

/**
 * Destroy (delete, remove, etc.) a model.
 */
function destroy(model, success, error) {
    var projectPath = path.join(settings.files, 'project', model.id);
    rmrf(projectPath, function() {
        return success(model);
    });
};

/**
 * Save a model. Called by create/update.
 */
function save(model, success, error) {
    var projectPath = path.join(settings.files, 'project', model.id);

    rmrf(projectPath, function() {
        fs.mkdir(projectPath, 0777, function() {
            // Hard clone the model JSON before doing adjustments to the data
            // based on writing separate stylesheets.
            var data = JSON.parse(JSON.stringify(model.toJSON()));
            var files = [];
            if (data.id) {
                delete data.id;
            }
            if (data.Stylesheet) {
                _.each(data.Stylesheet, function(stylesheet, key) {
                    if (stylesheet.id) {
                        files.push({
                            filename: stylesheet.id,
                            data: stylesheet.data
                        });
                        data.Stylesheet[key] = stylesheet.id;
                    }
                });
            }
            files.push({
                filename: model.id + '.mml',
                data: JSON.stringify(data)
            });

            var queue = new events.EventEmitter;
            var queueLength = files.length;
            for (var i = 0; i < files.length; i++) {
                fs.writeFile(path.join(projectPath, files[i].filename),
                    files[i].data,
                    function(err) {
                    queueLength--;
                    if (queueLength === 0) {
                        queue.emit('complete');
                    }
                });
            }
            queue.on('complete', function() {
                success(model);
            });
        });
    });
}

module.exports = Backbone;

<|endoftext|>


<commit_before>var jsdom = require("jsdom");
var test = require('tape');

jsdom.env({
  html:'

',
  features: { QuerySelector:true },
  scripts: ["js/d3.js", "build/vistk.js"],
  done: function (err, window) {

    var d3 = window.d3;
    var vistk = window.vistk;

    var data = ["rect", "circle", "triangle", "tick", "star", "diamond", "polygon", "marker"];

    var visualization = vistk.viz()
        .params({
          height: 200,
          width: 500,
          margin: {top: 30, right: 100, bottom: 30, left: 10},
          type: 'ordinal_horizontal',
          data: data,
          container: '#viz',
          var_x: '__id',
          var_y: '__id',
          items: [{
            marks: [{
              var_mark: '__value',
              type: function(d) { return d; }
            }]
          }]
        });

    d3.select("#viz").call(visualization);

    test('we should have ' + data.length + ' marks drawn', function (t) {

      t.plan(1);
      t.equal(d3.select("#viz").selectAll('.items__mark__circle')[0].length, data.length);

    });

    // FILL
    test('default circles have no fill', function (t) {

      t.plan(1);
      t.equal(d3.selectAll('.items__mark__circle')[0][0].style.fill, "");

    });

  }
});
<commit_msg>Testing marks filling JS and CSS<commit_after>var jsdom = require("jsdom");
var test = require('tape');

jsdom.env({
  // In case we want to test with CSS <link href="../css/vistk.css" rel="stylesheet">
  html:'

',
  features: { QuerySelector:true },
  scripts: ["js/d3.js", "build/vistk.js"],
  done: function (err, window) {

    var d3 = window.d3;
    var vistk = window.vistk;
    var document = window.document;

    var data = ["rect", "circle", "triangle", "tick", "star", "diamond", "polygon", "marker"];

    var visualization = vistk.viz()
        .params({
          height: 200,
          width: 500,
          margin: {top: 30, right: 100, bottom: 30, left: 10},
          type: 'ordinal_horizontal',
          data: data,
          container: '#viz',
          var_x: '__id',
          var_y: '__id',
          items: [{
            marks: [{
              var_mark: '__value',
              type: function(d) { return d; }
            }]
          }]
        });

    d3.select("#viz").call(visualization);

    test('we should have ' + data.length + ' marks drawn', function (t) {

      t.plan(data.length);
      data.forEach(function(mark) {
        t.equal(d3.select("#viz").selectAll('.items__mark__' + mark)[0].length, 1, mark);
      })

    });

    // fill
    test('default circles have no JS fill', function (t) {

      t.plan(data.length);
      data.forEach(function(mark) {
        t.equal(d3.selectAll('.items__mark__' + mark)[0][0].style.fill, "", mark);
      })

    });

    test('default circles have no CSS fill', function (t) {

      t.plan(data.length);
      data.forEach(function(mark) {

        var mark_el = document.getElementsByClassName('items__mark__' + mark);
        var mark_el_style = window.getComputedStyle(mark_el[0]);
        var mark_el_style_css = mark_el_style.fill;

        t.equal(mark_el_style_css, "", mark);
      })

    });

    // height
    // width
    // rotate
    // scale
    // stroke
    // stroke-width
    // stroke-opacity
    // offsets x y top right
    // transform

    // MARKS SPECIFIC
    // text-anchor
    // x y
    // dx dy
    // cx cy
    // pointer-events (for text?)
    // text-overflow (div)
  }
});
<|endoftext|>


<commit_before>#!/usr/bin/node
/*
 * Test creation of an incremental custom image.
 */

var DEBUG = true;
var debug = console.log;
if (!DEBUG) {
    debug = function () {};
}

var exec = require('child_process').exec;
var fs = require('fs');
var format = require('util').format;

var async = require('async');

// node-tap API
if (require.cache[__dirname + '/helper.js'])
    delete require.cache[__dirname + '/helper.js'];
var helper = require('./helper.js');
var after = helper.after;
var before = helper.before;
var test = helper.test;

var data = {
    name: 'incremental-image',
    version: '1.0.0'
};

var base_uuid = 'f669428c-a939-11e2-a485-b790efc0f0c1';
var base_kvm_uuid = '30e9e4c8-bbf2-11e2-ac3b-3b598ee13393';
var restricted_package = '9b81f74c-7535-428f-91f6-92f7c5876a45';
var six5server = '44454c4c-3700-104e-8033-cac04f475131';
var old7server = '44454c4c-3700-104d-8032-cac04f475131';

var motd = 'booga booga';

test('custom image (base 13.1.0) on 6.5 CN', function(t) {
    var cmd1 = format('%s/mk-custom-image %s "%s" \'%s\' %s',
        __dirname, base_uuid, motd, JSON.stringify(data), restricted_package);
    var options = {
        //maxBuffer: 2*1024*1024,  // suggested if TRACE is on
        env: {
            //"TRACE": "1"
        }
    };
    exec(cmd1, options, function (err1, stdout1, stderr1) {
        t.ifError(err1, format('error running "%s":\n'
            + '  err: %s\n'
            + '  stdout: %s\n'
            + '  stderr: %s', cmd1, err1, stdout1, stderr1));
        if (err1) {
            return t.end();
        }
        var customImageUuid = stdout1.trim().split(/\n/g).slice(-1);
        var cmd2 = format('%s/try-custom-image %s "%s" %s',
            __dirname, customImageUuid, motd, six5server);
        exec(cmd2, function (err2, stdout2, stderr2) {
            t.ifError(err2, format('error running "%s":\n'
                + '  err: %s\n'
                + '  stdout: %s\n'
                + '  stderr: %s', cmd2, err2, stdout2, stderr2));
            var cmd3 = '/opt/smartdc/bin/sdc-imgadm delete ' + customImageUuid;
            exec(cmd3, function (err3, stdout3, stderr3) {
                t.ifError(err3, format('error running "%s":\n'
                        + '  err: %s\n'
                        + '  stdout: %s\n'
                        + '  stderr: %s', cmd3, err3, stdout3, stderr3));
                    t.end();
            });
        });
    });
});

test('custom image (base 13.1.0) on older 7.0 CN', function(t) {
    var cmd1 = format('%s/mk-custom-image %s "%s" \'%s\' %s',
        __dirname, base_uuid, motd, JSON.stringify(data), restricted_package);
    var options = {
        //maxBuffer: 2*1024*1024,  // suggested if TRACE is on
        env: {
            //"TRACE": "1"
        }
    };
    exec(cmd1, options, function (err1, stdout1, stderr1) {
        t.ifError(err1, format('error running "%s":\n'
            + '  err: %s\n'
            + '  stdout: %s\n'
            + '  stderr: %s', cmd1, err1, stdout1, stderr1));
        if (err1) {
            return t.end();
        }
        var customImageUuid = stdout1.trim().split(/\n/g).slice(-1);
        var cmd2 = format('%s/try-custom-image %s "%s" %s',
            __dirname, customImageUuid, motd, old7server);
        exec(cmd2, function (err2, stdout2, stderr2) {
            t.ifError(err2, format('error running "%s":\n'
                + '  err: %s\n'
                + '  stdout: %s\n'
                + '  stderr: %s', cmd2, err2, stdout2, stderr2));
            var cmd3 = '/opt/smartdc/bin/sdc-imgadm delete ' + customImageUuid;
            exec(cmd3, function (err3, stdout3, stderr3) {
                t.ifError(err3, format('error running "%s":\n'
                        + '  err: %s\n'
                        + '  stdout: %s\n'
                        + '  stderr: %s', cmd3, err3, stdout3, stderr3));
                    t.end();
            });
        });
    });
});

test('custom image (base 13.1.0) on latest 7.0 CN with CloudAPI & DAPI', function(t) {
    var cmd1 = format('%s/mk-custom-image %s "%s" \'%s\' %s',
        __dirname, base_uuid, motd, JSON.stringify(data), restricted_package);
    var options = {
        //maxBuffer: 2*1024*1024,  // suggested if TRACE is on
        env: {
            //"TRACE": "1"
        }
    };
    exec(cmd1, options, function (err1, stdout1, stderr1) {
        t.ifError(err1, format('error running "%s":\n'
            + '  err: %s\n'
            + '  stdout: %s\n'
            + '  stderr: %s', cmd1, err1, stdout1, stderr1));
        if (err1) {
            return t.end();
        }
        var customImageUuid = stdout1.trim().split(/\n/g).slice(-1);
        var cmd2 = format('%s/try-custom-image %s "%s"',
            __dirname, customImageUuid, motd);
        exec(cmd2, function (err2, stdout2, stderr2) {
            t.ifError(err2, format('error running "%s":\n'
                + '  err: %s\n'
                + '  stdout: %s\n'
                + '  stderr: %s', cmd2, err2, stdout2, stderr2));
            var cmd3 = '/opt/smartdc/bin/sdc-imgadm delete ' + customImageUuid;
            exec(cmd3, function (err3, stdout3, stderr3) {
                t.ifError(err3, format('error running "%s":\n'
                        + '  err: %s\n'
                        + '  stdout: %s\n'
                        + '  stderr: %s', cmd3, err3, stdout3, stderr3));
                    t.end();
            });
        });
    });
});

test('custom KVM image (base CentOS6)', function(t) {
    var cmd1 = format('%s/mk-custom-image %s "%s" \'%s\'',
        __dirname, base_kvm_uuid, motd, JSON.stringify(data));
    var options = {
        //maxBuffer: 2*1024*1024,  // suggested if TRACE is on
        env: {
            //"TRACE": "1"
        }
    };
    exec(cmd1, options, function (err1, stdout1, stderr1) {
        t.ifError(err1, format('error running "%s":\n'
            + '  err: %s\n'
            + '  stdout: %s\n'
            + '  stderr: %s', cmd1, err1, stdout1, stderr1));
        if (err1) {
            return t.end();
        }
        var customImageUuid = stdout1.trim().split(/\n/g).slice(-1);
        var cmd2 = format('%s/try-custom-image %s "%s"',
            __dirname, customImageUuid, motd);
        exec(cmd2, function (err2, stdout2, stderr2) {
            t.ifError(err2, format('error running "%s":\n'
                + '  err: %s\n'
                + '  stdout: %s\n'
                + '  stderr: %s', cmd2, err2, stdout2, stderr2));
            var cmd3 = '/opt/smartdc/bin/sdc-imgadm delete ' + customImageUuid;
            exec(cmd3, function (err3, stdout3, stderr3) {
                t.ifError(err3, format('error running "%s":\n'
                        + '  err: %s\n'
                        + '  stdout: %s\n'
                        + '  stderr: %s', cmd3, err3, stdout3, stderr3));
                    t.end();
            });
        });
    });
});
<commit_msg>RELENG-498 tests for image creation and provisioning of kvm images (new package uuids)<commit_after>#!/usr/bin/node
/*
 * Test creation of an incremental custom image.
 */

var DEBUG = true;
var debug = console.log;
if (!DEBUG) {
    debug = function () {};
}

var exec = require('child_process').exec;
var fs = require('fs');
var format = require('util').format;

var async = require('async');

// node-tap API
if (require.cache[__dirname + '/helper.js'])
    delete require.cache[__dirname + '/helper.js'];
var helper = require('./helper.js');
var after = helper.after;
var before = helper.before;
var test = helper.test;

var data = {
    name: 'incremental-image',
    version: '1.0.0'
};

var base_uuid = 'f669428c-a939-11e2-a485-b790efc0f0c1';
var base_kvm_uuid = '30e9e4c8-bbf2-11e2-ac3b-3b598ee13393';
var restricted_package = '92e2b20a-0c37-11e3-9605-63a778146273';
var kvm_restricted_package = 'a3501ccc-0c37-11e3-965d-ef7e825515c9';
var six5server = '44454c4c-3700-104e-8033-cac04f475131';
var old7server = '44454c4c-3700-104d-8032-cac04f475131';

var motd = 'booga booga';

test('custom image (base 13.1.0) on 6.5 CN', function(t) {
    var cmd1 = format('%s/mk-custom-image %s "%s" \'%s\' %s',
        __dirname, base_uuid, motd, JSON.stringify(data), restricted_package);
    var options = {
        //maxBuffer: 2*1024*1024,  // suggested if TRACE is on
        env: {
            //"TRACE": "1"
        }
    };
    exec(cmd1, options, function (err1, stdout1, stderr1) {
        t.ifError(err1, format('error running "%s":\n'
            + '  err: %s\n'
            + '  stdout: %s\n'
            + '  stderr: %s', cmd1, err1, stdout1, stderr1));
        if (err1) {
            return t.end();
        }
        var customImageUuid = stdout1.trim().split(/\n/g).slice(-1);
        var cmd2 = format('%s/try-custom-image %s "%s" %s',
            __dirname, customImageUuid, motd, six5server);
        exec(cmd2, function (err2, stdout2, stderr2) {
            t.ifError(err2, format('error running "%s":\n'
                + '  err: %s\n'
                + '  stdout: %s\n'
                + '  stderr: %s', cmd2, err2, stdout2, stderr2));
            var cmd3 = '/opt/smartdc/bin/sdc-imgadm delete ' + customImageUuid;
            exec(cmd3, function (err3, stdout3, stderr3) {
                t.ifError(err3, format('error running "%s":\n'
                        + '  err: %s\n'
                        + '  stdout: %s\n'
                        + '  stderr: %s', cmd3, err3, stdout3, stderr3));
                    t.end();
            });
        });
    });
});

test('custom image (base 13.1.0) on older 7.0 CN', function(t) {
    var cmd1 = format('%s/mk-custom-image %s "%s" \'%s\' %s',
        __dirname, base_uuid, motd, JSON.stringify(data), restricted_package);
    var options = {
        //maxBuffer: 2*1024*1024,  // suggested if TRACE is on
        env: {
            //"TRACE": "1"
        }
    };
    exec(cmd1, options, function (err1, stdout1, stderr1) {
        t.ifError(err1, format('error running "%s":\n'
            + '  err: %s\n'
            + '  stdout: %s\n'
            + '  stderr: %s', cmd1, err1, stdout1, stderr1));
        if (err1) {
            return t.end();
        }
        var customImageUuid = stdout1.trim().split(/\n/g).slice(-1);
        var cmd2 = format('%s/try-custom-image %s "%s" %s',
            __dirname, customImageUuid, motd, old7server);
        exec(cmd2, function (err2, stdout2, stderr2) {
            t.ifError(err2, format('error running "%s":\n'
                + '  err: %s\n'
                + '  stdout: %s\n'
                + '  stderr: %s', cmd2, err2, stdout2, stderr2));
            var cmd3 = '/opt/smartdc/bin/sdc-imgadm delete ' + customImageUuid;
            exec(cmd3, function (err3, stdout3, stderr3) {
                t.ifError(err3, format('error running "%s":\n'
                        + '  err: %s\n'
                        + '  stdout: %s\n'
                        + '  stderr: %s', cmd3, err3, stdout3, stderr3));
                    t.end();
            });
        });
    });
});

test('custom image (base 13.1.0) on latest 7.0 CN with CloudAPI & DAPI', function(t) {
    var cmd1 = format('%s/mk-custom-image %s "%s" \'%s\' %s',
        __dirname, base_uuid, motd, JSON.stringify(data), restricted_package);
    var options = {
        //maxBuffer: 2*1024*1024,  // suggested if TRACE is on
        env: {
            //"TRACE": "1"
        }
    };
    exec(cmd1, options, function (err1, stdout1, stderr1) {
        t.ifError(err1, format('error running "%s":\n'
            + '  err: %s\n'
            + '  stdout: %s\n'
            + '  stderr: %s', cmd1, err1, stdout1, stderr1));
        if (err1) {
            return t.end();
        }
        var customImageUuid = stdout1.trim().split(/\n/g).slice(-1);
        var cmd2 = format('%s/try-custom-image %s "%s"',
            __dirname, customImageUuid, motd);
        exec(cmd2, function (err2, stdout2, stderr2) {
            t.ifError(err2, format('error running "%s":\n'
                + '  err: %s\n'
                + '  stdout: %s\n'
                + '  stderr: %s', cmd2, err2, stdout2, stderr2));
            var cmd3 = '/opt/smartdc/bin/sdc-imgadm delete ' + customImageUuid;
            exec(cmd3, function (err3, stdout3, stderr3) {
                t.ifError(err3, format('error running "%s":\n'
                        + '  err: %s\n'
                        + '  stdout: %s\n'
                        + '  stderr: %s', cmd3, err3, stdout3, stderr3));
                    t.end();
            });
        });
    });
});

test('custom KVM image (base CentOS6)', function(t) {
    var cmd1 = format('%s/mk-custom-image %s "%s" \'%s\' %s',
        __dirname, base_kvm_uuid, motd, JSON.stringify(data), kvm_restricted_package);
    var options = {
        //maxBuffer: 2*1024*1024,  // suggested if TRACE is on
        env: {
            //"TRACE": "1"
        }
    };
    exec(cmd1, options, function (err1, stdout1, stderr1) {
        t.ifError(err1, format('error running "%s":\n'
            + '  err: %s\n'
            + '  stdout: %s\n'
            + '  stderr: %s', cmd1, err1, stdout1, stderr1));
        if (err1) {
            return t.end();
        }
        var customImageUuid = stdout1.trim().split(/\n/g).slice(-1);
        var cmd2 = format('%s/try-custom-image %s "%s"',
            __dirname, customImageUuid, motd);
        exec(cmd2, function (err2, stdout2, stderr2) {
            t.ifError(err2, format('error running "%s":\n'
                + '  err: %s\n'
                + '  stdout: %s\n'
                + '  stderr: %s', cmd2, err2, stdout2, stderr2));
            var cmd3 = '/opt/smartdc/bin/sdc-imgadm delete ' + customImageUuid;
            exec(cmd3, function (err3, stdout3, stderr3) {
                t.ifError(err3, format('error running "%s":\n'
                        + '  err: %s\n'
                        + '  stdout: %s\n'
                        + '  stderr: %s', cmd3, err3, stdout3, stderr3));
                    t.end();
            });
        });
    });
});
<|endoftext|>