<commit_before>var fs = require('fs');
var path = require('path');

var async = require('async');

var farmjs = require('../main');
var instman = require('./lib/instman');
var logule = require('logule');

var defaultExpectations = require('./lib/cases').$default;

//
// some test definitions
//

var ITER = async.forEach;
var NO_OF_INSTANCES = 3;
var METHODS = [ 'POST', 'GET' ];
var SHOW_TRACE = false;

//
// set up code
//

if (!SHOW_TRACE) logule.suppress('trace');
var tests = { };
tests.setUp = function(cb) {
    var self = this;

    /**
     * Helper log function so it will be easy to differeciate test logs from other stuff
     */
    self.log = function() {
        var args = [];
        args.push('\n================================================================================================================\n')
        for (var k in arguments) args.push(arguments[k]);
        args.push('\n================================================================================================================\n')
        console.info.apply(console, args);
    }

    self.instman = instman.createInstanceManager({ logger: logule });

    self.ok = function(test, c, condition, msg) {
        var m = c.from;
        if (msg) m += ": " + msg;
        return test.ok(condition, m);
    };

    self.equals = function(test, c, obj1, obj2, msg) {
        var m = c.from;
        if (msg) m += ": " + msg;
        return test.deepEqual(obj1, obj2, m);
    };

    self.log('SETUP');
    return self.instman.startMany(NO_OF_INSTANCES, cb);
};

var inner = tests.setUp;
tests.setUp = function(cb) {
    try { inner.call(this, cb); }
    catch (e) {
        console.log(e.stack);
        cb(e);
    }
};

tests.tearDown = function(cb) {
    var self = this;
    self.log('TEARDOWN');
    self.instman.close();
    cb();
};

tests.all = function(test) {
    var self = this;

    //
    // Iterate through all the cases and run them (in parallel !)
    //

    var cases = require('./lib/cases').tests;
    ITER(cases, function(c, next) {

        //
        // Send request to all instances and verify they all behave as expected
        //

        self.instman.reqall(c.from, METHODS, function(err, allresults) {
            self.ok(test, c, !err);

            if (!c.expected) throw new Error("Invalid test case, 'expected' is required");

            function assertExpected(res, expected, inst) {

                //
                // verify some general response stuff
                //

                self.ok(test, c, !res.err, "not expecting an error:" + res.err);
                self.ok(test, c, res.headers[farmjs.HEADERS.REQID], "expecting x-farmjs-reqid on every response");
                self.ok(test, c, res.headers[farmjs.HEADERS.INSTANCE], "expecting x-farmjs-instance on every response");
                self.equals(test, c, res.headers[farmjs.HEADERS.INSTANCE], expected.instance || inst, "x-farmjs-instance should be " + (expected.instance || inst));

                // verify the we have [CORS](http://www.w3.org/TR/cors/) headers.
                self.ok(test, c, res.headers['access-control-allow-origin']);
                self.ok(test, c, res.headers['access-control-allow-methods']);
                self.ok(test, c, res.headers['access-control-allow-headers']);
                self.ok(test, c, res.headers['access-control-allow-credentials']);

                //self.log(c.from, '==>', expected);

                if (expected.status) {
                    self.equals(test, c, res.statusCode, expected.status);
                }

                // this means that we can use the echo response to check a few more things
                if (expected.status === 200) {

                    self.equals(test, c, res.headers['content-type'], "application/json");

                    var echo;
                    if (!expected.bcast) {
                        return _assertEcho(JSON.parse(res.body));
                    }
                    else {

                        // handle broadcast responses. these responses basically contain
                        // the status code and headers for all the instances. the actual echo
                        // is in the x-echo header, so we extract it from there and call _assertEcho
                        // to verify it against the expecations.

                        var broadcastResponses = JSON.parse(res.body);

                        for (var id in broadcastResponses) {
                            var response = broadcastResponses[id];
                            var echo = JSON.parse(response.headers['x-echo']);
                            expected.instance = id; // make sure the instance fits the instance in the response
                            _assertEcho(echo);
                        }
                    }

                    function _assertEcho(echo) {

                        // request id must exist
                        self.ok(test, c, echo.headers[farmjs.HEADERS.REQID], "Expecting x-farmjs-reqid header");

                        if (expected.headers) {
                            for (var h in expected.headers) {
                                self.equals(test, c, echo.headers[h], expected.headers[h]);
                            }
                        }

                        if (expected.url) {
                            self.equals(test, c, echo.url, expected.url, "Expecting URL passed to app should be " + expected.url);
                        }

                        if (expected.app) {
                            self.equals(test, c, echo.headers[farmjs.HEADERS.APP], expected.app, "Expecting app to be " + expected.app);
                            self.equals(test, c, echo.appbasename, expected.app, "Expecting app to be " + expected.app);
                        }

                        if (expected.spawn) {
                            var expectedScript = path.normalize(expected.spawn.replace('$', path.join(__dirname, 'workdir')));
                            self.equals(test, c, echo.argv[1], expectedScript, "Expecting script to be " + expectedScript);
                        }

                        var expectedInstance = expected.instance || inst;
                        self.equals(test, c, echo.inst, expectedInstance, "Expecting response from instance " + expectedInstance);

                        if (expected.proxy) {
                            self.ok(test, c, echo.webserver, "Expecting response to come from webserver");
                        }

                        if (expected.method === "POST") {
                            self.equals(test, c, echo.bodyLength, self.instman.postBodyLength, "Since this is a POST, expecting body length");
                        }
                    }
                }
                else {
                    if (expected.redirect) {
                        self.equals(test, c, res.headers.location, expected.redirect, "Expecting redirect location to be " + expected.redirect);
                    }

                    if (expected.body) {
                        self.equals(test, c, res.headers['content-type'], "application/json", "Body is expected, so we need json");

                        var body = JSON.parse(res.body);
                        for (var k in expected.body) {
                            self.equals(test, c, body[k], expected.body[k], "Expecting body to contain " + k + ": " + expected.body[k]);
                        }
                    }
                }
            }

            //
            // iterate over results from all instances
            //

            for (var inst in self.instman.instances) {

                var results = allresults[inst];

                self.ok(test, c, results, "expecting results");

                //
                // iterate over results from all endpoints
                //

                for (var method in results) {

                    var endpoints = results[method];

                    self.ok(test, c, endpoints, "expecting endpoints in the results for " + method);

                    //
                    // iterate over all http methods

                    for (var endpoint in endpoints) {

                        var result = endpoints[endpoint];

                        self.ok(test, c, result, "expecting result for method " + method + " endpoint " + endpoint);

                        //
                        // prepare the 'expected' object by overriding global
                        // and then local defaults
                        //

                        var expected = {};

                        // global defaults
                        var globalDefaults = defaultExpectations[endpoint];
                        for (var k in globalDefaults) expected[k] = globalDefaults[k];

                        // local default
                        var caseDefaults = c.expected.$default;
                        if (caseDefaults) for (var k in caseDefaults) expected[k] = caseDefaults[k];

                        // actual case

                        var exp = c.expected[endpoint];

                        for (var k in exp) expected[k] = exp[k];

                        //
                        // put some matrix-specific data on the expected object
                        //

                        expected.method = method;

                        //
                        // check that the result fits expectation
                        //

                        assertExpected(result, expected, inst);
                    }

                }
            }

            next();
        });
    },
    function(err) {
        test.ok(!err, err);
        test.done();
    });
};

exports.tests = require('nodeunit').testCase(tests);<commit_msg>Added an assert that headers must exist in resp<commit_after>var fs = require('fs');
var path = require('path');

var async = require('async');

var farmjs = require('../main');
var instman = require('./lib/instman');
var logule = require('logule');

var defaultExpectations = require('./lib/cases').$default;

//
// some test definitions
//

var ITER = async.forEach;
var NO_OF_INSTANCES = 3;
var METHODS = [ 'POST', 'GET' ];
var SHOW_TRACE = false;

//
// set up code
//

if (!SHOW_TRACE) logule.suppress('trace');
var tests = { };
tests.setUp = function(cb) {
    var self = this;

    /**
     * Helper log function so it will be easy to differeciate test logs from other stuff
     */
    self.log = function() {
        var args = [];
        args.push('\n================================================================================================================\n')
        for (var k in arguments) args.push(arguments[k]);
        args.push('\n================================================================================================================\n')
        console.info.apply(console, args);
    }

    self.instman = instman.createInstanceManager({ logger: logule });

    self.ok = function(test, c, condition, msg) {
        var m = c.from;
        if (msg) m += ": " + msg;
        return test.ok(condition, m);
    };

    self.equals = function(test, c, obj1, obj2, msg) {
        var m = c.from;
        if (msg) m += ": " + msg;
        return test.deepEqual(obj1, obj2, m);
    };

    self.log('SETUP');
    return self.instman.startMany(NO_OF_INSTANCES, cb);
};

var inner = tests.setUp;
tests.setUp = function(cb) {
    try { inner.call(this, cb); }
    catch (e) {
        console.log(e.stack);
        cb(e);
    }
};

tests.tearDown = function(cb) {
    var self = this;
    self.log('TEARDOWN');
    self.instman.close();
    cb();
};

tests.all = function(test) {
    var self = this;

    //
    // Iterate through all the cases and run them (in parallel !)
    //

    var cases = require('./lib/cases').tests;
    ITER(cases, function(c, next) {

        //
        // Send request to all instances and verify they all behave as expected
        //

        self.instman.reqall(c.from, METHODS, function(err, allresults) {
            self.ok(test, c, !err);

            if (!c.expected) throw new Error("Invalid test case, 'expected' is required");

            function assertExpected(res, expected, inst) {

                //
                // verify some general response stuff
                //

                self.ok(test, c, !res.err, "not expecting an error:" + res.err);
                self.ok(test, c, res.headers, "Expecting headers in response");

                if (res.headers) {
                    self.ok(test, c, res.headers[farmjs.HEADERS.REQID], "expecting x-farmjs-reqid on every response");
                    self.ok(test, c, res.headers[farmjs.HEADERS.INSTANCE], "expecting x-farmjs-instance on every response");
                    self.equals(test, c, res.headers[farmjs.HEADERS.INSTANCE], expected.instance || inst, "x-farmjs-instance should be " + (expected.instance || inst));

                    // verify the we have [CORS](http://www.w3.org/TR/cors/) headers.
                    self.ok(test, c, res.headers['access-control-allow-origin']);
                    self.ok(test, c, res.headers['access-control-allow-methods']);
                    self.ok(test, c, res.headers['access-control-allow-headers']);
                    self.ok(test, c, res.headers['access-control-allow-credentials']);
                }

                if (expected.status) {
                    self.equals(test, c, res.statusCode, expected.status);
                }

                // this means that we can use the echo response to check a few more things
                if (expected.status === 200) {

                    self.equals(test, c, res.headers['content-type'], "application/json");

                    var echo;
                    if (!expected.bcast) {
                        return _assertEcho(JSON.parse(res.body));
                    }
                    else {

                        // handle broadcast responses. these responses basically contain
                        // the status code and headers for all the instances. the actual echo
                        // is in the x-echo header, so we extract it from there and call _assertEcho
                        // to verify it against the expecations.

                        var broadcastResponses = JSON.parse(res.body);

                        for (var id in broadcastResponses) {
                            var response = broadcastResponses[id];
                            var echo = JSON.parse(response.headers['x-echo']);
                            expected.instance = id; // make sure the instance fits the instance in the response
                            _assertEcho(echo);
                        }
                    }

                    function _assertEcho(echo) {

                        // request id must exist
                        self.ok(test, c, echo.headers[farmjs.HEADERS.REQID], "Expecting x-farmjs-reqid header");

                        if (expected.headers) {
                            for (var h in expected.headers) {
                                self.equals(test, c, echo.headers[h], expected.headers[h]);
                            }
                        }

                        if (expected.url) {
                            self.equals(test, c, echo.url, expected.url, "Expecting URL passed to app should be " + expected.url);
                        }

                        if (expected.app) {
                            self.equals(test, c, echo.headers[farmjs.HEADERS.APP], expected.app, "Expecting app to be " + expected.app);
                            self.equals(test, c, echo.appbasename, expected.app, "Expecting app to be " + expected.app);
                        }

                        if (expected.spawn) {
                            var expectedScript = path.normalize(expected.spawn.replace('$', path.join(__dirname, 'workdir')));
                            self.equals(test, c, echo.argv[1], expectedScript, "Expecting script to be " + expectedScript);
                        }

                        var expectedInstance = expected.instance || inst;
                        self.equals(test, c, echo.inst, expectedInstance, "Expecting response from instance " + expectedInstance);

                        if (expected.proxy) {
                            self.ok(test, c, echo.webserver, "Expecting response to come from webserver");
                        }

                        if (expected.method === "POST") {
                            self.equals(test, c, echo.bodyLength, self.instman.postBodyLength, "Since this is a POST, expecting body length");
                        }
                    }
                }
                else {
                    if (expected.redirect) {
                        self.equals(test, c, res.headers.location, expected.redirect, "Expecting redirect location to be " + expected.redirect);
                    }

                    if (expected.body) {
                        self.equals(test, c, res.headers['content-type'], "application/json", "Body is expected, so we need json");

                        var body = JSON.parse(res.body);
                        for (var k in expected.body) {
                            self.equals(test, c, body[k], expected.body[k], "Expecting body to contain " + k + ": " + expected.body[k]);
                        }
                    }
                }
            }

            //
            // iterate over results from all instances
            //

            for (var inst in self.instman.instances) {

                var results = allresults[inst];

                self.ok(test, c, results, "expecting results");

                //
                // iterate over results from all endpoints
                //

                for (var method in results) {

                    var endpoints = results[method];

                    self.ok(test, c, endpoints, "expecting endpoints in the results for " + method);

                    //
                    // iterate over all http methods

                    for (var endpoint in endpoints) {

                        var result = endpoints[endpoint];

                        self.ok(test, c, result, "expecting result for method " + method + " endpoint " + endpoint);

                        //
                        // prepare the 'expected' object by overriding global
                        // and then local defaults
                        //

                        var expected = {};

                        // global defaults
                        var globalDefaults = defaultExpectations[endpoint];
                        for (var k in globalDefaults) expected[k] = globalDefaults[k];

                        // local default
                        var caseDefaults = c.expected.$default;
                        if (caseDefaults) for (var k in caseDefaults) expected[k] = caseDefaults[k];

                        // actual case

                        var exp = c.expected[endpoint];

                        for (var k in exp) expected[k] = exp[k];

                        //
                        // put some matrix-specific data on the expected object
                        //

                        expected.method = method;

                        //
                        // check that the result fits expectation
                        //

                        assertExpected(result, expected, inst);
                    }

                }
            }

            next();
        });
    },
    function(err) {
        test.ok(!err, err);
        test.done();
    });
};

exports.tests = require('nodeunit').testCase(tests);<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var connect = require('connect'),
    helpers = require('./helpers'),
    assert = require('assert'),
    http = require('http');

/**
 * Path to ./test/fixtures/
 */

var fixturesPath = __dirname + '/fixtures';

// Faux products app

function products(app){
    app.all('*', function(req, res, next){
        if ('GET' == req.method) {
          return next();
        }
        res.writeHead(404, {});
        res.end('only GET is allowed to /products');
    });
    app.get('/.:format?', function(req, res){
        res.writeHead(200, {});
        res.end('products' + (req.params.format ? ' as ' + req.params.format : ''));
    });
    app.get('/:id', function(req, res){
        res.writeHead(200, {});
        res.end('product ' + req.params.id);
    });
}

// Faux main app

function main(app){
    app.post('/', function(req, res){
        res.writeHead(200, {});
        res.end('POST /');
    });
    app.put('/', function(req, res){
        res.writeHead(200, {});
        res.end('PUT /');
    });
    app.del('/', function(req, res){
        res.writeHead(200, {});
        res.end('DELETE /');
    });
    app.get('/', function(req, res){
        res.writeHead(200, {});
        res.end('GET /');
    });
    app.get('/public/*', function(req, res){
        res.writeHead(200, {});
        res.end('splat "' + req.params[0] + '"');
    });
    app.get('/files/*.*', function(req, res){
        res.writeHead(200, {});
        res.end('path: "' + req.params[0] + '" ext: "' + req.params[1] + '"');
    });
    app.get('/user/:id/:operation?', function(req, res){
        res.writeHead(200, {});
        res.end((req.params.operation || 'view') + 'ing user ' + req.params.id);
    });
    app.get('/range/:from([0-9]{1,5})-:to([0-9]{1,5})?', function(req, res){
        res.writeHead(200, {});
        res.end('range ' + req.params.from + ' to ' + (req.params.to || 'HEAD'));
    });
    app.get('/users.:format', function(req, res){
        res.writeHead(200, {});
        res.end(req.params.format + ' format');
    });
    app.get(/\/commit\/(\w+)\.\.(\w+)\/?/i, function(req, res){
        res.writeHead(200, {});
        res.end('captures: ' + [req.params[0], req.params[1]].join(', '));
    });
    app.get('/next', function(req, res, next){
        next();
    });
    app.get('/error', function(req, res, params, next){
        throw new Error('boom!');
    });
    app.get('/cookies.:format?', function(req, res, next){
        var cookies = ['num', 'num'];
        res.writeHead(200, {});
        switch (req.params.format) {
            case 'json':
                res.end(JSON.stringify(cookies));
                break;
            default:
                res.end(cookies.join(' '));
        }
    });
    app.get('/items/:id?', function(req, res, next){
        if (req.params.id) {
            res.writeHead(200, {});
            res.end('item ' + req.params.id);
        } else {
            next();
        }
    });
    app.get('/items', function(req, res, next){
        next()
    });
    app.get('/items', function(req, res){
        res.writeHead(200, {});
        res.end('items');
    });
    app.get('/failure/:id?', function(req, res, next){
        next(new Error('fail boat'));
    });
    app.get('/failure', function(req, res){
        assert.fail('next(new Error) passed to next matching router callback');
    });
    app.get('/out/:id?', function(req, res, next){
        next(true);
    });
    app.get('/out', function(){
        assert.fail('Called /out');
    });
    app.get('/cars/:id.:format?', function(req, res, next){
        res.writeHead(200, {});
        res.end('format: ' + req.params.format + ' id: ' + req.params.id);
    });
    app.get('/account/:id/files/:file', function(req, res){
        res.writeHead(200);
        res.end('file: ' + req.params.file);
    });
    app.all('/staff/:id', function(req, res, next){
        req.staff = { name: 'tj', id: req.params.id };
        next();
    });
    app.get('/staff/:id', function(req, res, next){
        res.writeHead(200);
        res.end('GET staff ' + req.staff.id);
    });
    app.post('/staff/:id', function(req, res, next){
        res.writeHead(200);
        res.end('POST staff ' + req.staff.id);
    });
    app.get('/lang/:lang([a-z]{2})', function(req, res, next){
      res.writeHead(200);
      res.end(req.params.lang);
    });
    app.options('/options', function(req, res){
      res.writeHead(204, { Allow: 'GET' });
      res.end();
    });
}

module.exports = {
    'test routing': function(){
        var server = helpers.run();
        server.use('/products', connect.router(products));
        server.use('/', connect.router(main));
        server.use('/', connect.errorHandler({ showMessage: true }));

        server.assertResponse('OPTIONS', '/options', 204);
        server.assertResponse('OPTIONS', '/items', 200, 'GET');
        server.assertResponse('OPTIONS', '/', 200, 'GET,POST,PUT,DELETE');

        server.assertResponse('GET', '/lang/en', 200, 'en');
        server.assertResponse('GET', '/lang/foobar', 404, 'Cannot GET /lang/foobar');

        server.assertResponse('GET', '/out', 404, 'Cannot GET /out');

        server.assertResponse('GET', '/items/12', 200, 'item 12');
        server.assertResponse('GET', '/items', 200, 'items');

        server.assertResponse('GET', '/staff/12', 200, 'GET staff 12');
        server.assertResponse('POST', '/staff/12', 200, 'POST staff 12');

        server.assertResponse('GET', '/failure/12', 500, 'Error: fail boat');

        server.assertResponse('GET', '/products', 200, 'products');
        server.assertResponse('GET', '/products/', 200, 'products');
        server.assertResponse('GET', '/products.json', 200, 'products as json');
        server.assertResponse('GET', '/products/12', 200, 'product 12');
        server.assertResponse('POST', '/products.json', 404, 'only GET is allowed to /products');
        server.assertResponse('PUT', '/products/12', 404, 'only GET is allowed to /products');
        server.assertResponse('DELETE', '/products', 404, 'only GET is allowed to /products');

        server.assertResponse('GET', '/next', 404, 'Cannot GET /next');
        server.assertResponse('GET', '/error', 500, 'Error: boom!');

        server.assertResponse('GET', '/cars/%5Bhey%5D', 200, 'format: undefined id: [hey]');
        server.assertResponse('GET', '/cars/12', 200, 'format: undefined id: 12');
        server.assertResponse('GET', '/cars/12.json', 200, 'format: json id: 12');

        server.assertResponse('GET', '/account/12/files/jquery.js', 200, 'file: jquery.js');

        server.assertResponse('GET', '/', 200, 'GET /', 'Test router GET /');
        server.assertResponse('POST', '/', 200, 'POST /', 'Test router POST /');
        server.assertResponse('PUT', '/', 200, 'PUT /', 'Test router PUT /');
        server.assertResponse('DELETE', '/', 200, 'DELETE /', 'Test router DELETE /');
        server.assertResponse('GET', '/user', 404, 'Cannot GET /user', 'Test router GET unmatched path param');
        server.assertResponse('GET', '/user/12', 200, 'viewing user 12', 'Test router GET matched path param');
        server.assertResponse('GET', '/user/12/', 200, 'viewing user 12', 'Test router GET matched path param with trailing slash');
        server.assertResponse('GET', '/user/99/edit', 200, 'editing user 99', 'Test router GET matched path with several params');
        server.assertResponse('GET', '/user/99/edit/', 200, 'editing user 99', 'Test router GET matched path with several params with trailing slash');
        server.assertResponse('GET', '/range/11-99', 200, 'range 11 to 99');
        server.assertResponse('GET', '/range/11-aa', 404, 'Cannot GET /range/11-aa');
        server.assertResponse('GET', '/range/11-', 200, 'range 11 to HEAD');
        server.assertResponse('GET', '/users.json', 200, 'json format');
        server.assertResponse('GET', '/cookies', 200, 'num num', 'Test router optional placeholder without value');
        server.assertResponse('GET', '/cookies.json', 200, '["num","num"]', 'Test reset optional placeholder with value');
        server.assertResponse('GET', '/public', 404, 'Cannot GET /public', 'Test required splat without value');
        server.assertResponse('GET', '/public/jquery.js', 200, 'splat "jquery.js"', 'Test required splat with value');
        server.assertResponse('GET', '/public/javascripts/jquery.js', 200, 'splat "javascripts/jquery.js"', 'Test required splat with segmented');
        server.assertResponse('GET', '/files/jquery.js', 200, 'path: "jquery" ext: "js"', 'Test several required splats');
        server.assertResponse('GET', '/files/javascripts/jquery.js', 200, 'path: "javascripts/jquery" ext: "js"', 'Test several required splats');
        server.assertResponse('GET', '/commit/foo..bar', 200, 'captures: foo, bar', 'Test RegExp paths');
    }
}
<commit_msg>rewritting router tests<commit_after>
/**
 * Module dependencies.
 */

var connect = require('connect')
  , assert = require('assert')
  , http = require('http');

module.exports = {
  'test methods': function(){
    var app = connect.createServer(
      connect.router(function(app){
        app.get('/', function(req, res){
          res.end('GET /');
        });

        app.post('/', function(req, res){
          res.end('POST /');
        });

        app.put('/', function(req, res){
          res.end('PUT /');
        });
      })
    );

    assert.response(app,
      { url: '/' },
      { body: 'GET /' });

    assert.response(app,
      { url: '/', method: 'POST' },
      { body: 'POST /' });

    assert.response(app,
      { url: '/', method: 'PUT' },
      { body: 'PUT /' });
  }
};
<|endoftext|>


<commit_before>'use strict';

require('should');

var update = require('../lib/update.js');
var config = require('../config/configuration.js');

describe("Testing the create/upload event", function() {
  var fakeQueue = {
    addition: []
  };

  before(function(done) {
    var nock = require('nock');
    // mocking the refresh token request
    nock('https://api.box.com:443')
    .post('/oauth2/token', "grant_type=refresh_token&refresh_token=fake_token&client_secret=" + config.box.secret + "&client_id=" + config.box.api)
    .reply(200, {
      access_token: 'fake_access'
    });

    // mocking the event call
    nock('https://api.box.com:443')
    .get('/2.0/events?stream_position=1')
    .reply(200, {
      "next_stream_position": "1",
      "entries": [{
        "event_type": "ITEM_CREATE",
        "source": {
          "type": "file",
          "id": "10"
          }
        },
        {"event_type": "ITEM_UPLOAD",
        "source": {
          "type": "file",
          "id": "11"
        }
      }]
    });

    done();
  });

  it('should add the two events to the addition queue', function(done) {
    update({refresh_token: 'fake_token', next_stream_position: '1'}, null, fakeQueue, function(err, cursor, serviceData) {
      cursor.should.not.equal(null);
      serviceData.access_token.should.equal('fake_access');
      serviceData.next_stream_position.should.equal('1');
      fakeQueue.addition.should.have.lengthOf(2);
      fakeQueue.addition[0].id.should.equal('10');
      fakeQueue.addition[1].id.should.equal('11');
      done(err);
    });
  });
});
<commit_msg>Update test-create.js<commit_after>'use strict';

require('should');

var update = require('../lib/update.js');
var config = require('../config/configuration.js');

describe("Testing the create/upload event", function() {
  var fakeQueue = {
    addition: []
  };

  before(function(done) {
    var nock = require('nock');
    // mocking the refresh token request
    nock('https://api.box.com:443')
    .post('/oauth2/token', "grant_type=refresh_token&refresh_token=fake_token&client_secret=" + config.box.secret + "&client_id=" + config.box.api)
    .reply(200, {
      access_token: 'fake_access'
    });

    // mocking the event call
    nock('https://api.box.com:443')
    .get('/2.0/events?stream_position=1')
    .reply(200, {
      "next_stream_position": "1",
      "entries": [{
        "event_type": "ITEM_CREATE",
        "source": {
          "type": "file",
          "id": "10"
          }
        },
        {
          "event_type": "ITEM_UPLOAD",
          "source": {
            "type": "file",
            "id": "11"
          }
        }
      ]
    });

    done();
  });

  it('should add the two events to the addition queue', function(done) {
    update({refresh_token: 'fake_token', next_stream_position: '1'}, null, fakeQueue, function(err, cursor, serviceData) {
      cursor.should.not.equal(null);
      serviceData.access_token.should.equal('fake_access');
      serviceData.next_stream_position.should.equal('1');
      fakeQueue.addition.should.have.lengthOf(2);
      fakeQueue.addition[0].id.should.equal('10');
      fakeQueue.addition[1].id.should.equal('11');
      done(err);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';
describe("high level REST requests on tungus", function () {
    var ctx = {};
    before(function (done) {
        _.each(require.cache, function (mod, modName) {
            if (~modName.indexOf('formage') || ~modName.indexOf('mongoose') || ~modName.indexOf('jugglingdb'))
                delete require.cache[modName];
        });
        require('tungus');
        var formage = require('../index');
        var mongoose = ctx.mongoose = require("mongoose");
        var conn_str = 'tingodb://./.data/' + this.test.parent.title.replace(/\s/g, '');
        mongoose.connect(conn_str, function (err) {
            if (err) return done(err);
            return mongoose.connection.db.dropDatabase(function (err, doc) {
                var AppliesTo = mongoose.model('AppliesTo', new mongoose.Schema({
                    Title: {type: String, limit: 100, required: true},
                    Identifier: {type: String, limit: 100},
                    Editable: {type: Number}
                }));
                var tests = require('../example/classic/models/tests');
                var pages = require('../example/classic/models/pages');
                var express = require('express');
                var app = express();
                formage.init(app, express, {pages: pages, AppliesTo: AppliesTo, Tests: tests}, {
                    title: 'Formage Example',
                    default_section: 'Main',
                    admin_users_gui: true
                });
                ctx.app = mock_req_proto.app = app.admin_app;
                done(err);
            });
        });
    });

    require('./common/core_test')(ctx);

    after(function () {
        ctx.mongoose.disconnect();
        delete ctx.mongoose;
        delete ctx.app;
    });
});
<commit_msg>Could it be failing because of the dirname?<commit_after>'use strict';
describe("high level REST requests on tungus", function () {
    var ctx = {};
    before(function (done) {
        _.each(require.cache, function (mod, modName) {
            if (~modName.indexOf('formage') || ~modName.indexOf('mongoose') || ~modName.indexOf('jugglingdb'))
                delete require.cache[modName];
        });
        require('tungus');
        var formage = require('../index');
        var mongoose = ctx.mongoose = require("mongoose");
        var conn_str = 'tingodb://./.data/RESTontingodb';
        mongoose.connect(conn_str, function (err) {
            if (err) return done(err);
            return mongoose.connection.db.dropDatabase(function (err, doc) {
                var AppliesTo = mongoose.model('AppliesTo', new mongoose.Schema({
                    Title: {type: String, limit: 100, required: true},
                    Identifier: {type: String, limit: 100},
                    Editable: {type: Number}
                }));
                var tests = require('../example/classic/models/tests');
                var pages = require('../example/classic/models/pages');
                var express = require('express');
                var app = express();
                formage.init(app, express, {pages: pages, AppliesTo: AppliesTo, Tests: tests}, {
                    title: 'Formage Example',
                    default_section: 'Main',
                    admin_users_gui: true
                });
                ctx.app = mock_req_proto.app = app.admin_app;
                done(err);
            });
        });
    });

    require('./common/core_test')(ctx);

    after(function () {
        ctx.mongoose.disconnect();
        delete ctx.mongoose;
        delete ctx.app;
    });
});
<|endoftext|>


<commit_before>import {fromGenMaker} from '../src/arbitrary';

describe('Monkey Testing', () => {

  it('behaviour', (done) => {
    let m = new ke.monkey.Monkey();
    let insert = fromGenMaker(function() {
      return function(engine, locale) {
        return function(done) {
          return done(1);
        };
      };
    });
    m.behaviour('insert', insert, {
      postcond: (n) => expect(n).eq(1)
    });
    m.start();

    setInterval(function() {
      m.stop();
      done();
    }, 500);
  });

});
<commit_msg>Fix test error.<commit_after>import {fromGenMaker} from '../src/arbitrary';

describe('Monkey Testing', () => {

  it('behaviour', (done) => {
    let m = new ke.monkey.Monkey();
    let insert = fromGenMaker(function() {
      return function(engine, locale) {
        return function(end) {
          return end(1);
        };
      };
    });
    m.behaviour('insert', insert, {
      postcond: (n) => expect(n).eq(1)
    });
    m.start();

    setTimeout(function() {
      m.stop();
      done();
    }, 500);
  });

});
<|endoftext|>


<commit_before>/*jshint expr: true*/
'use strict';

var should = require('should')
  , EventEmitter = require('events').EventEmitter
  , http = require('http')
  , StaticHandler = require('../lib/static');

describe('StaticHandler', function() {
  var server, config;
  var handled, handleResult;
  beforeEach(function() {
    config = {
      dir: __dirname + '/public',
      port: 8000
    };

    server = http.createServer(function(req, res) {
      if (!new StaticHandler(config).handle(req, res)) {
        res.writeHead(500);
        res.write("static is disabled");
        res.end();
      }
    }).listen(8000);
  });

  afterEach(function() {
    server.close();
  });

  it('should handle /test.txt', function(done) {
    http.get('http://localhost:8000/test.txt', function(res) {
      res.should.have.status(200);
      res.on('data', function(chunk) {
        chunk.should.match(/test\.txt content/);
        chunk.should.not.match(/<script>/);
        done();
      });
    });
  });

  it('should handle /has-body.html', function(done) {
    http.get('http://localhost:8000/has-body.html', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/<html>/);
        chunk.toString().should.match(/:8000\/livereload.js/);
        chunk.toString().should.match(/script>'\)<\/script><\/body>/);
        done();
      });
    });
  });

  it('should handle /has-no-body.html', function(done) {
    http.get('http://localhost:8000/has-no-body.html', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/<\/p>\r?\n<script>/);
        chunk.toString().should.match(/script>'\)<\/script>$/);
        done();
      });
    });
  });

  it('should handle /utf8.html', function(done) {
    http.get('http://localhost:8000/utf8.html', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/:8000\/livereload.js/);
        done();
      });
    });
  });

  it('should handle /euc-jp.html', function(done) {
    http.get('http://localhost:8000/euc-jp.html', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/:8000\/livereload.js/);

        // find A3 C5 A3 D5 A3 C3 A1 DD A3 CA A3 D0
        for (var i = 0; i < chunk.length; i++) {
          if (chunk[i] === 0xA3) {
            break;
          }
        }
        i.should.not.eql(chunk.length);
        chunk[i +  1].should.be.eql(0xC5);
        chunk[i +  2].should.be.eql(0xA3);
        chunk[i +  3].should.be.eql(0xD5);
        chunk[i +  4].should.be.eql(0xA3);
        chunk[i +  5].should.be.eql(0xC3);
        chunk[i +  6].should.be.eql(0xA1);
        chunk[i +  7].should.be.eql(0xDD);
        chunk[i +  8].should.be.eql(0xA3);
        chunk[i +  9].should.be.eql(0xCA);
        chunk[i + 10].should.be.eql(0xA3);
        chunk[i + 11].should.be.eql(0xD0);
        done();
      });
    });
  });

  it('should handle /empty.htm', function(done) {
    http.get('http://localhost:8000/empty.htm', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/:8000\/livereload.js/);
        done();
      });
    });
  });
});
<commit_msg>Fix test of StaticHandler<commit_after>/*jshint expr: true*/
'use strict';

var should = require('should')
  , EventEmitter = require('events').EventEmitter
  , http = require('http')
  , StaticHandler = require('../lib/static');

describe('StaticHandler', function() {
  var server, config;
  var handled, handleResult;
  beforeEach(function() {
    config = {
      dir: __dirname + '/public',
      port: 8000
    };

    server = http.createServer(function(req, res) {
      if (!new StaticHandler(config).handle(req, res)) {
        res.writeHead(500);
        res.write("static is disabled");
        res.end();
      }
    }).listen(8000);
  });

  afterEach(function() {
    server.close();
  });

  it('should handle /test.txt', function(done) {
    http.get('http://localhost:8000/test.txt', function(res) {
      res.should.have.status(200);
      res.on('data', function(chunk) {
        chunk.toString().should.match(/test\.txt content/);
        chunk.toString().should.not.match(/<script>/);
        done();
      });
    });
  });

  it('should handle /has-body.html', function(done) {
    http.get('http://localhost:8000/has-body.html', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/<html>/);
        chunk.toString().should.match(/:8000\/livereload.js/);
        chunk.toString().should.match(/script>'\)<\/script><\/body>/);
        done();
      });
    });
  });

  it('should handle /has-no-body.html', function(done) {
    http.get('http://localhost:8000/has-no-body.html', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/<\/p>\r?\n<script>/);
        chunk.toString().should.match(/script>'\)<\/script>$/);
        done();
      });
    });
  });

  it('should handle /utf8.html', function(done) {
    http.get('http://localhost:8000/utf8.html', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/:8000\/livereload.js/);
        done();
      });
    });
  });

  it('should handle /euc-jp.html', function(done) {
    http.get('http://localhost:8000/euc-jp.html', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/:8000\/livereload.js/);

        // find A3 C5 A3 D5 A3 C3 A1 DD A3 CA A3 D0
        for (var i = 0; i < chunk.length; i++) {
          if (chunk[i] === 0xA3) {
            break;
          }
        }
        i.should.not.eql(chunk.length);
        chunk[i +  1].should.be.eql(0xC5);
        chunk[i +  2].should.be.eql(0xA3);
        chunk[i +  3].should.be.eql(0xD5);
        chunk[i +  4].should.be.eql(0xA3);
        chunk[i +  5].should.be.eql(0xC3);
        chunk[i +  6].should.be.eql(0xA1);
        chunk[i +  7].should.be.eql(0xDD);
        chunk[i +  8].should.be.eql(0xA3);
        chunk[i +  9].should.be.eql(0xCA);
        chunk[i + 10].should.be.eql(0xA3);
        chunk[i + 11].should.be.eql(0xD0);
        done();
      });
    });
  });

  it('should handle /empty.htm', function(done) {
    http.get('http://localhost:8000/empty.htm', function(res) {
      res.should.have.status(200);
      res.should.be.html;
      res.on('data', function(chunk) {
        chunk.toString().should.match(/:8000\/livereload.js/);
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @author Vladimir Kozhin <affka@affka.ru>
 * @license MIT
 */
'use strict';

var Jii = require('../BaseJii');
var _trim = require('lodash/trim');
var _isObject = require('lodash/isObject');
var _isString = require('lodash/isString');
var _isArray = require('lodash/isArray');
var BaseObject = require('../base/Object');
class Url extends BaseObject {

    /**
         * Returns a value indicating whether a URL is relative.
         * A relative URL does not have host info part.
         * @param {string} url the URL to be checked
         * @returns {boolean} whether the URL is relative
         */
    static isRelative(url) {
        return url.indexOf('//') !== 0 && url.indexOf('://') === -1;
    }

    static to(url, context, scheme) {
        if (_isObject(url)) {
            return this.constructor.toRoute(url, context, scheme);
        }

        return url;
    // @todo
    /*$url = Yii::getAlias($url);
        if ($url === '') {
            $url = Yii::$app->getRequest()->getUrl();
        }

        if (!$scheme) {
            return $url;
        }

        if (strncmp($url, '//', 2) === 0) {
            // e.g. //hostname/path/to/resource
            return is_string($scheme) ? "$scheme:$url" : $url;
        }

        if (($pos = strpos($url, ':')) === false || !ctype_alpha(substr($url, 0, $pos))) {
            // turn relative URL into absolute
            $url = static::getUrlManager()->getHostInfo() . '/' . ltrim($url, '/');
        }

        if (is_string($scheme) && ($pos = strpos($url, ':')) !== false) {
            // replace the scheme with the specified one
            $url = $scheme . substr($url, $pos);
        }

        return $url;*/
    }

    static toRoute(route, context, scheme) {
        scheme = scheme || false;

        if (!_isObject(route)) {
            route = [route];
        }

        return scheme ? this.constructor._getUrlManager().createAbsoluteUrl(route, context, _isString(scheme) ? scheme : null) : this.constructor._getUrlManager().createUrl(route, context);
    }

    /**
         *
         * @returns {Jii.request.UrlManager}
         * @private
         */
    static _getUrlManager() {
        return this.constructor.urlManager || Jii.app.urlManager;
    }

    /**
         *
         * @param {string|array|object} route
         * @param {Jii.base.Context} context
         * @returns {{route: string, params: {}}}
         */
    static parseRoute(route, context) {
        var params = {};

        // Format ['site/index', {foo: 'bar'}]
        if (_isArray(route)) {
            if (_isObject(route[1]) && route.length === 2) {
                params = route[1];
            }
            route = route[0];
        }

        // Format {0:'site/index', foo: 'bar'}
        if (_isObject(route)) {
            params = route;
            route = params[0] || '';
            delete params[0];
        }

        return {
            route: Url._normalizeRoute(route, context),
            params: params
        };
    }

    static _normalizeRoute(route, context) {
        route = Jii.getAlias(route);
        if (route.substr(0, 1) === '/') {
            // absolute route
            return _trim(route, '/');
        }
    // relative route
    // @todo
    /*if (!Jii.app || Jii.app.controller === null) {
       throw new InvalidParamException("Unable to resolve the relative route: $route. No active controller is available.");
        }

        if (strpos($route, '/') === false) {
       // empty or an action ID
       return $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route;
        } else {
       // relative to module
       return ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/');
        }*/
    }

}

/**
         * @type {Jii.request.UrlManager}
         */
Url.urlManager = null;
module.exports = Url;<commit_msg>fix 1 place this._constructor.function() in static method<commit_after>/**
 * @author Vladimir Kozhin <affka@affka.ru>
 * @license MIT
 */
'use strict';

var Jii = require('../BaseJii');
var _trim = require('lodash/trim');
var _isObject = require('lodash/isObject');
var _isString = require('lodash/isString');
var _isArray = require('lodash/isArray');
var BaseObject = require('../base/Object');
class Url extends BaseObject {

    /**
         * Returns a value indicating whether a URL is relative.
         * A relative URL does not have host info part.
         * @param {string} url the URL to be checked
         * @returns {boolean} whether the URL is relative
         */
    static isRelative(url) {
        return url.indexOf('//') !== 0 && url.indexOf('://') === -1;
    }

    static to(url, context, scheme) {
        if (_isObject(url)) {
            return this.constructor.toRoute(url, context, scheme);
        }

        return url;
    // @todo
    /*$url = Yii::getAlias($url);
        if ($url === '') {
            $url = Yii::$app->getRequest()->getUrl();
        }

        if (!$scheme) {
            return $url;
        }

        if (strncmp($url, '//', 2) === 0) {
            // e.g. //hostname/path/to/resource
            return is_string($scheme) ? "$scheme:$url" : $url;
        }

        if (($pos = strpos($url, ':')) === false || !ctype_alpha(substr($url, 0, $pos))) {
            // turn relative URL into absolute
            $url = static::getUrlManager()->getHostInfo() . '/' . ltrim($url, '/');
        }

        if (is_string($scheme) && ($pos = strpos($url, ':')) !== false) {
            // replace the scheme with the specified one
            $url = $scheme . substr($url, $pos);
        }

        return $url;*/
    }

    static toRoute(route, context, scheme) {
        scheme = scheme || false;

        if (!_isObject(route)) {
            route = [route];
        }

        return scheme ? this.constructor._getUrlManager().createAbsoluteUrl(route, context, _isString(scheme) ? scheme : null) : this.constructor._getUrlManager().createUrl(route, context);
    }

    /**
         *
         * @returns {Jii.request.UrlManager}
         * @private
         */
    static _getUrlManager() {
        return this.constructor.urlManager || Jii.app.urlManager;
    }

    /**
         *
         * @param {string|array|object} route
         * @param {Jii.base.Context} context
         * @returns {{route: string, params: {}}}
         */
    static parseRoute(route, context) {
        var params = {};

        // Format ['site/index', {foo: 'bar'}]
        if (_isArray(route)) {
            if (_isObject(route[1]) && route.length === 2) {
                params = route[1];
            }
            route = route[0];
        }

        // Format {0:'site/index', foo: 'bar'}
        if (_isObject(route)) {
            params = route;
            route = params[0] || '';
            delete params[0];
        }

        return {
            route: this._normalizeRoute(route, context),
            params: params
        };
    }

    static _normalizeRoute(route, context) {
        route = Jii.getAlias(route);
        if (route.substr(0, 1) === '/') {
            // absolute route
            return _trim(route, '/');
        }
    // relative route
    // @todo
    /*if (!Jii.app || Jii.app.controller === null) {
       throw new InvalidParamException("Unable to resolve the relative route: $route. No active controller is available.");
        }

        if (strpos($route, '/') === false) {
       // empty or an action ID
       return $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route;
        } else {
       // relative to module
       return ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/');
        }*/
    }

}

/**
         * @type {Jii.request.UrlManager}
         */
Url.urlManager = null;
module.exports = Url;<|endoftext|>


<commit_before>"use strict";

var Response = require("./Response.class.js"),
    router = require("../router.js"),
    log = require("../../shared/logger.js").get("server"),
    _ = require("underscore");

/**
 * handle alamid-requests: services/validators
 * @param {Request} req
 * @param {function(err)} callback
 */
function handleRequest(req, callback) {

    var dispatch = router.get().handler;

    var res = new Response(),
        path = req.getPath(),
        type = req.getType(),
        method = req.getMethod(),
        transport = req.getTransportType(),
        startTime = new Date();

    var isValidRequest = ( type === "service" ) || ( type === "validator" && method === "create" );

    //only apply if res in an event-emitter
    if(typeof(res.once) === "function") {
        res.once("end", function(err) {
            res.removeAllListeners();
            callback(err, req, res);
        });
    }

    if(isValidRequest) {

        dispatch(req, res, function(err) {
            log.debug(type.toUpperCase() + " " + method + " /" + path + " " + transport + " " + (new Date() - startTime) + "ms");

            if(err === undefined) {
                err = null;
            }

            res.removeAllListeners();
            callback(err, req, res);
        });

        return;

    }

    //callback with err still needed? could be improved here
    callback(new Error("Invalid Request: " + req.getType()), req, res);
}

module.exports = handleRequest;<commit_msg>- improved request-logging<commit_after>"use strict";

var Response = require("./Response.class.js"),
    router = require("../router.js"),
    log = require("../../shared/logger.js").get("server"),
    _ = require("underscore");

/**
 * handle alamid-requests: services/validators
 * @param {Request} req
 * @param {function(err)} callback
 */
function handleRequest(req, callback) {

    var dispatch = router.get().handler;

    var res = new Response(),
        path = req.getPath(),
        type = req.getType(),
        method = req.getMethod(),
        transport = req.getTransportType(),
        startTime = new Date();

    var isValidRequest = ( type === "service" ) || ( type === "validator" && method === "create" );

    //only apply if res in an event-emitter
    if(typeof(res.once) === "function") {
        res.once("end", function(err) {
            res.removeAllListeners();
            callback(err, req, res);
        });
    }

    if(isValidRequest) {

        log.info(method.toUpperCase() + " " + req.getRawPath() + " (" + transport + ")");

        dispatch(req, res, function(err) {
            log.debug(method.toUpperCase() + " " + req.getRawPath() + " " + " (" + transport + ") " + res.getStatusCode() + " " + res.getStatus().toUpperCase() + " - " + (new Date() - startTime) + "ms");

            if(err === undefined) {
                err = null;
            }

            res.removeAllListeners();
            callback(err, req, res);
        });

        return;

    }

    //callback with err still needed? could be improved here
    callback(new Error("Invalid Request: " + req.getType()), req, res);
}

module.exports = handleRequest;<|endoftext|>


<commit_before>var assert = require('assert');
var path = require('path');
var testee = require('../lib/testee');

describe.only('Testee', function() {
  var config = {
    reporter: 'Dot',
    root: path.join(__dirname, '..')
  };

  describe('QUnit example', function() {
    it('socketio provider', function(done) {
      testee.test([ 'examples/qunit/index.html' ], [ 'firefox' ], config).fail(function(error) {
        assert.equal(error.message, 'There were 0 general errors and 1 total test failures.');
        done();
      });
    });
    it('rest provider', function(done) {
      testee.test([ 'examples/qunit/rest.html' ], [ 'firefox' ], config).fail(function(error) {
        assert.equal(error.message, 'There were 0 general errors and 1 total test failures.');
        done();
      });
    });
  });

  describe('Jasmine example', function() {
    it('socketio provider', function(done) {
      testee.test([ 'examples/jasmine/index.html' ], [ 'firefox' ], config).fail(function(error) {
        assert.equal(error.message, 'There were 0 general errors and 1 total test failures.');
        done();
      });
    });
    it('rest provider', function(done) {
      testee.test([ 'examples/jasmine/rest.html' ], [ 'firefox' ], config).fail(function(error) {
        assert.equal(error.message, 'There were 0 general errors and 1 total test failures.');
        done();
      });
    });
  });

  describe('Mocha example', function() {
    it('socketio provider', function(done) {
      testee.test([ 'examples/mocha/index.html' ], [ 'firefox' ], config).fail(function() {
        done();
      });
    });
    it('rest provider', function(done) {
      testee.test([ 'examples/mocha/rest.html' ], [ 'firefox' ], config).fail(function() {
        done();
      });
    });
  });
});
<commit_msg>running all tests<commit_after>var assert = require('assert');
var path = require('path');
var testee = require('../lib/testee');

describe('Testee', function() {
  var config = {
    reporter: 'Dot',
    root: path.join(__dirname, '..')
  };

  describe('QUnit example', function() {
    it('socketio provider', function(done) {
      testee.test([ 'examples/qunit/index.html' ], [ 'firefox' ], config).fail(function(error) {
        assert.equal(error.message, 'There were 0 general errors and 1 total test failures.');
        done();
      });
    });
    it('rest provider', function(done) {
      testee.test([ 'examples/qunit/rest.html' ], [ 'firefox' ], config).fail(function(error) {
        assert.equal(error.message, 'There were 0 general errors and 1 total test failures.');
        done();
      });
    });
  });

  describe('Jasmine example', function() {
    it('socketio provider', function(done) {
      testee.test([ 'examples/jasmine/index.html' ], [ 'firefox' ], config).fail(function(error) {
        assert.equal(error.message, 'There were 0 general errors and 1 total test failures.');
        done();
      });
    });
    it('rest provider', function(done) {
      testee.test([ 'examples/jasmine/rest.html' ], [ 'firefox' ], config).fail(function(error) {
        assert.equal(error.message, 'There were 0 general errors and 1 total test failures.');
        done();
      });
    });
  });

  describe('Mocha example', function() {
    it('socketio provider', function(done) {
      testee.test([ 'examples/mocha/index.html' ], [ 'firefox' ], config).fail(function() {
        done();
      });
    });
    it('rest provider', function(done) {
      testee.test([ 'examples/mocha/rest.html' ], [ 'firefox' ], config).fail(function() {
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>/*global require __dirname describe it after */
var should = require('should')
var fs = require('fs')
var async = require('async')

var makedir = require('../.')

// A lot of paths, and repeats, so that you have to handle multiple
// simultaneous makes

var path    = require('path')
var rootdir = path.normalize(__dirname)

var path_components = [rootdir,'foo','bar','baz','bat']

var paths = [rootdir + '/foo/bar/baz/bat'
            ,rootdir + '/repos/jem/node-data-proxy/public/data/airbasins/monthly/2007'
            ,rootdir + '/pos/jem/node-data-proxy/public/data/airbasins/monthly/2007'
            ,rootdir + '/os/jem/node-data-proxy/public/data/airbasins/monthly/2007'
            ,rootdir + '/s/jem/node-data-proxy/public/data/airbasins/monthly/2007'
            ,rootdir + '/repos/jem/node-data-proxy/public/data/airbasins/monthly/2007'
            ,rootdir + '/pos/jem/node-data-proxy/public/data/airbasins/monthly/2007'
            ,rootdir + '/os/jem/node-data-proxy/public/data/airbasins/monthly/2007'
            ,rootdir + '/s/jem/node-data-proxy/public/data/airbasins/monthly/2007'
            ];

after(function(done){
    try{
        fs.unlinkSync(path_components.join('/'))
    } catch (x) {
        // whatever
    }
    paths.forEach(function(path){
        try{
            fs.unlinkSync(path)
        } catch (x) {
            // whatever
        }
        return null

    });

    return done()
})

describe('create directories',function(){
    it('should create a directory and its parent',function(done){
        makedir.makedir(path_components.join('/'),function(err){
            should.not.exist(err)
            // make all of the pieces exist
            var path
            for(var i = 0; i < path_components.length; i++){

                path = path_components.slice(0,i+1)
                var stats = fs.statSync(path.join('/'))
                stats.isDirectory().should.be.ok

            }

            return done()
        })
    })

    it('should create many directories at once',function(done){
        async.each(paths
                  ,function(p,cb){
                       makedir.makedir(p,function(err){
                           should.not.exist(err)
                           return cb()
                       })
                       return null
                   }
                  ,function(e){
                       should.not.exist(e)
                       // make sure all of the paths exist

                       paths.forEach(function(p){

                           var stats = fs.statSync(p)
                           stats.isDirectory().should.be.ok

                       })
                       return done()
                   });
        return null

    })

})
<commit_msg>fix the rmdir stuff to clean up the temp dirs<commit_after>/*global require __dirname describe it after */
var should = require('should')
var fs = require('fs')
var async = require('async')

var makedir = require('../.')

// A lot of paths, and repeats, so that you have to handle multiple
// simultaneous makes

var path    = require('path')
var rootdir = path.normalize(__dirname)

var path_components = [rootdir,'foo','bar','baz','bat']

var paths = [[rootdir , 'foo','bar','baz','bat']
            ,[rootdir , 'repos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
            ,[rootdir , 'pos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
            ,[rootdir , 'os','jem','node-data-proxy','public','data','airbasins','monthly','2007']
            ,[rootdir , 's','jem','node-data-proxy','public','data','airbasins','monthly','2007']
            ,[rootdir , 'repos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
            ,[rootdir , 'pos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
            ,[rootdir , 'os','jem','node-data-proxy','public','data','airbasins','monthly','2007']
            ,[rootdir , 's','jem','node-data-proxy','public','data','airbasins','monthly','2007']
            ];

after(function(done){
    var len = path_components.length
    for(var i = 0; i < path_components.length-1; i++){
        try{
            fs.rmdirSync(path_components.slice(0,len - i).join('/'))
        } catch (x) {
            // don't care
        }
    }

    paths.forEach(function(p){
        var len = p.length
        for(var i = 0; i < p.length-1; i++){
            var rmp=p.slice(0,len - i).join('/')
            try{
                fs.rmdirSync(rmp)
            } catch (x) {
                // don't care
            }
        }
        return null

    });

    return done()
})

describe('create directories',function(){
    it('should create a directory and its parent',function(done){
        makedir.makedir(path_components.join('/'),function(err){
            should.not.exist(err)
            // make all of the pieces exist
            var path
            for(var i = 0; i < path_components.length; i++){

                path = path_components.slice(0,i+1)
                var stats = fs.statSync(path.join('/'))
                stats.isDirectory().should.be.ok

            }

            return done()
        })
    })

    it('should create many directories at once',function(done){
        async.each(paths
                  ,function(p,cb){
                       makedir.makedir(p.join('/'),function(err){
                           should.not.exist(err)
                           return cb()
                       })
                       return null
                   }
                  ,function(e){
                       should.not.exist(e)
                       // make sure all of the paths exist

                       paths.forEach(function(p){

                           var stats = fs.statSync(p.join('/'))
                           stats.isDirectory().should.be.ok

                       })
                       return done()
                   });
        return null

    })

})
<|endoftext|>


<commit_before>var createContext = require('./util/create-context')
var createREGL = require('../../regl')
var tape = require('tape')

tape('texture cube', function (t) {
  var gl = createContext(16, 16)
  var regl = createREGL({
    gl: gl,
    optionalExtensions: ['ext_texture_filter_anisotropic']
  })

  var renderCubeFace = regl({
    vert: [
      'attribute vec2 position;',
      'void main() {',
      'gl_Position = vec4(position, 0, 1);',
      '}'
    ].join('\n'),

    frag: [
      'precision highp float;',
      'uniform samplerCube tex;',
      'uniform vec2 shape;',
      'uniform vec3 front, up, right;',
      'void main() {',
      'vec2 uv = 2.0 * gl_FragCoord.xy / shape - 1.0;',
      'gl_FragColor = textureCube(tex, front + uv.x * right + uv.y * up);',
      '}'
    ].join('\n'),

    attributes: {
      position: [
        0, -4,
        -4, 4,
        4, 4
      ]
    },

    uniforms: {
      shape: regl.prop('shape'),
      tex: regl.prop('texture'),
      front: regl.prop('front'),
      up: regl.prop('up'),
      right: regl.prop('right')
    },

    depth: {enable: false},

    count: 3
  })

  function checkShouldThrow (name) {
    var args = Array.prototype.slice.call(arguments, 1)
    t.throws(function () {
      regl.cube.apply(null, args)
    }, /\(regl\)/, name + ' throws')
  }

  function comparePixels (texture, width, height, faces, tolerance, name) {
    createContext.resize(gl, width, height)
    regl._refresh()

    var axes = [
      [0, 1, -1, -1, 1, 2],
      [0, -1, -1, 1, 1, 2],
      [1, 1, 1, 1, 2, 0],
      [1, -1, -1, 1, 2, 0],
      [2, 1, -1, 1, 1, 0],
      [2, -1, -1, -1, 1, 0]
    ]

    for (var p = 0; p < axes.length; ++p) {
      var front = [0, 0, 0]
      var up = [0, 0, 0]
      var right = [0, 0, 0]
      var d = axes[p][0]
      front[d] = axes[p][1]
      up[axes[p][4]] = axes[p][2]
      right[axes[p][5]] = axes[p][3]

      renderCubeFace({
        texture: texture,
        shape: [width, height],
        front: front,
        up: up,
        right: right
      })

      var expected = faces[p]
      var actual = regl.read()
      t.equals(expected.length, actual.length,
        name + ', face ' + p + ' length')
      for (var i = 0; i < expected.length; ++i) {
        if (!(Math.abs(actual[i] - expected[i]) <= tolerance)) {
          t.fail(name + ', face: ' + p + ' @ index ' + i + ' ' + expected[i] + ' - ' + actual[i])
          return
        }
      }
    }
    t.pass(name)
  }

  function checkProperties (name, texture, props) {
    var width = props.width
    var height = props.height

    t.equals(texture.width, width, name + ' width')
    t.equals(texture.height, height, name + ' height')

    if ('faces' in props) {
      comparePixels(texture, width, height, props.faces, props.tolerance || 0,
        name + ' pixels')
    } else if ('mipmap' in props) {
      var mipmaps = props.mipmap
      for (var i = 0; i < mipmaps.length; ++i) {
        var w = width >> i
        var h = height >> i
        comparePixels(texture, w, h, mipmaps[i], props.tolerance || 0,
          name + ' mipmap ' + i)
      }
    }

    // check texture properties
    var mag = gl.getTexParameter(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER)
    var min = gl.getTexParameter(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER)

    t.equals(mag, props.magFilter || gl.NEAREST, name + ': mag filter')
    t.equals(min, props.minFilter || gl.NEAREST, name + ': min filter')

    if (regl.hasExtension('ext_texture_filter_anisotropic')) {
      var aniso = gl.getTexParameter(gl.TEXTURE_CUBE_MAP,
        gl.getExtension('ext_texture_filter_anisotropic').TEXTURE_MAX_ANISOTROPY_EXT)
      t.equals(aniso, props.anisotropic || 1, name + ': aniso ext')
    }
  }

  checkProperties('empty', regl.cube(), {
    width: 1,
    height: 1,
    faces: [
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0]
    ]
  })

  checkProperties('empty - object', regl.cube(), {
    width: 1,
    height: 1,
    faces: [
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0]
    ]
  })

  checkProperties('cube shape only', regl.cube(5), {
    width: 5,
    height: 5
  })

  checkShouldThrow('bad cube size', {
    width: 5,
    height: 2
  })

  // FIXME: seems like a headless-gl bug
  if (typeof document !== 'undefined') {
    checkProperties('cube colors', regl.cube(
      [[[255, 0, 0, 255]]],
      [[[0, 255, 0, 255]]],
      [[[0, 0, 255, 255]]],
      [[[0, 0, 0, 255]]],
      [[[255, 255, 0, 255]]],
      [[[0, 255, 255, 255]]]), {
        width: 1,
        height: 1,
        faces: [
          [255, 0, 0, 255],
          [0, 255, 0, 255],
          [0, 0, 255, 255],
          [0, 0, 0, 255],
          [255, 255, 0, 255],
          [0, 255, 255, 255]
        ]
      })

    checkProperties('cube colors - face map', regl.cube({
      faces: [
        [[[255, 0, 0, 255]]],
        [[[0, 255, 0, 255]]],
        [[[0, 0, 255, 255]]],
        [[[0, 0, 0, 255]]],
        [[[255, 0, 0, 255]]],
        [[[0, 255, 0, 255]]]
      ]
    }), {
      width: 1,
      height: 1,
      faces: [
        [255, 0, 0, 255],
        [0, 255, 0, 255],
        [0, 0, 255, 255],
        [0, 0, 0, 255],
        [255, 0, 0, 255],
        [0, 255, 0, 255]
      ]
    })
  }

  checkShouldThrow('inconsistent shapes',
    [[0]],
    [[1]],
    [[2, 2]],
    [[3]],
    [[4]],
    [[5]])

  checkShouldThrow('inconsistent formats',
    { radius: 2 },
    { radius: 2 },
    { radius: 2, channels: 1 },
    { radius: 2 },
    { radius: 2 },
    { radius: 2 })

  var testPattern = [
    255, 0, 0, 255, 0, 255, 0, 255,
    0, 0, 255, 255, 255, 255, 255, 0
  ]
  checkProperties('test data', regl.cube({
    width: 2,
    height: 2,
    data: testPattern
  }), {
    width: 2,
    height: 2,
    faces: [
      testPattern,
      testPattern,
      testPattern,
      testPattern,
      testPattern,
      testPattern
    ]
  })

  // copy
  createContext.resize(gl, 2, 2)
  regl._refresh()
  regl.clear({
    color: [0, 1, 1, 1]
  })
  checkProperties('copy tex image', regl.cube({
    radius: 2,
    faces: [
      { copy: true },
      { },
      { },
      { },
      { },
      { }
    ]
  }), {
    width: 2,
    height: 2,
    faces: [
      [
        0, 255, 255, 255, 0, 255, 255, 255,
        0, 255, 255, 255, 0, 255, 255, 255
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ]
    ]
  })

  // subimage
  var cube = regl.cube(2)
  cube.subimage(0, [
    255, 0, 0, 255, 255, 0, 0, 255,
    255, 0, 0, 255, 0, 0, 0, 255
  ])
  cube.subimage(1, [
    [ [0, 255, 0, 255], [0, 0, 0, 0] ],
    [ [0, 255, 0, 255], [0, 255, 0, 255] ]
  ])
  cube.subimage(2, [0, 0, 255, 255], 1, 1)
  regl.clear({
    color: [1, 1, 0, 1]
  })
  cube.subimage(4, {
    copy: true,
    width: 1,
    height: 1
  })
  regl.clear({
    color: [1, 0, 1, 1]
  })
  cube.subimage(5, {
    copy: true,
    width: 1,
    height: 1
  }, 1, 0)
  checkProperties('subimage', cube, {
    width: 2,
    height: 2,
    faces: [
      [
        255, 0, 0, 255, 255, 0, 0, 255,
        255, 0, 0, 255, 0, 0, 0, 255
      ],
      [
        0, 255, 0, 255, 0, 0, 0, 0,
        0, 255, 0, 255, 0, 255, 0, 255
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 255, 255
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        255, 255, 0, 255, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 255, 0, 255, 255,
        0, 0, 0, 0, 0, 0, 0, 0
      ]
    ]
  })

  // TODO mipmaps
  // TODO alignment and pixel storage
  // TODO float cube maps
  // TODO dom elements
  // TODO: test resize

  regl.destroy()
  createContext.destroy(gl)
  t.end()
})
<commit_msg>test/textureCube.js: Fix the test 'empty - object'<commit_after>var createContext = require('./util/create-context')
var createREGL = require('../../regl')
var tape = require('tape')

tape('texture cube', function (t) {
  var gl = createContext(16, 16)
  var regl = createREGL({
    gl: gl,
    optionalExtensions: ['ext_texture_filter_anisotropic']
  })

  var renderCubeFace = regl({
    vert: [
      'attribute vec2 position;',
      'void main() {',
      'gl_Position = vec4(position, 0, 1);',
      '}'
    ].join('\n'),

    frag: [
      'precision highp float;',
      'uniform samplerCube tex;',
      'uniform vec2 shape;',
      'uniform vec3 front, up, right;',
      'void main() {',
      'vec2 uv = 2.0 * gl_FragCoord.xy / shape - 1.0;',
      'gl_FragColor = textureCube(tex, front + uv.x * right + uv.y * up);',
      '}'
    ].join('\n'),

    attributes: {
      position: [
        0, -4,
        -4, 4,
        4, 4
      ]
    },

    uniforms: {
      shape: regl.prop('shape'),
      tex: regl.prop('texture'),
      front: regl.prop('front'),
      up: regl.prop('up'),
      right: regl.prop('right')
    },

    depth: {enable: false},

    count: 3
  })

  function checkShouldThrow (name) {
    var args = Array.prototype.slice.call(arguments, 1)
    t.throws(function () {
      regl.cube.apply(null, args)
    }, /\(regl\)/, name + ' throws')
  }

  function comparePixels (texture, width, height, faces, tolerance, name) {
    createContext.resize(gl, width, height)
    regl._refresh()

    var axes = [
      [0, 1, -1, -1, 1, 2],
      [0, -1, -1, 1, 1, 2],
      [1, 1, 1, 1, 2, 0],
      [1, -1, -1, 1, 2, 0],
      [2, 1, -1, 1, 1, 0],
      [2, -1, -1, -1, 1, 0]
    ]

    for (var p = 0; p < axes.length; ++p) {
      var front = [0, 0, 0]
      var up = [0, 0, 0]
      var right = [0, 0, 0]
      var d = axes[p][0]
      front[d] = axes[p][1]
      up[axes[p][4]] = axes[p][2]
      right[axes[p][5]] = axes[p][3]

      renderCubeFace({
        texture: texture,
        shape: [width, height],
        front: front,
        up: up,
        right: right
      })

      var expected = faces[p]
      var actual = regl.read()
      t.equals(expected.length, actual.length,
        name + ', face ' + p + ' length')
      for (var i = 0; i < expected.length; ++i) {
        if (!(Math.abs(actual[i] - expected[i]) <= tolerance)) {
          t.fail(name + ', face: ' + p + ' @ index ' + i + ' ' + expected[i] + ' - ' + actual[i])
          return
        }
      }
    }
    t.pass(name)
  }

  function checkProperties (name, texture, props) {
    var width = props.width
    var height = props.height

    t.equals(texture.width, width, name + ' width')
    t.equals(texture.height, height, name + ' height')

    if ('faces' in props) {
      comparePixels(texture, width, height, props.faces, props.tolerance || 0,
        name + ' pixels')
    } else if ('mipmap' in props) {
      var mipmaps = props.mipmap
      for (var i = 0; i < mipmaps.length; ++i) {
        var w = width >> i
        var h = height >> i
        comparePixels(texture, w, h, mipmaps[i], props.tolerance || 0,
          name + ' mipmap ' + i)
      }
    }

    // check texture properties
    var mag = gl.getTexParameter(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER)
    var min = gl.getTexParameter(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER)

    t.equals(mag, props.magFilter || gl.NEAREST, name + ': mag filter')
    t.equals(min, props.minFilter || gl.NEAREST, name + ': min filter')

    if (regl.hasExtension('ext_texture_filter_anisotropic')) {
      var aniso = gl.getTexParameter(gl.TEXTURE_CUBE_MAP,
        gl.getExtension('ext_texture_filter_anisotropic').TEXTURE_MAX_ANISOTROPY_EXT)
      t.equals(aniso, props.anisotropic || 1, name + ': aniso ext')
    }
  }

  checkProperties('empty', regl.cube(), {
    width: 1,
    height: 1,
    faces: [
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0]
    ]
  })

  checkProperties('empty - object', regl.cube({}), {
    width: 1,
    height: 1,
    faces: [
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0]
    ]
  })

  checkProperties('cube shape only', regl.cube(5), {
    width: 5,
    height: 5
  })

  checkShouldThrow('bad cube size', {
    width: 5,
    height: 2
  })

  // FIXME: seems like a headless-gl bug
  if (typeof document !== 'undefined') {
    checkProperties('cube colors', regl.cube(
      [[[255, 0, 0, 255]]],
      [[[0, 255, 0, 255]]],
      [[[0, 0, 255, 255]]],
      [[[0, 0, 0, 255]]],
      [[[255, 255, 0, 255]]],
      [[[0, 255, 255, 255]]]), {
        width: 1,
        height: 1,
        faces: [
          [255, 0, 0, 255],
          [0, 255, 0, 255],
          [0, 0, 255, 255],
          [0, 0, 0, 255],
          [255, 255, 0, 255],
          [0, 255, 255, 255]
        ]
      })

    checkProperties('cube colors - face map', regl.cube({
      faces: [
        [[[255, 0, 0, 255]]],
        [[[0, 255, 0, 255]]],
        [[[0, 0, 255, 255]]],
        [[[0, 0, 0, 255]]],
        [[[255, 0, 0, 255]]],
        [[[0, 255, 0, 255]]]
      ]
    }), {
      width: 1,
      height: 1,
      faces: [
        [255, 0, 0, 255],
        [0, 255, 0, 255],
        [0, 0, 255, 255],
        [0, 0, 0, 255],
        [255, 0, 0, 255],
        [0, 255, 0, 255]
      ]
    })
  }

  checkShouldThrow('inconsistent shapes',
    [[0]],
    [[1]],
    [[2, 2]],
    [[3]],
    [[4]],
    [[5]])

  checkShouldThrow('inconsistent formats',
    { radius: 2 },
    { radius: 2 },
    { radius: 2, channels: 1 },
    { radius: 2 },
    { radius: 2 },
    { radius: 2 })

  var testPattern = [
    255, 0, 0, 255, 0, 255, 0, 255,
    0, 0, 255, 255, 255, 255, 255, 0
  ]
  checkProperties('test data', regl.cube({
    width: 2,
    height: 2,
    data: testPattern
  }), {
    width: 2,
    height: 2,
    faces: [
      testPattern,
      testPattern,
      testPattern,
      testPattern,
      testPattern,
      testPattern
    ]
  })

  // copy
  createContext.resize(gl, 2, 2)
  regl._refresh()
  regl.clear({
    color: [0, 1, 1, 1]
  })
  checkProperties('copy tex image', regl.cube({
    radius: 2,
    faces: [
      { copy: true },
      { },
      { },
      { },
      { },
      { }
    ]
  }), {
    width: 2,
    height: 2,
    faces: [
      [
        0, 255, 255, 255, 0, 255, 255, 255,
        0, 255, 255, 255, 0, 255, 255, 255
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ]
    ]
  })

  // subimage
  var cube = regl.cube(2)
  cube.subimage(0, [
    255, 0, 0, 255, 255, 0, 0, 255,
    255, 0, 0, 255, 0, 0, 0, 255
  ])
  cube.subimage(1, [
    [ [0, 255, 0, 255], [0, 0, 0, 0] ],
    [ [0, 255, 0, 255], [0, 255, 0, 255] ]
  ])
  cube.subimage(2, [0, 0, 255, 255], 1, 1)
  regl.clear({
    color: [1, 1, 0, 1]
  })
  cube.subimage(4, {
    copy: true,
    width: 1,
    height: 1
  })
  regl.clear({
    color: [1, 0, 1, 1]
  })
  cube.subimage(5, {
    copy: true,
    width: 1,
    height: 1
  }, 1, 0)
  checkProperties('subimage', cube, {
    width: 2,
    height: 2,
    faces: [
      [
        255, 0, 0, 255, 255, 0, 0, 255,
        255, 0, 0, 255, 0, 0, 0, 255
      ],
      [
        0, 255, 0, 255, 0, 0, 0, 0,
        0, 255, 0, 255, 0, 255, 0, 255
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 255, 255
      ],
      [
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        255, 255, 0, 255, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0
      ],
      [
        0, 0, 0, 0, 255, 0, 255, 255,
        0, 0, 0, 0, 0, 0, 0, 0
      ]
    ]
  })

  // TODO mipmaps
  // TODO alignment and pixel storage
  // TODO float cube maps
  // TODO dom elements
  // TODO: test resize

  regl.destroy()
  createContext.destroy(gl)
  t.end()
})
<|endoftext|>


<commit_before>module("Main");

test("dominoes returns itself", function() {

	strictEqual( dominoes() , dominoes , "dominoes returns itself" );

} );

test("dominoes.run is an alias for dominoes", function() {

	strictEqual( dominoes.run , dominoes , "dominoes returns itself" );

} );

test("Function", function() {

	expect( 1 );

    dominoes( function() {
		ok( true , "function called");
	} );

});

test("Definition", function() {

	expect(2);

    dominoes( {

    	chain: "first second",

    	first: function() {
    		ok( true , "first method called");
    	},

    	second: function() {
    		ok( true , "second method called");
    	}

	} );

});

test("Serial execution" , function() {

	expect( 1 );

	stop();

	var string = "";

	dominoes( {

		chain: "first > second",

		first: function(callback) {
			setTimeout( function() {
				string += "first ";
				callback();
			}, 100);
			return false;
		},

		second: function() {
			string += "second";
		}

	}, function() {

		strictEqual( string , "first second" , "first method did block the second one" );
		start();

	});

});

test("Parallel execution" , function() {

	expect( 1 );

	stop();

	var string = "";

	dominoes( {

		chain: "first second",

		first: function(callback) {
			setTimeout( function() {
				string += " first";
				callback();
			}, 100);
			return false;
		},

		second: function() {
			string += "second";
		}

	}, function() {

		strictEqual( string , "second first" , "first method didn't block the second one" );
		start();

	});

});

test("Non blocking sub-expression" , function() {

	expect( 2 );

	stop();

	var string = "";

	dominoes( {

		chain: "(( first > restart )) second > third",

		first: function(callback) {
			setTimeout( function() {
				string += " first";
				callback();
			}, 100);
			return false;
		},

		second: function() {
			string += "second";
		},

		third: function() {
			string += " third";
		},

		restart: function() {
			strictEqual( string , "second third first" , "first method did block its sub-chain" );
			start();
		}

	}, function() {

		strictEqual( string , "second third" , "first method didn't block the main chain" );

	});

});

test("Multiple arguments", function() {

	expect( 2 );

	var i = 0;

    dominoes( function() {
    		equal( ++i , 1 , "first function called first");
    } , function() {
    		equal( ++i , 2 , "second function called second");
    });

});

test("Array" , function() {

	expect( 2 );

	var i = 0;

    dominoes( [ function() {
    		equal( ++i , 1 , "first function called first");
    },function() {
    		equal( ++i , 2 , "second function called second");
    } ] );

});

test("URL" , function() {

	expect( 1 );

	window.DOMINOES_UNIT_STRING = "";

	stop();

	dominoes( url ( "./data/concat.php?str=A&wait=200" ) , function() {
		equal( window.DOMINOES_UNIT_STRING , "A" , "URL has been loaded" );
		start();
	});

});

test("URL (cache)" , function() {

	expect( 2 );

	window.DOMINOES_UNIT_STRING = "";

	stop();

	var i, list;

	for ( i = 0 , list = [] ; i < 20 ; i++ ) {
		list.push( "./data/concat.php?str=URL_CACHE_TEST&wait=200" );
	}

	list.push( function() {
		equal( window.DOMINOES_UNIT_STRING , "URL_CACHE_TEST" , "URL has been loaded only once" );
		dominoes( "./data/concat.php?str=URL_CACHE_TEST&wait=200" , function() {
			equal( window.DOMINOES_UNIT_STRING , "URL_CACHE_TEST" , "Cache is consistant amongst calls" );
			start();
		} );
	} );

	dominoes( list );

});

test("URL (options object)" , function() {

	expect( 1 );

	window.DOMINOES_UNIT_STRING = "";

	stop();

	dominoes( {

		url : url ( "./data/concat.php?str=A&wait=200" )

	} , function() {
		equal( window.DOMINOES_UNIT_STRING , "A" , "URL has been loaded" );
		start();
	} );

});

test("URL (options object with cache = false)" , function() {

	expect( 2 );

	window.DOMINOES_UNIT_STRING = "";

	stop();

	dominoes( {

		url : "./data/concat.php?str=NO_CACHE&wait=100" ,
		cache : false

	} , function() {

		equal( window.DOMINOES_UNIT_STRING , "NO_CACHE" , "URL has been loaded once" );

	} , {

		url : "./data/concat.php?str=NO_CACHE&wait=100" ,
		cache : false

	} , function() {

		equal( window.DOMINOES_UNIT_STRING , "NO_CACHENO_CACHE" , "URL has been loaded twice" );
		start();

	} );

});

test("Function with callback handling", function() {

	expect( 3 );

	stop();

	var i = 0;

    dominoes( function( callback ) {
    		equal( ++i , 1 , "first function called first");
    		setTimeout( function() {
    			equal( ++i , 2 , "execution is still blocked");
    			callback();
    		}, 200);
    		return false;
    } , function() {
    		equal( ++i , 3 , "second function called after callback");
    		start();
    });

});

test("Definition context", function() {

	expect( 2 );

    dominoes( {

    	chain: "first > second",

    	first: function() {
    		equal( this.chain , "first > second" , "first method is in context" );
    		this.string = "Hello world";
    	},

    	second: function() {
    		equal( this.string , "Hello world" , "second method is in context");
    	}

	} );

});

test("Definition context (recursive)", function() {

	expect( 2 );

    dominoes( {

    	chain: "subChain",

    	subChain: "first > second",

    	first: function() {
    		equal( this.chain , "subChain" , "first method is in context" );
    		this.string = "Hello world";
    	},

    	second: function() {
    		equal( this.string , "Hello world" , "second method is in context");
    	}

	} );

});

for ( var delay = 0 ; delay < 3 ; delay++ ) {

	( function( delay ) {

		test("Dom readyness detection (" + delay + "s delay)" , function() {

			expect( 3 )

			stop();

			window.notifyFrameReady = function( elem , duration ) {
				ok( elem , "Document was ready" );
				strictEqual( elem && elem.innerHTML , "WORLD" , "Document was ready and parsed" );
				ok( duration < ( delay + 1 ) * 1000 , "Image didn't block the event (delay to event was " + duration / 1000 + " seconds)" );
				start();
			};

			var iframe = document.createElement("iframe");

			iframe.src = url( "data/readyTest.php?delay=" + delay );

			( document.getElementsByTagName("head")[ 0 ] || document.documentElement ).appendChild( iframe );

		});

	} )( delay );

}
<commit_msg>Added a larger margin of error to control if the image blocks the DOM readyness event (just had a "latency" problem in gecko).<commit_after>module("Main");

test("dominoes returns itself", function() {

	strictEqual( dominoes() , dominoes , "dominoes returns itself" );

} );

test("dominoes.run is an alias for dominoes", function() {

	strictEqual( dominoes.run , dominoes , "dominoes returns itself" );

} );

test("Function", function() {

	expect( 1 );

    dominoes( function() {
		ok( true , "function called");
	} );

});

test("Definition", function() {

	expect(2);

    dominoes( {

    	chain: "first second",

    	first: function() {
    		ok( true , "first method called");
    	},

    	second: function() {
    		ok( true , "second method called");
    	}

	} );

});

test("Serial execution" , function() {

	expect( 1 );

	stop();

	var string = "";

	dominoes( {

		chain: "first > second",

		first: function(callback) {
			setTimeout( function() {
				string += "first ";
				callback();
			}, 100);
			return false;
		},

		second: function() {
			string += "second";
		}

	}, function() {

		strictEqual( string , "first second" , "first method did block the second one" );
		start();

	});

});

test("Parallel execution" , function() {

	expect( 1 );

	stop();

	var string = "";

	dominoes( {

		chain: "first second",

		first: function(callback) {
			setTimeout( function() {
				string += " first";
				callback();
			}, 100);
			return false;
		},

		second: function() {
			string += "second";
		}

	}, function() {

		strictEqual( string , "second first" , "first method didn't block the second one" );
		start();

	});

});

test("Non blocking sub-expression" , function() {

	expect( 2 );

	stop();

	var string = "";

	dominoes( {

		chain: "(( first > restart )) second > third",

		first: function(callback) {
			setTimeout( function() {
				string += " first";
				callback();
			}, 100);
			return false;
		},

		second: function() {
			string += "second";
		},

		third: function() {
			string += " third";
		},

		restart: function() {
			strictEqual( string , "second third first" , "first method did block its sub-chain" );
			start();
		}

	}, function() {

		strictEqual( string , "second third" , "first method didn't block the main chain" );

	});

});

test("Multiple arguments", function() {

	expect( 2 );

	var i = 0;

    dominoes( function() {
    		equal( ++i , 1 , "first function called first");
    } , function() {
    		equal( ++i , 2 , "second function called second");
    });

});

test("Array" , function() {

	expect( 2 );

	var i = 0;

    dominoes( [ function() {
    		equal( ++i , 1 , "first function called first");
    },function() {
    		equal( ++i , 2 , "second function called second");
    } ] );

});

test("URL" , function() {

	expect( 1 );

	window.DOMINOES_UNIT_STRING = "";

	stop();

	dominoes( url ( "./data/concat.php?str=A&wait=200" ) , function() {
		equal( window.DOMINOES_UNIT_STRING , "A" , "URL has been loaded" );
		start();
	});

});

test("URL (cache)" , function() {

	expect( 2 );

	window.DOMINOES_UNIT_STRING = "";

	stop();

	var i, list;

	for ( i = 0 , list = [] ; i < 20 ; i++ ) {
		list.push( "./data/concat.php?str=URL_CACHE_TEST&wait=200" );
	}

	list.push( function() {
		equal( window.DOMINOES_UNIT_STRING , "URL_CACHE_TEST" , "URL has been loaded only once" );
		dominoes( "./data/concat.php?str=URL_CACHE_TEST&wait=200" , function() {
			equal( window.DOMINOES_UNIT_STRING , "URL_CACHE_TEST" , "Cache is consistant amongst calls" );
			start();
		} );
	} );

	dominoes( list );

});

test("URL (options object)" , function() {

	expect( 1 );

	window.DOMINOES_UNIT_STRING = "";

	stop();

	dominoes( {

		url : url ( "./data/concat.php?str=A&wait=200" )

	} , function() {
		equal( window.DOMINOES_UNIT_STRING , "A" , "URL has been loaded" );
		start();
	} );

});

test("URL (options object with cache = false)" , function() {

	expect( 2 );

	window.DOMINOES_UNIT_STRING = "";

	stop();

	dominoes( {

		url : "./data/concat.php?str=NO_CACHE&wait=100" ,
		cache : false

	} , function() {

		equal( window.DOMINOES_UNIT_STRING , "NO_CACHE" , "URL has been loaded once" );

	} , {

		url : "./data/concat.php?str=NO_CACHE&wait=100" ,
		cache : false

	} , function() {

		equal( window.DOMINOES_UNIT_STRING , "NO_CACHENO_CACHE" , "URL has been loaded twice" );
		start();

	} );

});

test("Function with callback handling", function() {

	expect( 3 );

	stop();

	var i = 0;

    dominoes( function( callback ) {
    		equal( ++i , 1 , "first function called first");
    		setTimeout( function() {
    			equal( ++i , 2 , "execution is still blocked");
    			callback();
    		}, 200);
    		return false;
    } , function() {
    		equal( ++i , 3 , "second function called after callback");
    		start();
    });

});

test("Definition context", function() {

	expect( 2 );

    dominoes( {

    	chain: "first > second",

    	first: function() {
    		equal( this.chain , "first > second" , "first method is in context" );
    		this.string = "Hello world";
    	},

    	second: function() {
    		equal( this.string , "Hello world" , "second method is in context");
    	}

	} );

});

test("Definition context (recursive)", function() {

	expect( 2 );

    dominoes( {

    	chain: "subChain",

    	subChain: "first > second",

    	first: function() {
    		equal( this.chain , "subChain" , "first method is in context" );
    		this.string = "Hello world";
    	},

    	second: function() {
    		equal( this.string , "Hello world" , "second method is in context");
    	}

	} );

});

for ( var delay = 0 ; delay < 3 ; delay++ ) {

	( function( delay ) {

		test("Dom readyness detection (" + delay + "s delay)" , function() {

			expect( 3 )

			stop();

			window.notifyFrameReady = function( elem , duration ) {
				ok( elem , "Document was ready" );
				strictEqual( elem && elem.innerHTML , "WORLD" , "Document was ready and parsed" );
				ok( duration < ( delay + 3 ) * 1000 , "Image didn't block the event (delay to event was " + duration / 1000 + " seconds)" );
				start();
			};

			var iframe = document.createElement("iframe");

			iframe.src = url( "data/readyTest.php?delay=" + delay );

			( document.getElementsByTagName("head")[ 0 ] || document.documentElement ).appendChild( iframe );

		});

	} )( delay );

}
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var logger = require('../..');

describe('cli-logger:', function() {
  it('should decorate json with properties', function(done) {
    var name = 'mock-object-logger';
    var conf = {name: name, json: true, streams: [{path: 'log/mock-write.log'}]};
    var log = logger(conf);
    log.on('write', function(record, stream) {
      expect(record.req).to.be.an('object');
      expect(record.req.path).to.eql('/');
      done();
    })
    log.info({req: {path: '/'}});
  });
  it('should decorate json with properties (custom message)', function(done) {
    var msg = 'mock info message';
    var name = 'mock-object-logger';
    var conf = {name: name, json: true, streams: [{path: 'log/mock-write.log'}]};
    var log = logger(conf);
    log.on('write', function(record, stream) {
      expect(record.msg).to.eql(msg);
      expect(record.req).to.be.an('object');
      expect(record.req.path).to.eql('/');
      done();
    })
    log.info({req: {path: '/'}}, msg);
  });
})
<commit_msg>Assert on object plus message with parameters.<commit_after>var expect = require('chai').expect;
var logger = require('../..');

describe('cli-logger:', function() {
  it('should decorate json with properties', function(done) {
    var name = 'mock-object-logger';
    var conf = {name: name, json: true, streams: [{path: 'log/mock-write.log'}]};
    var log = logger(conf);
    log.on('write', function(record, stream) {
      expect(record.req).to.be.an('object');
      expect(record.req.path).to.eql('/');
      done();
    })
    log.info({req: {path: '/'}});
  });
  it('should decorate json with properties (message)', function(done) {
    var msg = 'mock info message';
    var name = 'mock-object-logger';
    var conf = {name: name, json: true, streams: [{path: 'log/mock-write.log'}]};
    var log = logger(conf);
    log.on('write', function(record, stream) {
      expect(record.msg).to.eql(msg);
      expect(record.req).to.be.an('object');
      expect(record.req.path).to.eql('/');
      done();
    })
    log.info({req: {path: '/'}}, msg);
  });
  it('should decorate json with properties (message+parameters)', function(done) {
    var expected = 'mock info message';
    var name = 'mock-object-logger';
    var conf = {name: name, json: true, streams: [{path: 'log/mock-write.log'}]};
    var log = logger(conf);
    log.on('write', function(record, stream) {
      expect(record.msg).to.eql(expected);
      expect(record.req).to.be.an('object');
      expect(record.req.path).to.eql('/');
      done();
    })
    log.info({req: {path: '/'}}, 'mock %s message', 'info');
  });
})
<|endoftext|>


<commit_before>var Assert = require('assert');
var Queue = require('../index');

describe.skip("Control", function() {
	it("hasn't had tests written yet...");
});
<commit_msg>Some flow-control tests<commit_after>var Assert = require('assert');
var Queue = require('../index');

describe("Control", function() {
	var flood = 16;
	var drain = 5;

	var queue = new Queue({
		paused : true,
		flood : flood,
		drain : drain
	});

	queue.worker = function(task, done) {
		done(null, {
			sum : task.a + task.b
		});
	};

	var tasks = [], count = 500, shouldBe = 0;
	for ( var i = 0; i < count; i++) {
		tasks.push({
			a : Math.floor(Math.random() * 6) + 1,
			b : Math.floor(Math.random() * 6) + 1
		});
	}

	describe("Setup", function() {
		it("new queue has correct initial values", function() {
			Assert.ok(queue.paused, "Not paused");
			Assert.equal(queue.flood, flood, "Wrong flood threshold");
			Assert.equal(queue.drain, drain, "Wrong drain threshold");
		});
		it(count + " test tasks have been generated", function() {
			Assert.equal(tasks.length, count);
		});
	});

	describe("Concurrency", function() {
		var concurrency = 16;
		queue.concurrency = concurrency;

		it("should run " + concurrency + " parallel tasks", function() {
			queue.push(tasks.splice(0, 64));
			queue.resume();

			process.nextTick(function() {
				Assert.equal(queue.running, concurrency);
			});
		});
	});

	describe("Callbacks", function() {
		it("should call the task's callback", function(done) {
			queue.buffer(tasks.shift(), function(err, res) {
				if(err) {
					done(err);
					return;
				}

				done();
			});
		});
	});

	describe("Worker", function() {
		it("should use an overriding work functon", function(done) {
			queue.buffer(tasks.shift(), function(err, res) {
				if(err) {
					done(err);
					return;
				}

				try {
					Assert.notEqual(typeof res.diff, "undefined");
					done();
				} catch(e) {
					done(e);
				}
			}, null, function(task, done) {
				done(null, {
					diff : task.a - task.b
				});
			});
		});
	});
});
<|endoftext|>