<commit_before>'use strict';

// Load modules

const Fs = require('fs');
const Os = require('os');
const Path = require('path');
const _Lab = require('../test_runner');
const Code = require('code');
const Linters = require('../lib/lint');

// Test shortcuts

const lab = exports.lab = _Lab.script();
const describe = lab.describe;
const it = lab.it;
const expect = Code.expect;

describe('Linters - eslint', () => {

    it('should lint files in a folder', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'basic');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile).to.include({ filename: Path.join(path, 'fail.js') });
        expect(checkedFile.errors).to.include([
            { line: 13, severity: 'ERROR', message: 'semi - Missing semicolon.' },
            { line: 14, severity: 'WARNING', message: 'eol-last - Newline required at end of file but not found.' }
        ]);
    });

    it('should default to eslint', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'basic');
        const result = await Linters.lint({ lintingPath: path });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile).to.include({ filename: Path.join(path, 'fail.js') });
        expect(checkedFile.errors).to.include([
            { line: 13, severity: 'ERROR', message: 'semi - Missing semicolon.' },
            { line: 14, severity: 'WARNING', message: 'eol-last - Newline required at end of file but not found.' }
        ]);
    });

    it('should use local configuration files', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'with_config');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile).to.include({ filename: Path.join(path, 'fail.js') });
        expect(checkedFile.errors).to.include([
            { line: 14, severity: 'ERROR', message: 'eol-last - Newline required at end of file but not found.' }]);
        expect(checkedFile.errors).to.not.include({ line: 8, severity: 'ERROR', message: 'no-unused-vars - internals is defined but never used' });
    });

    it('displays success message if no issues found', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'clean');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result.lint).to.exist();

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile.errors.length).to.equal(0);
    });

    it('allows err to be shadowed', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'shadow');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result.lint).to.exist();

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile.errors.length).to.equal(0);
    });

    it('doesn\'t allow res to be shadowed', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'shadow-res');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result.lint).to.exist();

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile.errors.length).to.equal(1);
    });

    it('allows object rest/spread properties', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'object-rest-spread');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result.lint).to.exist();

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile.errors.length).to.equal(0);
    });

    it('should pass options and not find any files', async () => {

        const lintOptions = JSON.stringify({ extensions: ['.jsx'] });
        const path = Path.join(__dirname, 'lint', 'eslint', 'basic');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint', 'lint-options': lintOptions });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);
        expect(eslintResults[0].errors[0].message).to.contain('No files');
    });

    it('should fix lint rules when --lint-fix used', async (flags) => {

        let isFixed = false;
        const originalWriteFileSync = Fs.writeFileSync;

        flags.onCleanup = () => {

            Fs.writeFileSync = originalWriteFileSync;
        };

        Fs.writeFileSync = (path, output) => {

            expect(path).to.endWith(Path.join('test', 'lint', 'eslint', 'fix', 'success.js'));

            expect(output).to.endWith(Os.EOL + '    return value;' + Os.EOL + '};' + Os.EOL);
            isFixed = true;
        };

        const path = Path.join(__dirname, 'lint', 'eslint', 'fix');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint', 'lint-fix': true });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);
        expect(eslintResults[0]).to.include({
            totalErrors: 0,
            totalWarnings: 1
        });
        expect(isFixed, 'Lint updates not written').to.be.true();
    });

    it('should error on malformed lint-options', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'fix');

        try {
            await Linters.lint({ lintingPath: path, linter: 'eslint', 'lint-options': '}' });
        }
        catch (ex) {
            expect(ex.message).to.equal('lint-options could not be parsed');
        }
    });
});

describe('Linters - custom', () => {

    it('can run custom linter', async () => {

        const path = Path.join(__dirname, 'lint');
        const result = await Linters.lint({ lintingPath: path, linter: Path.join(__dirname, 'lint', 'custom') });

        expect(result).to.include('lint');

        const results = result.lint;
        expect(results).to.have.length(1);

        const checkedFile = results[0];
        expect(checkedFile.filename).to.equal('custom');
        expect(checkedFile.errors.length).to.equal(1);
    });
});
<commit_msg>Fix lint and switch to use regex matching instead of endsWith/Os.EOL in output tests.<commit_after>'use strict';

// Load modules

const Fs = require('fs');
const Path = require('path');
const _Lab = require('../test_runner');
const Code = require('code');
const Linters = require('../lib/lint');

// Test shortcuts

const lab = exports.lab = _Lab.script();
const describe = lab.describe;
const it = lab.it;
const expect = Code.expect;

describe('Linters - eslint', () => {

    it('should lint files in a folder', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'basic');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile).to.include({ filename: Path.join(path, 'fail.js') });
        expect(checkedFile.errors).to.include([
            { line: 13, severity: 'ERROR', message: 'semi - Missing semicolon.' },
            { line: 14, severity: 'WARNING', message: 'eol-last - Newline required at end of file but not found.' }
        ]);
    });

    it('should default to eslint', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'basic');
        const result = await Linters.lint({ lintingPath: path });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile).to.include({ filename: Path.join(path, 'fail.js') });
        expect(checkedFile.errors).to.include([
            { line: 13, severity: 'ERROR', message: 'semi - Missing semicolon.' },
            { line: 14, severity: 'WARNING', message: 'eol-last - Newline required at end of file but not found.' }
        ]);
    });

    it('should use local configuration files', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'with_config');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile).to.include({ filename: Path.join(path, 'fail.js') });
        expect(checkedFile.errors).to.include([
            { line: 14, severity: 'ERROR', message: 'eol-last - Newline required at end of file but not found.' }]);
        expect(checkedFile.errors).to.not.include({ line: 8, severity: 'ERROR', message: 'no-unused-vars - internals is defined but never used' });
    });

    it('displays success message if no issues found', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'clean');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result.lint).to.exist();

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile.errors.length).to.equal(0);
    });

    it('allows err to be shadowed', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'shadow');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result.lint).to.exist();

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile.errors.length).to.equal(0);
    });

    it('doesn\'t allow res to be shadowed', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'shadow-res');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result.lint).to.exist();

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile.errors.length).to.equal(1);
    });

    it('allows object rest/spread properties', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'object-rest-spread');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint' });

        expect(result.lint).to.exist();

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);

        const checkedFile = eslintResults[0];
        expect(checkedFile.errors.length).to.equal(0);
    });

    it('should pass options and not find any files', async () => {

        const lintOptions = JSON.stringify({ extensions: ['.jsx'] });
        const path = Path.join(__dirname, 'lint', 'eslint', 'basic');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint', 'lint-options': lintOptions });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);
        expect(eslintResults[0].errors[0].message).to.contain('No files');
    });

    it('should fix lint rules when --lint-fix used', async (flags) => {

        let isFixed = false;
        const originalWriteFileSync = Fs.writeFileSync;

        flags.onCleanup = () => {

            Fs.writeFileSync = originalWriteFileSync;
        };

        Fs.writeFileSync = (path, output) => {

            expect(path).to.endWith(Path.join('test', 'lint', 'eslint', 'fix', 'success.js'));
            expect(output).to.match(/\r?\n    return value;\r?\n\};\r?\n/);
            isFixed = true;
        };

        const path = Path.join(__dirname, 'lint', 'eslint', 'fix');
        const result = await Linters.lint({ lintingPath: path, linter: 'eslint', 'lint-fix': true });

        expect(result).to.include('lint');

        const eslintResults = result.lint;
        expect(eslintResults).to.have.length(1);
        expect(eslintResults[0]).to.include({
            totalErrors: 0,
            totalWarnings: 1
        });
        expect(isFixed, 'Lint updates not written').to.be.true();
    });

    it('should error on malformed lint-options', async () => {

        const path = Path.join(__dirname, 'lint', 'eslint', 'fix');

        try {
            await Linters.lint({ lintingPath: path, linter: 'eslint', 'lint-options': '}' });
        }
        catch (ex) {
            expect(ex.message).to.equal('lint-options could not be parsed');
        }
    });
});

describe('Linters - custom', () => {

    it('can run custom linter', async () => {

        const path = Path.join(__dirname, 'lint');
        const result = await Linters.lint({ lintingPath: path, linter: Path.join(__dirname, 'lint', 'custom') });

        expect(result).to.include('lint');

        const results = result.lint;
        expect(results).to.have.length(1);

        const checkedFile = results[0];
        expect(checkedFile.filename).to.equal('custom');
        expect(checkedFile.errors.length).to.equal(1);
    });
});
<|endoftext|>


<commit_before>var restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    uuid = require('node-uuid'),
    neo4j = require('node-neo4j'),
    Promise = require('promise');
module.exports.offers = (function() {
    //Some handy variables
    var rand = uuid.v1(),
        db = new neo4j('http://localhost:7474');
    return {
        addOffer: function(req, res, next) {
            console.log('NEW OFFER!');
            //Set variables from params
            var businessName = req.params.businessname;
            var description = req.params.description;
            var offertitle = req.params.title + ' - ' + businessName;
            var offerCost = req.params.cost;
            var nodeid = 0;
            //Build date and time
            var d = new Date();
            var date = d.toUTCString();
            //URL for when offer will be stored in CouchDB
            var url = 'http://localhost:5984/offers/' + offertitle;
            //Make a new promise by getting the URL
            getRequest(url).
            catch(function(err) {
                //If there is a error getting the document from within the promise
                console.log("GET request error on couchDB document")
                return next(new restify.InternalServerError('Error communicating with CouchDB'));
            }).then(function(call) {
                // if the document isnt found it will create it from sratch
                console.log('CouchDB request statuscode - ' + call.response.statusCode)
                if(call.response.statusCode === 200) {
                    return next(new restify.ConflictError('Offer has already been created with the same name'));
                }
                return call
            }).then(function(call) {
                console.log(call)
                //Insert node into neo4j
                if(call.response.statusCode === 404) {
                    //Insert node into neo4j
                    db.insertNode({
                        name: offertitle
                    }, ['Offer', businessName], function(err, node) {
                        if(err) throw err;
                        // Output node properties.
                        console.log('New neo4j node created with name = ' + node.name);
                        nodeid = node._id
                    })
                    var doc = {
                        date_created: date,
                        last_modified: date,
                        offer_title: offertitle,
                        offer_description: description,
                        offer_cost: offerCost,
                        businessname: businessName,
                        redeems: [],
                        nodeid: nodeid
                    };
                    return doc
                }
            }).then(function(doc) {
                console.log(doc)
                var params = {
                    uri: url,
                    body: JSON.stringify(doc)
                };
                request.put(params, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant create document in CouchDB'));
                    }
                    // document has been inserted into database
                    res.setHeader('Location', 'http://' + req.headers.host + req.url);
                    res.setHeader('Last-Modified', date);
                    res.setHeader('Content-Type', 'application/json');
                    var sendBack = {
                        Added: 'OK',
                        Offer_Title: offertitle,
                        Offer_Description: description,
                        Date_Added: date
                    }
                    res.send(201, sendBack);
                    res.end();
                })
            })
        },
        getAllOffers: function(req, res, next) {
            //Set business name
            var business = req.params.businessname;
            if(business == 'all') {
                var url = 'http://localhost:5984/offers/_design/offers/_view/all';
            } else {
                var url = 'http://localhost:5984/offers/_design/offers/_view/business?startkey="' + business + '"&endkey="' + business + '"';
            };
            getRequest(url).
            catch(function(err) {
                console.log("GET request error on couchDB document")
                return next(new restify.InternalServerError('Error communicating with CouchDB'));
            }).then(function(call) {
                if(call.response.statusCode === 404) {
                    return next(new restify.InternalServerError('No Offers Found'));
                } else if(call.response.statusCode === 200) {
                    var resp = JSON.parse(call.body)
                    var allOffers = [];
                    resp.rows.forEach(function(i) {
                        var offer = {
                            title: i.value.offer_title,
                            description: i.value.offer_description,
                            points_cost: i.value.offer_cost,
                            businessname: i.value.businessname,
                            last_modified: i.value.last_modified
                        };
                        console.log(offer)
                        allOffers.push(offer);
                    });
                    var offers = {
                        total_Offers: resp.rows.length,
                        offers: allOffers
                    }
                    res.send(offers);
                    res.end()
                }
            })
        },
        redeemOffer: function(req, res, next) {
            console.log('REDEEM OFFER!');
            //Set username from auth header
            var username = req.authorization.basic.username;
            //Get offerTitle from params
            var offerTitle = req.params.offerTitle;
            var offerUrl = 'http://localhost:5984/offers/' + offerTitle;
            var userUrl = 'http://localhost:5984/users/' + username;
            //Create the offer variables which are used in promises
            var offer, user, cost, businessName, totalPoints;
            //Build the transaction variables
            var d = new Date(),
                date = d.toUTCString(),
                txID = uuid.v1();
            //Get back to here
            var that = this;
            //Check to make sure offer title has been sent in the body params
            if(typeof offerTitle == 'undefined') {
                return next(new restify.NotAcceptableError('Please supply an offer title'));
            };
            //Get the offer URL
            getRequest(offerUrl).
            catch(function(err) {
                console.log("GET request error on couchDB document")
                return next(new restify.InternalServerError('Error communicating with CouchDB'));
            }).then(function(call) {
                //If offer not found
                if(call.response.statusCode === 404) {
                    return next(new restify.NotFoundError('Offer Not Found'));
                };
                if(call.response.statusCode === 200) {
                    //Set offer variable as whats returned from the GET Offer
                    offer = JSON.parse(call.body);
                    //Take some values from the offer
                    businessName = offer.businessname;
                    cost = offer.cost;
                    request.get(userUrl, function(err, response, doc) {
                        //If no user exists
                        if(response.statusCode === 404) {
                            return next(new restify.NotFoundError('User Not Found'));
                        };
                        if(response.statusCode === 200) {
                            user = JSON.parse(doc);
                            console.log(user)
                        }
                    })
                }
            }).then(function() {
                //Checks to see if user has enough points
                if((user.points - cost) < 0) {
                    console.log("You don't have enough points sunshine - come back another day :D")
                    return next(new restify.ForbiddenError("You don't have enough points to redeem this offer"));
                }
            }).then(function() {
                //Get users transaction and points
                user.points = user.points - cost;
                totalPoints = user.points;
                user.transactions.push({
                    transactionid: txID,
                    date: date,
                    amount_of_points: (cost - (cost * 2)),
                    business_redeemed: businessName
                })
                console.log(username + " now has " + totalPoints + " points");
                //Build the object for sending to couchDB
                var userParams = {
                    uri: userUrl,
                    body: JSON.stringify(user)
                };
                //Add the transaction to couchDB for user
                request.put(userParams, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant Update users CouchDB document'));
                    }
                    console.log("Added new transaction for" + username)
                })
            }).then(function() {
                offer.redeems.push({
                    transactionid: txID,
                    date: date,
                    amount_of_points: (cost - (cost * 2)),
                    user_redeemed: username
                })
                var redeemParams = {
                    uri: offerUrl,
                    body: JSON.stringify(offer)
                };
                request.put(redeemParams, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant Update CouchDB document'));
                    }
                    // document has been inserted into database
                    res.setHeader('Last-Modified', date);
                    res.setHeader('Content-Type', 'application/json');
                    res.setHeader('Accepts', 'PUT');
                    var sendBack = {
                        Redeem: 'OK',
                        username: username,
                        business: businessName,
                        points_taken: cost,
                        total_points: totalPoints
                    }
                    res.send(202, sendBack);
                    res.end();
                })
            })
        },
        getRequest: function(url) {
            // set up initial get request.
            return new Promise(function(resolve, reject) {
                request.get(url, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        putRequest: function(params) {
            return new Promise(function(resolve, reject) {
                request.put(params, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        }
    }
})();<commit_msg>Added var that = this to try and get back to closure<commit_after>var restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    uuid = require('node-uuid'),
    neo4j = require('node-neo4j'),
    Promise = require('promise');
module.exports.offers = (function() {
    //Some handy variables
    var rand = uuid.v1(),
        db = new neo4j('http://localhost:7474');
    return {
        addOffer: function(req, res, next) {
            console.log('NEW OFFER!');
            //Set variables from params
            var businessName = req.params.businessname;
            var description = req.params.description;
            var offertitle = req.params.title + ' - ' + businessName;
            var offerCost = req.params.cost;
            var nodeid = 0;
            //Build date and time
            var d = new Date();
            var date = d.toUTCString();
            //URL for when offer will be stored in CouchDB
            var url = 'http://localhost:5984/offers/' + offertitle;
            //Make a new promise by getting the URL
            getRequest(url).
            catch(function(err) {
                //If there is a error getting the document from within the promise
                console.log("GET request error on couchDB document")
                return next(new restify.InternalServerError('Error communicating with CouchDB'));
            }).then(function(call) {
                // if the document isnt found it will create it from sratch
                console.log('CouchDB request statuscode - ' + call.response.statusCode)
                if(call.response.statusCode === 200) {
                    return next(new restify.ConflictError('Offer has already been created with the same name'));
                }
                return call
            }).then(function(call) {
                console.log(call)
                //Insert node into neo4j
                if(call.response.statusCode === 404) {
                    //Insert node into neo4j
                    db.insertNode({
                        name: offertitle
                    }, ['Offer', businessName], function(err, node) {
                        if(err) throw err;
                        // Output node properties.
                        console.log('New neo4j node created with name = ' + node.name);
                        nodeid = node._id
                    })
                    var doc = {
                        date_created: date,
                        last_modified: date,
                        offer_title: offertitle,
                        offer_description: description,
                        offer_cost: offerCost,
                        businessname: businessName,
                        redeems: [],
                        nodeid: nodeid
                    };
                    return doc
                }
            }).then(function(doc) {
                console.log(doc)
                var params = {
                    uri: url,
                    body: JSON.stringify(doc)
                };
                request.put(params, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant create document in CouchDB'));
                    }
                    // document has been inserted into database
                    res.setHeader('Location', 'http://' + req.headers.host + req.url);
                    res.setHeader('Last-Modified', date);
                    res.setHeader('Content-Type', 'application/json');
                    var sendBack = {
                        Added: 'OK',
                        Offer_Title: offertitle,
                        Offer_Description: description,
                        Date_Added: date
                    }
                    res.send(201, sendBack);
                    res.end();
                })
            })
        },
        getAllOffers: function(req, res, next) {
            //Set business name
            var business = req.params.businessname;
            if(business == 'all') {
                var url = 'http://localhost:5984/offers/_design/offers/_view/all';
            } else {
                var url = 'http://localhost:5984/offers/_design/offers/_view/business?startkey="' + business + '"&endkey="' + business + '"';
            };
            getRequest(url).
            catch(function(err) {
                console.log("GET request error on couchDB document")
                return next(new restify.InternalServerError('Error communicating with CouchDB'));
            }).then(function(call) {
                if(call.response.statusCode === 404) {
                    return next(new restify.InternalServerError('No Offers Found'));
                } else if(call.response.statusCode === 200) {
                    var resp = JSON.parse(call.body)
                    var allOffers = [];
                    resp.rows.forEach(function(i) {
                        var offer = {
                            title: i.value.offer_title,
                            description: i.value.offer_description,
                            points_cost: i.value.offer_cost,
                            businessname: i.value.businessname,
                            last_modified: i.value.last_modified
                        };
                        console.log(offer)
                        allOffers.push(offer);
                    });
                    var offers = {
                        total_Offers: resp.rows.length,
                        offers: allOffers
                    }
                    res.send(offers);
                    res.end()
                }
            })
        },
        redeemOffer: function(req, res, next) {
            console.log('REDEEM OFFER!');
            //Set username from auth header
            var username = req.authorization.basic.username;
            //Get offerTitle from params
            var offerTitle = req.params.offerTitle;
            var offerUrl = 'http://localhost:5984/offers/' + offerTitle;
            var userUrl = 'http://localhost:5984/users/' + username;
            //Create the offer variables which are used in promises
            var offer, user, cost, businessName, totalPoints;
            //Build the transaction variables
            var d = new Date(),
                date = d.toUTCString(),
                txID = uuid.v1();
            //Check to make sure offer title has been sent in the body params
            if(typeof offerTitle == 'undefined') {
                return next(new restify.NotAcceptableError('Please supply an offer title'));
            };
            //Get the offer URL
            getRequest(offerUrl).
            catch(function(err) {
                console.log("GET request error on couchDB document")
                return next(new restify.InternalServerError('Error communicating with CouchDB'));
            }).then(function(call) {
                //If offer not found
                if(call.response.statusCode === 404) {
                    return next(new restify.NotFoundError('Offer Not Found'));
                };
                if(call.response.statusCode === 200) {
                    //Set offer variable as whats returned from the GET Offer
                    offer = JSON.parse(call.body);
                    //Take some values from the offer
                    businessName = offer.businessname;
                    cost = offer.cost;
                    request.get(userUrl, function(err, response, doc) {
                        //If no user exists
                        if(response.statusCode === 404) {
                            return next(new restify.NotFoundError('User Not Found'));
                        };
                        if(response.statusCode === 200) {
                            user = JSON.parse(doc);
                        }
                    })
                }
            }).then(function() {
                //Checks to see if user has enough points
                if((user.points - cost) < 0) {
                    console.log("You don't have enough points sunshine - come back another day :D")
                    return next(new restify.ForbiddenError("You don't have enough points to redeem this offer"));
                }
            }).then(function() {
                //Get users transaction and points
                user.points = user.points - cost;
                console.log(user.points);
                totalPoints = user.points;
                console.log(totalPoints);
                user.transactions.push({
                    transactionid: txID,
                    date: date,
                    amount_of_points: (cost - (cost * 2)),
                    business_redeemed: businessName
                })
                console.log(username + " now has " + totalPoints + " points");
                //Build the object for sending to couchDB
                var userParams = {
                    uri: userUrl,
                    body: JSON.stringify(user)
                };
                //Add the transaction to couchDB for user
                request.put(userParams, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant Update users CouchDB document'));
                    }
                    console.log("Added new transaction for" + username)
                })
            }).then(function() {
                offer.redeems.push({
                    transactionid: txID,
                    date: date,
                    amount_of_points: (cost - (cost * 2)),
                    user_redeemed: username
                })
                var redeemParams = {
                    uri: offerUrl,
                    body: JSON.stringify(offer)
                };
                request.put(redeemParams, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant Update CouchDB document'));
                    }
                    // document has been inserted into database
                    res.setHeader('Last-Modified', date);
                    res.setHeader('Content-Type', 'application/json');
                    res.setHeader('Accepts', 'PUT');
                    var sendBack = {
                        Redeem: 'OK',
                        username: username,
                        business: businessName,
                        points_taken: cost,
                        total_points: totalPoints
                    }
                    res.send(202, sendBack);
                    res.end();
                })
            })
        },
        getRequest: function(url) {
            // set up initial get request.
            return new Promise(function(resolve, reject) {
                request.get(url, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        putRequest: function(params) {
            return new Promise(function(resolve, reject) {
                request.put(params, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        }
    }
})();<|endoftext|>


<commit_before><commit_msg>test: MObject: #verbcall: test for searching up the inheritance tree<commit_after><|endoftext|>


<commit_before><commit_msg>tests for MObject#load<commit_after><|endoftext|>


<commit_before><commit_msg>Fix tests<commit_after><|endoftext|>


<commit_before><commit_msg>popoverClick tests<commit_after><|endoftext|>


<commit_before><commit_msg>test extracting names of languages<commit_after><|endoftext|>


<commit_before><commit_msg>Test the responseBounds field<commit_after><|endoftext|>


<commit_before>var assert = require('assert');
var sinon = require('sinon');
var Queue = require('../lib/queue');
var Worker = require('../lib/worker');

describe('Worker', function() {
    var worker;

    beforeEach(function() {
        worker = new Worker();
    });

    it('has default queue', function() {
        assert.equal(worker.queues.length, 1);
        assert.equal(worker.queues[0].name, 'default');
    });

    it('has default polling interval', function() {
        assert.equal(worker.interval, 5000);
    });

    it('is an event emitter', function(done) {
        worker.on('foo', function(bar) {
            assert.equal(bar, 'bar');
            done();
        });

        worker.emit('foo', 'bar');
    });

    describe('when publishing events', function() {
        var job;

        beforeEach(function() {
            var pubsub = { publish: function() {}};
            worker = new Worker({ pubsub: pubsub });
            job = { queue: 'default' };
        });

        it('emits event on object', function(done) {
            worker.on('foo', function(j) {
                assert.equal(j, job);
                done();
            });

            worker.publish('foo', job);
        });

        it('publishes event to pubsub bus', function() {
            var publish = sinon.stub(worker.pubsub, 'publish');

            worker.publish('foo', job);

            assert.ok(publish.calledOnce);
            assert.deepEqual(publish.getCall(0).args[0], {
                event: 'foo',
                queue: 'default',
                job: job
            });
        });
    });

    describe('when dequeuing', function() {
        beforeEach(function() {
            worker = new Worker({ queues: ['foo', 'bar', 'baz'] });
        });

        it('cycles queues', function() {
            var foo = sinon.stub(worker.queues[0], 'dequeue').yields();
            var bar = sinon.stub(worker.queues[1], 'dequeue').yields();
            var baz = sinon.stub(worker.queues[2], 'dequeue').yields();

            worker.dequeue(function() {});
            worker.dequeue(function() {});
            worker.dequeue(function() {});
            worker.dequeue(function() {});

            assert.ok(foo.calledTwice);
            assert.ok(foo.calledBefore(bar));
            assert.ok(bar.calledOnce);
            assert.ok(bar.calledBefore(baz));
            assert.ok(baz.calledOnce);
            assert.ok(baz.calledBefore(foo));
        });
    });

    describe('when polling', function() {
        beforeEach(function() {
            worker = new Worker({ queues: ['foo', 'bar'] });
        });

        describe('when error', function() {
            it('emits an `error` event', function(done) {
                var error = new Error();
                sinon.stub(worker, 'dequeue').yields(error);

                worker.on('error', function(err) {
                    assert.equal(err, error);
                    done();
                });

                worker.start();
            });
        });

        describe('when job is available', function() {
            var job, work;

            beforeEach(function() {
                job = { some: 'job' };
                work = sinon.stub(worker, 'work');
                sinon.stub(worker.queues[0], 'dequeue').yields(null, job);
            });

            it('works on the job', function() {
                worker.start();

                assert.ok(work.calledOnce);
                assert.equal(work.getCall(0).args[0], job);
            });

            it('publishes `dequeued` event', function() {
                var publish = sinon.spy(worker, 'publish');

                worker.start();

                assert.ok(publish.calledOnce);
                var args = publish.getCall(0).args;
                assert.equal(args[0], 'dequeued');
                assert.equal(args[1], job);
            });
        });

        describe('when no job is available', function() {
            var clock;

            beforeEach(function() {
                clock = sinon.useFakeTimers();
                sinon.stub(worker.queues[0], 'dequeue').yields(null, null);
                sinon.stub(worker.queues[1], 'dequeue').yields(null, null);
            });

            afterEach(function() {
                clock.restore();
            });

            it('waits an interval before polling again', function() {
                worker.start();

                var poll = sinon.spy(worker, 'poll');
                worker.stop();
                clock.tick(5000);

                assert.ok(poll.calledOnce);
            });
        });
    });

    describe('when working', function() {
        describe('when processing fails', function() {
            var error, fail, job, poll;

            beforeEach(function() {
                error = new Error();
                job = { fail: function() {}};
                fail = sinon.stub(job, 'fail').yields();
                poll = sinon.spy(worker, 'poll');

                sinon.stub(worker, 'process').yields(error);
            });

            it('fails the job', function() {
                worker.work(job);

                assert.ok(fail.calledOnce);
                assert.equal(fail.getCall(0).args[0], error)
            });

            it('publishes `failed` event', function() {
                var publish = sinon.spy(worker, 'publish');

                worker.work(job);

                assert.ok(publish.calledOnce);
                assert.equal(publish.getCall(0).args[0], 'failed');
                assert.equal(publish.getCall(0).args[1], job);
            });

            it('polls for a new job', function() {
                worker.work(job);

                assert.ok(poll.calledOnce);
            });
        });

        describe('when processing succeeds', function() {
            var complete, job, poll;

            beforeEach(function() {
                job = { complete: function() {}};
                complete = sinon.stub(job, 'complete').yields();
                poll = sinon.spy(worker, 'poll');

                sinon.stub(worker, 'process').yields(null, 'foobar');
            });

            it('completes the job', function() {
                worker.work(job);

                assert.ok(complete.calledOnce);
                assert.equal(complete.getCall(0).args[0], 'foobar')
            });

            it('publishes `complete` event', function() {
                var publish = sinon.spy(worker, 'publish');

                worker.work(job);

                assert.ok(publish.calledOnce);
                assert.equal(publish.getCall(0).args[0], 'complete');
                assert.equal(publish.getCall(0).args[1], job);
            });

            it('polls for a new job', function() {
                worker.work(job);

                assert.ok(poll.calledOnce);
            });
        });
    });

    describe('when processing', function() {
        beforeEach(function() {
            worker = new Worker();

            worker.register({
                example: function(params, callback) {
                    callback(null, params);
                }
            });
        });

        it('passes job to registered callback', function(done) {
            worker.process({ name: 'example', params: { foo: 'bar' }}, function(err, result) {
                assert.deepEqual(result, { foo: 'bar' });
                done();
            });
        });

        it('returns error if there is no registered callback', function(done) {
            worker.process({ name: 'asdf' }, function(err, result) {
                assert.ok(err);
                done();
            });
        });
    });
});<commit_msg>Fix worker tests<commit_after>var assert = require('assert');
var sinon = require('sinon');
var Queue = require('../lib/queue');
var Worker = require('../lib/worker');

describe('Worker', function() {
    var worker;

    beforeEach(function() {
        worker = new Worker();
    });

    it('has default queue', function() {
        assert.equal(worker.queues.length, 1);
        assert.equal(worker.queues[0].name, 'default');
    });

    it('has default polling interval', function() {
        assert.equal(worker.interval, 5000);
    });

    it('is an event emitter', function(done) {
        worker.on('foo', function(bar) {
            assert.equal(bar, 'bar');
            done();
        });

        worker.emit('foo', 'bar');
    });

    describe('when publishing events', function() {
        var job;

        beforeEach(function() {
            var pubsub = { publish: function() {}};
            worker = new Worker({ pubsub: pubsub });
            job = { queue: 'default' };
        });

        it('emits event on object', function(done) {
            worker.on('foo', function(j) {
                assert.equal(j, job);
                done();
            });

            worker.publish('foo', job);
        });

        it('publishes event to pubsub bus', function() {
            var publish = sinon.stub(worker.pubsub, 'publish');

            worker.publish('foo', job);

            assert.ok(publish.calledOnce);
            assert.deepEqual(publish.getCall(0).args[0], {
                event: 'foo',
                job: job
            });
        });
    });

    describe('when dequeuing', function() {
        beforeEach(function() {
            worker = new Worker({ queues: ['foo', 'bar', 'baz'] });
        });

        it('cycles queues', function() {
            var foo = sinon.stub(worker.queues[0], 'dequeue').yields();
            var bar = sinon.stub(worker.queues[1], 'dequeue').yields();
            var baz = sinon.stub(worker.queues[2], 'dequeue').yields();

            worker.dequeue(function() {});
            worker.dequeue(function() {});
            worker.dequeue(function() {});
            worker.dequeue(function() {});

            assert.ok(foo.calledTwice);
            assert.ok(foo.calledBefore(bar));
            assert.ok(bar.calledOnce);
            assert.ok(bar.calledBefore(baz));
            assert.ok(baz.calledOnce);
            assert.ok(baz.calledBefore(foo));
        });
    });

    describe('when polling', function() {
        beforeEach(function() {
            worker = new Worker({ queues: ['foo', 'bar'] });
        });

        describe('when error', function() {
            it('emits an `error` event', function(done) {
                var error = new Error();
                sinon.stub(worker, 'dequeue').yields(error);

                worker.on('error', function(err) {
                    assert.equal(err, error);
                    done();
                });

                worker.start();
            });
        });

        describe('when job is available', function() {
            var job, work;

            beforeEach(function() {
                job = { some: 'job' };
                work = sinon.stub(worker, 'work');
                sinon.stub(worker.queues[0], 'dequeue').yields(null, job);
            });

            it('works on the job', function() {
                worker.start();

                assert.ok(work.calledOnce);
                assert.equal(work.getCall(0).args[0], job);
            });

            it('publishes `dequeued` event', function() {
                var publish = sinon.spy(worker, 'publish');

                worker.start();

                assert.ok(publish.calledOnce);
                var args = publish.getCall(0).args;
                assert.equal(args[0], 'dequeued');
                assert.equal(args[1], job);
            });
        });

        describe('when no job is available', function() {
            var clock;

            beforeEach(function() {
                clock = sinon.useFakeTimers();
                sinon.stub(worker.queues[0], 'dequeue').yields(null, null);
                sinon.stub(worker.queues[1], 'dequeue').yields(null, null);
            });

            afterEach(function() {
                clock.restore();
            });

            it('waits an interval before polling again', function() {
                worker.start();

                var poll = sinon.spy(worker, 'poll');
                worker.stop();
                clock.tick(5000);

                assert.ok(poll.calledOnce);
            });
        });
    });

    describe('when working', function() {
        describe('when processing fails', function() {
            var error, fail, job, poll;

            beforeEach(function() {
                error = new Error();
                job = { fail: function() {}};
                fail = sinon.stub(job, 'fail').yields();
                poll = sinon.spy(worker, 'poll');

                sinon.stub(worker, 'process').yields(error);
            });

            it('fails the job', function() {
                worker.work(job);

                assert.ok(fail.calledOnce);
                assert.equal(fail.getCall(0).args[0], error)
            });

            it('publishes `failed` event', function() {
                var publish = sinon.spy(worker, 'publish');

                worker.work(job);

                assert.ok(publish.calledOnce);
                assert.equal(publish.getCall(0).args[0], 'failed');
                assert.equal(publish.getCall(0).args[1], job);
            });

            it('polls for a new job', function() {
                worker.work(job);

                assert.ok(poll.calledOnce);
            });
        });

        describe('when processing succeeds', function() {
            var complete, job, poll;

            beforeEach(function() {
                job = { complete: function() {}};
                complete = sinon.stub(job, 'complete').yields();
                poll = sinon.spy(worker, 'poll');

                sinon.stub(worker, 'process').yields(null, 'foobar');
            });

            it('completes the job', function() {
                worker.work(job);

                assert.ok(complete.calledOnce);
                assert.equal(complete.getCall(0).args[0], 'foobar')
            });

            it('publishes `complete` event', function() {
                var publish = sinon.spy(worker, 'publish');

                worker.work(job);

                assert.ok(publish.calledOnce);
                assert.equal(publish.getCall(0).args[0], 'complete');
                assert.equal(publish.getCall(0).args[1], job);
            });

            it('polls for a new job', function() {
                worker.work(job);

                assert.ok(poll.calledOnce);
            });
        });
    });

    describe('when processing', function() {
        beforeEach(function() {
            worker = new Worker();

            worker.register({
                example: function(params, callback) {
                    callback(null, params);
                }
            });
        });

        it('passes job to registered callback', function(done) {
            worker.process({ name: 'example', params: { foo: 'bar' }}, function(err, result) {
                assert.deepEqual(result, { foo: 'bar' });
                done();
            });
        });

        it('returns error if there is no registered callback', function(done) {
            worker.process({ name: 'asdf' }, function(err, result) {
                assert.ok(err);
                done();
            });
        });
    });
});<|endoftext|>


<commit_before>var assert = require("assert");
var path = require("path");
var Promise = require("promise");
var promisify = require("promisify-node");
var rimraf = promisify("rimraf");

describe("Clone", function() {
  var http = path.resolve("test/repos/http");
  var https = path.resolve("test/repos/https");
  var ssh = path.resolve("test/repos/ssh");
  var git = path.resolve("test/repos/git");
  var file = path.resolve("test/repos/file");

  var Repository = require("../../lib/repository");
  var Clone = require("../../lib/clone");
  var NodeGit = require("../../");

  before(function() {
    return Promise.all([
      rimraf(http),
      rimraf(https),
      rimraf(ssh),
      rimraf(git),
      rimraf(file),
    ]);
  });

  it("can clone with http", function() {
    var url = "http://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, http, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with https", function() {
    var url = "https://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, https, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with ssh", function() {
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      ignoreCertErrors: 1,
      remoteCallbacks: {
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyFromAgent(userName);
        }
      }
    };

    return Clone.clone(url, ssh, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with git", function() {
    var url = "git://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, git, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with filesystem", function() {
    var url = "file://" + path.resolve("test/repos/empty");

    return Clone.clone(url, file).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });
});
<commit_msg>Fix clone with filesytem for windows<commit_after>var assert = require("assert");
var path = require("path");
var Promise = require("promise");
var promisify = require("promisify-node");
var rimraf = promisify("rimraf");

describe("Clone", function() {
  var http = path.resolve("test/repos/http");
  var https = path.resolve("test/repos/https");
  var ssh = path.resolve("test/repos/ssh");
  var git = path.resolve("test/repos/git");
  var file = path.resolve("test/repos/file");

  var Repository = require("../../lib/repository");
  var Clone = require("../../lib/clone");
  var NodeGit = require("../../");

  before(function() {
    return Promise.all([
      rimraf(http),
      rimraf(https),
      rimraf(ssh),
      rimraf(git),
      rimraf(file),
    ]);
  });

  it("can clone with http", function() {
    var url = "http://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, http, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with https", function() {
    var url = "https://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, https, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with ssh", function() {
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      ignoreCertErrors: 1,
      remoteCallbacks: {
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyFromAgent(userName);
        }
      }
    };

    return Clone.clone(url, ssh, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with git", function() {
    var url = "git://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, git, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with filesystem", function() {
    var prefix = process.platform === "win32" ? "" : "file://";
    var url = prefix + path.resolve("test/repos/empty");

    return Clone.clone(url, file).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';
const describe = require('mocha').describe;
const it = require('mocha').it;
const assert = require('assert');
const gutil = require('gulp-util');
const vfs = require('vinyl-fs');
const tslint = require('gulp-tslint');
const reporter = require('../');

require('./sandbox');

describe('TSLint', function() {
	this.timeout(10000);
	it('console reporter', done => {
		return vfs.src('test/fixtures/tslint/invalid.ts', {
			base: process.cwd()
		})
			.pipe(tslint())
			.pipe(reporter({
				filter: null
			}))

			.on('error', ex => {
				assert.equal(ex.plugin, 'gulp-reporter');
				assert.equal(ex.message, 'Lint failed for: test/fixtures/tslint/invalid.ts');
				assert.ok(/\s+\[\d+:\d+\]/.test(gutil.log.lastCall.args[0]));
				assert.ok(gutil.log.lastCall.args[0].indexOf('missing whitespace (TSLint one-line https://palantir.github.io/tslint/rules/one-line/)') >= 0);
				assert.ok(gutil.log.lastCall.args[0].indexOf('missing whitespace (TSLint whitespace https://palantir.github.io/tslint/rules/whitespace/)') >= 0);
				done();
			});
	});
	it('fail function', done => {
		let error;
		return vfs.src('test/fixtures/tslint/invalid.ts', {
			base: process.cwd()
		})
			.pipe(tslint())
			.pipe(reporter({
				filter: null,
				fail: () => {
					return false;
				}
			}))

			.on('error', ex => {
				error = error || ex;
			}).on('finish', () => {
				assert.ok(!error);
				done();
			});
	});
});
<commit_msg>fix tslint warning (#56)<commit_after>'use strict';
const describe = require('mocha').describe;
const it = require('mocha').it;
const assert = require('assert');
const gutil = require('gulp-util');
const vfs = require('vinyl-fs');
const gulpTslint = require('gulp-tslint');
const tslint = require('tslint');
const reporter = require('../');

require('./sandbox');

describe('TSLint', function() {
	this.timeout(10000);
	it('console reporter', done => {
		return vfs.src('test/fixtures/tslint/invalid.ts', {
			base: process.cwd()
		})
			.pipe(gulpTslint({
				program: tslint.Linter.createProgram('test/fixtures/tslint/tslint.json')
			}))
			.pipe(reporter({
				filter: null
			}))

			.on('error', ex => {
				assert.equal(ex.plugin, 'gulp-reporter');
				assert.equal(ex.message, 'Lint failed for: test/fixtures/tslint/invalid.ts');
				assert.ok(/\s+\[\d+:\d+\]/.test(gutil.log.lastCall.args[0]));
				assert.ok(gutil.log.lastCall.args[0].indexOf('missing whitespace (TSLint one-line https://palantir.github.io/tslint/rules/one-line/)') >= 0);
				assert.ok(gutil.log.lastCall.args[0].indexOf('missing whitespace (TSLint whitespace https://palantir.github.io/tslint/rules/whitespace/)') >= 0);
				done();
			});
	});
	it('fail function', done => {
		let error;
		return vfs.src('test/fixtures/tslint/invalid.ts', {
			base: process.cwd()
		})
			.pipe(gulpTslint({
				program: tslint.Linter.createProgram('test/fixtures/tslint/tslint.json')
			}))
			.pipe(reporter({
				filter: null,
				fail: () => {
					return false;
				}
			}))

			.on('error', ex => {
				error = error || ex;
			}).on('finish', () => {
				assert.ok(!error);
				done();
			});
	});
});
<|endoftext|>


<commit_before>/**
 * .reel Unit Tests
 */
(function($){

  module('Issues', { teardown: function teardown(){
    $('.jquery-reel').trigger('teardown').unbind('.test');
    $(document).unbind('.test');
  }});

  test( 'GH-4 Proper background positioning range for stitched non-looping panoramas', function(){
    /* Github issue 4 bugfix
     * http://github.com/pisi/Reel/issues/#issue/4
     */
    expect($.browser.msie ? 4 : 2);
    var
      stitched= 1652,
      $pano= $('#stitched_nonlooping').reel({ stitched: stitched, loops: false }),
      travel= stitched - parseInt($pano.css('width'))

    $pano.trigger('frameChange', 1);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Frame 1 (min, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Frame 1 (min, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Frame 1 (min)');
    }
    $pano.trigger('frameChange', 36);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), -travel+'px', 'Frame 36 (max, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Frame 36 (max, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), -travel+'px 0px', 'Frame 36 (max)');
    }
  });

  test( 'GH-6 Proper background positioning range for stitched looping panoramas', function(){
    /* Github issue 6 bugfix
     * http://github.com/pisi/Reel/issues/#issue/6
     */
    expect($.browser.msie ? 4 : 2);
    var
      stitched= 1652,
      $pano= $('#stitched_looping').reel({ stitched: stitched, loops: true }),
      travel= stitched

    $pano.trigger('frameChange', 1);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Looping - frame 1 (min, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Looping - frame 1 (min, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Looping - frame 1 (min)');
    }
    $pano.trigger('frameChange', 36);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Looping - frame 36 (max, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Looping - frame 36 (max, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Looping - frame 36 (max)');
    }
  });

  asyncTest( 'GH-11 First frame disappears after image sequence loading is complete', function(){
    /* Github issue 11 bugfix
     * http://github.com/pisi/Reel/issues/#issue/11
     * Replacement of original image source with embedded transparent sprite
     * can not happen when using `images` option
     */
    expect(1);
    var
      $pano= $('#sequence').reel({
        footage:  10,
        cw:       true,
        orbital:  3,
        inversed: true,
        path:     'samples/phone/',
        images:   phone_frames(20)
      })

    $pano.one('loaded', function(){
      equal($pano.attr('src'), 'samples/phone/01.png', 'Image is from the sequence');
      start();
    });

    /*
      Borrowed from test/sampler.html
    */
    function phone_frames(frames){
      var every= 1, stack= []
      for(var i= 1; i <= frames; i+= every){
        var name= [i, '.png'].join('')
        while (name.length < 6) name= '0'+name
        stack.push(name)
      }
      return stack
    }
  });

  asyncTest( 'GH-30 Broken "play" in IE', function(){
    /* Github issue 30 bugfix
     * http://github.com/pisi/Reel/issues/#issue/30
     * First of all, private `slidable` boolean flag leaked into global scope
     * and also caused Reel to throw JS errors.
     * Then adaptive ticker timeout sometimes went sub-zero causing IE to invalidate such `setTimeout` call
     * and thus effectively ceised the timer completely.
     * Another IE issue: broken image overlay in IE 7 or lower was caused by no support for "data:" protocol URLs,
     * so to workaround it a CDN-served blank image is be used instead.
     */
    expect(4);
    var
      $pano= $('#image').reel(),
      ticks= 0

    equal(typeof slidable, 'undefined', '`slidable` is undefined in the global scope');
    equal(typeof window.slidable, 'undefined', '`window.slidable` is also undefined');

    $(document).bind('tick.reel.test', function(){
      ticks++;
      if (ticks == 100){
        ok(true, 'Ticked 100 times - ticker runs ;)');

        var
          protocol= $('#image').attr('src').split(':')[0]

        if ($.browser.msie && +$.browser.version <= 7) equal(protocol, 'http', 'CDN-served transparent image.')
        else equal(protocol, 'data', 'Embedded transparent image.');

        start();
      }
    });
  });

  asyncTest( '`stage_pool` private variable leaked into global scope', function()
  {
    expect(1);

    var
      $reel= $('#image').reel()

    setTimeout(function(){
      ok( typeof stage_pool === 'undefined', 'No leaked `stage_pool` accessible in the global scope');
      start();
    }, 100)
  });

  asyncTest( 'Teardown doesn\'t propagate the cloned original image down the chain', function(){
    /*
     * When Reel instance is torn down and `.reel()` is called again in the same chain,
     * the instance isn't properly initialized.
     * The cloned-back original `IMG` tag doesn't propagate as a proper target
     * for subsequent `.reel()` calls. These don't fail (as they are most probably
     * performed upon the old now detached DOM node. The extra selector evaluation
     * is therefore required in order to further manipulate the node.
     */
    expect( 3 );

    $('#image').reel().bind('click.test', function(){
      ok( true, 'Event binding is preserved');
    });

    setTimeout( function(){
      $('#image').trigger('teardown').reel();
      ok( $('#image').is('.jquery-reel'), 'IMG tag is flagged as a Reel instance');
      ok( $('#image').parent().is('.jquery-reel-overlay#image-reel'), 'and wrapped in overlay DIV');
      $('#image').click();
      start();
    }, 500 );
  });

  test( 'GH-46 Incorrect `row` to `frame` translation in multi-row movies', function(){
    /* Github issue 46 bugfix
     * http://github.com/pisi/Reel/issues/#issue/46
     * When topmost row has been reached with dragging, the instance freeze in that row
     * no matter the vertical direction of the drag. Instance then has to be dragged
     * left or right to restore the vertical movement. Unfortunately enough
     * this happens for all frames lying on the first row and especially the default value.
     *
     * This bug expresses itself by locking vertical reel in the topmost row
     * and preventing proper `row` > `frame` propagation unless horizontal drag
     * is performed.
     */
    var
      try_rows= [ 1, 2 ],
      try_frames= [ 1, 2, 3, 4, 5, 6, 7, /*8,*/ 9, 10, 11, 12, 13, 14, /*15,*/ 16, 17, 18, 19, 20,
                    21, 22, 23, 24, 25, 26, 27, 28, /*29,*/ 30, 31, 32, 33, 34, 35, 36 ]
                    /* The three commented-out frame values (8, 15 and 29)
                     * are known exceptions from the rule and the actual calculated value is
                     * always one less. Exactly why this happens and especially why it is
                     * independent on `frames` value is still a true mystery for me.
                     * Anyway, it yields 96.3% accuracy, which is as far as I could get it,
                     * is much better then before and I'm happy with it. At least for now.
                     */

    expect( try_rows * try_frames * 3 ); // 3 test for each combination

    for( var i= 0; i < try_rows.length; i++){
      for( var ii= 0; ii < try_frames.length; ii++){
        $('#image').trigger('teardown');
        var
          frame= try_frames[ ii ],
          row= try_rows[ i ],
          rows= 2,
          frames= 36, // default
          $pano= $('#image').reel({
            frame: frame,
            rows: rows,
            row: row
          })

        // Click and drag long way down
        $pano.trigger('down', [ 100, 200 ]);
        $pano.trigger('pan', [ 100, 400 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 1, frame: rows * frames - frames + frame },
                  'Drag way down on frame '+frame+' / '+frames+', row '+row+' / '+rows);

        // `tick` needs to be triggered manually between `pan`s in order to have the instance slidable again
        $pano.trigger('tick');

        // Then drag it all the way back up to reach the first row
        $pano.trigger('pan', [ 100, 1 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 0, frame: frame },
                  '& drag way up');

        $pano.trigger('tick');

        // Then drag it back all the way down
        $pano.trigger('pan', [ 100, 400 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 1, frame: rows * frames - frames + frame },
                  '& drag way down again.');
      }
    }
  });

  asyncTest( 'GH-62 Implicit teardown', function(){
    /*
     * Unable to switch Reels in a simple manner without a manual teardown.
     */
    expect( 1 );
    var
      image = undefined

    $('#image').reel().bind('loaded.test', function(){
      if (image === undefined){
        image= $(this).data('image');
        var
          new_instance= $(this).reel({
            image: '../example/panorama-reel.jpg'
          });

        // Finish the test in case reel initialization fails
        if (!new_instance.length){
          ok( false, 'Unable to instantitate the same DOM node for the second time');
          start();
        }
      }else{
        ok( image !== $(this).data('image'), 'The second reel image is different than the starting one');
        start();
      }
    });
    $('#image').reel();
  });

})(jQuery);
<commit_msg>Split the computation intensive #46 test into two passes for each row in order to not exceed timeout and expire on lazy mobile devices (observed on iPad) #75<commit_after>/**
 * .reel Unit Tests
 */
(function($){

  module('Issues', { teardown: function teardown(){
    $('.jquery-reel').trigger('teardown').unbind('.test');
    $(document).unbind('.test');
  }});

  test( 'GH-4 Proper background positioning range for stitched non-looping panoramas', function(){
    /* Github issue 4 bugfix
     * http://github.com/pisi/Reel/issues/#issue/4
     */
    expect($.browser.msie ? 4 : 2);
    var
      stitched= 1652,
      $pano= $('#stitched_nonlooping').reel({ stitched: stitched, loops: false }),
      travel= stitched - parseInt($pano.css('width'))

    $pano.trigger('frameChange', 1);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Frame 1 (min, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Frame 1 (min, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Frame 1 (min)');
    }
    $pano.trigger('frameChange', 36);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), -travel+'px', 'Frame 36 (max, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Frame 36 (max, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), -travel+'px 0px', 'Frame 36 (max)');
    }
  });

  test( 'GH-6 Proper background positioning range for stitched looping panoramas', function(){
    /* Github issue 6 bugfix
     * http://github.com/pisi/Reel/issues/#issue/6
     */
    expect($.browser.msie ? 4 : 2);
    var
      stitched= 1652,
      $pano= $('#stitched_looping').reel({ stitched: stitched, loops: true }),
      travel= stitched

    $pano.trigger('frameChange', 1);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Looping - frame 1 (min, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Looping - frame 1 (min, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Looping - frame 1 (min)');
    }
    $pano.trigger('frameChange', 36);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Looping - frame 36 (max, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Looping - frame 36 (max, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Looping - frame 36 (max)');
    }
  });

  asyncTest( 'GH-11 First frame disappears after image sequence loading is complete', function(){
    /* Github issue 11 bugfix
     * http://github.com/pisi/Reel/issues/#issue/11
     * Replacement of original image source with embedded transparent sprite
     * can not happen when using `images` option
     */
    expect(1);
    var
      $pano= $('#sequence').reel({
        footage:  10,
        cw:       true,
        orbital:  3,
        inversed: true,
        path:     'samples/phone/',
        images:   phone_frames(20)
      })

    $pano.one('loaded', function(){
      equal($pano.attr('src'), 'samples/phone/01.png', 'Image is from the sequence');
      start();
    });

    /*
      Borrowed from test/sampler.html
    */
    function phone_frames(frames){
      var every= 1, stack= []
      for(var i= 1; i <= frames; i+= every){
        var name= [i, '.png'].join('')
        while (name.length < 6) name= '0'+name
        stack.push(name)
      }
      return stack
    }
  });

  asyncTest( 'GH-30 Broken "play" in IE', function(){
    /* Github issue 30 bugfix
     * http://github.com/pisi/Reel/issues/#issue/30
     * First of all, private `slidable` boolean flag leaked into global scope
     * and also caused Reel to throw JS errors.
     * Then adaptive ticker timeout sometimes went sub-zero causing IE to invalidate such `setTimeout` call
     * and thus effectively ceised the timer completely.
     * Another IE issue: broken image overlay in IE 7 or lower was caused by no support for "data:" protocol URLs,
     * so to workaround it a CDN-served blank image is be used instead.
     */
    expect(4);
    var
      $pano= $('#image').reel(),
      ticks= 0

    equal(typeof slidable, 'undefined', '`slidable` is undefined in the global scope');
    equal(typeof window.slidable, 'undefined', '`window.slidable` is also undefined');

    $(document).bind('tick.reel.test', function(){
      ticks++;
      if (ticks == 100){
        ok(true, 'Ticked 100 times - ticker runs ;)');

        var
          protocol= $('#image').attr('src').split(':')[0]

        if ($.browser.msie && +$.browser.version <= 7) equal(protocol, 'http', 'CDN-served transparent image.')
        else equal(protocol, 'data', 'Embedded transparent image.');

        start();
      }
    });
  });

  asyncTest( '`stage_pool` private variable leaked into global scope', function()
  {
    expect(1);

    var
      $reel= $('#image').reel()

    setTimeout(function(){
      ok( typeof stage_pool === 'undefined', 'No leaked `stage_pool` accessible in the global scope');
      start();
    }, 100)
  });

  asyncTest( 'Teardown doesn\'t propagate the cloned original image down the chain', function(){
    /*
     * When Reel instance is torn down and `.reel()` is called again in the same chain,
     * the instance isn't properly initialized.
     * The cloned-back original `IMG` tag doesn't propagate as a proper target
     * for subsequent `.reel()` calls. These don't fail (as they are most probably
     * performed upon the old now detached DOM node. The extra selector evaluation
     * is therefore required in order to further manipulate the node.
     */
    expect( 3 );

    $('#image').reel().bind('click.test', function(){
      ok( true, 'Event binding is preserved');
    });

    setTimeout( function(){
      $('#image').trigger('teardown').reel();
      ok( $('#image').is('.jquery-reel'), 'IMG tag is flagged as a Reel instance');
      ok( $('#image').parent().is('.jquery-reel-overlay#image-reel'), 'and wrapped in overlay DIV');
      $('#image').click();
      start();
    }, 500 );
  });

  asyncTest( 'GH-46 Incorrect `row` to `frame` translation in multi-row movies', function(){
    /* Github issue 46 bugfix
     * http://github.com/pisi/Reel/issues/#issue/46
     * When topmost row has been reached with dragging, the instance freeze in that row
     * no matter the vertical direction of the drag. Instance then has to be dragged
     * left or right to restore the vertical movement. Unfortunately enough
     * this happens for all frames lying on the first row and especially the default value.
     *
     * This bug expresses itself by locking vertical reel in the topmost row
     * and preventing proper `row` > `frame` propagation unless horizontal drag
     * is performed.
     */
    var
      try_rows= [ 1, 2 ],
      done_rows= 0,
      try_frames= [ 1, 2, 3, 4, 5, 6, 7, /*8,*/ 9, 10, 11, 12, 13, 14, /*15,*/ 16, 17, 18, 19, 20,
                    21, 22, 23, 24, 25, 26, 27, 28, /*29,*/ 30, 31, 32, 33, 34, 35, 36 ]
                    /* The three commented-out frame values (8, 15 and 29)
                     * are known exceptions from the rule and the actual calculated value is
                     * always one less. Exactly why this happens and especially why it is
                     * independent on `frames` value is still a true mystery for me.
                     * Anyway, it yields 96.3% accuracy, which is as far as I could get it,
                     * is much better then before and I'm happy with it. At least for now.
                     */

    expect( try_rows * try_frames * 3 ); // 3 test for each combination

    for( var i= 0; i < try_rows.length; i++) setTimeout( function(){
      for( var ii= 0; ii < try_frames.length; ii++){
        $('#image').trigger('teardown');
        var
          frame= try_frames[ ii ],
          row= try_rows[ i ],
          rows= 2,
          frames= 36, // default
          $pano= $('#image').reel({
            frame: frame,
            rows: rows,
            row: row
          })

        // Click and drag long way down
        $pano.trigger('down', [ 100, 200 ]);
        $pano.trigger('pan', [ 100, 400 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 1, frame: rows * frames - frames + frame },
                  'Drag way down on frame '+frame+' / '+frames+', row '+row+' / '+rows);

        // `tick` needs to be triggered manually between `pan`s in order to have the instance slidable again
        $pano.trigger('tick');

        // Then drag it all the way back up to reach the first row
        $pano.trigger('pan', [ 100, 1 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 0, frame: frame },
                  '& drag way up');

        $pano.trigger('tick');

        // Then drag it back all the way down
        $pano.trigger('pan', [ 100, 400 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 1, frame: rows * frames - frames + frame },
                  '& drag way down again.');
      }
      done_rows++;
      if (done_rows == rows) start();
    }, 5);
  });

  asyncTest( 'GH-62 Implicit teardown', function(){
    /*
     * Unable to switch Reels in a simple manner without a manual teardown.
     */
    expect( 1 );
    var
      image = undefined

    $('#image').reel().bind('loaded.test', function(){
      if (image === undefined){
        image= $(this).data('image');
        var
          new_instance= $(this).reel({
            image: '../example/panorama-reel.jpg'
          });

        // Finish the test in case reel initialization fails
        if (!new_instance.length){
          ok( false, 'Unable to instantitate the same DOM node for the second time');
          start();
        }
      }else{
        ok( image !== $(this).data('image'), 'The second reel image is different than the starting one');
        start();
      }
    });
    $('#image').reel();
  });

})(jQuery);
<|endoftext|>


<commit_before>

var connect = require('connect')

var seneca = require('seneca')()
var app    = connect()

app.use( connect.query() )

seneca.use('mem-store',{web:{dump:true}})
seneca.use('user')
seneca.use(function(){
  this.act({role:'web',use:function(req,res,next){
    req.seneca.user = req.user
    next()
  }})
})
seneca.use('..')

seneca.ready( function(err){
  if( err ) process.exit( console.error(err) && 1 );

  seneca.act('role:user, cmd:register, nick:n1', function(err,out){
    if( err ) process.exit( console.error(err) && 1 );

    seneca.act('role:settings, cmd:define_spec, kind:user, spec:{foo:"string"}')
    seneca.act('role:settings, cmd:save, kind:user, data:{foo:"aaa"}, user:"'+out.user.id+'"')

    app.use( function(req,res,next){
      req.user = out.user

      res.send = function(obj) {
        res.writeHead(200)
        res.end(JSON.stringify(obj))
      }

      next()
    })

    app.use( seneca.export('web') )

    app.listen(8888)
  })
})

<commit_msg>fix test/web-app.js, can now handle JSON<commit_after>

var connect = require('connect')

var seneca = require('seneca')()
var app    = connect()

app.use( connect.query() )
app.use( connect.json() )

seneca.use('mem-store',{web:{dump:true}})
seneca.use('user')
seneca.use(function(){
  this.act({role:'web',use:function(req,res,next){
    req.seneca.user = req.user
    next()
  }})
})
seneca.use('..')

seneca.ready( function(err){
  if( err ) process.exit( console.error(err) && 1 );

  seneca.act('role:user, cmd:register, nick:n1', function(err,out){
    if( err ) process.exit( console.error(err) && 1 );

    seneca.act('role:settings, cmd:define_spec, kind:user, spec:{foo:"string"}')
    seneca.act('role:settings, cmd:save, kind:user, data:{foo:"aaa"}, user:"'+out.user.id+'"')

    app.use( function(req,res,next){
      req.user = out.user

      res.send = function(obj) {
        res.writeHead(200)
        res.end(JSON.stringify(obj))
      }

      next()
    })

    app.use( seneca.export('web') )

    app.listen(8888)
  })
})

<|endoftext|>


<commit_before>import React from 'react';
import Ionize from 'ionize';
import { BrowserWindow } from 'electron';

import 'index.html';

function handleReady() {
  console.log("window is ready to show");
}

class TestApp extends React.Component {
  constructor(props) {
    super(props);
    this.handleAppReady = this.handleAppReady.bind(this);
    this.handleShow = this.handleShow.bind(this);

    this.state = {
      isWindowReady: false,
      isWindowClosing: false,
    };
  }

  handleAppReady() {
    setTimeout(() => {
      this._appDialog.show();
    }, 500);
  }

  handleShow() {
    setTimeout(() => {
      this._windowDialog.show();
    }, 1000);
  }

  render() {
    const {
      isWindowReady,
      isWindowClosing,
    } = this.state;

    return (
      <app onReady={this.handleAppReady}>
        <menu id="a">
          <menu id="b">
          </menu>
        </menu>

        <dialog ref={c => { this._appDialog = c }} />
        <window
          file="index.html"
          onReadyToShow={() => this.setState({ isWindowReady: true })}
          onClose={() => this.setState({ isWindowClosing: true })}
          show={isWindowReady}
          onShow={this.handleShow}
        >
          <dialog ref={c => { this._windowDialog = c }} />
        </window>
      </app>
    );
  }
}

Ionize.start(
  <TestApp />,
  () => {
    console.log("--- Finished Ionize.start()");
  }
);
<commit_msg>Add some dialog messages<commit_after>import React from 'react';
import Ionize from 'ionize';
import { BrowserWindow } from 'electron';

import 'index.html';

function handleReady() {
  console.log("window is ready to show");
}

class TestApp extends React.Component {
  constructor(props) {
    super(props);
    this.handleAppReady = this.handleAppReady.bind(this);
    this.handleShow = this.handleShow.bind(this);

    this.state = {
      isWindowReady: false,
      isWindowClosing: false,
    };
  }

  handleAppReady() {
    setTimeout(() => {
      this._appDialog.show("This is a global dialog!");
    }, 2000);
  }

  handleShow() {
    setTimeout(() => {
      this._windowDialog.show("This is a window dialog!");
    }, 5000);
  }

  render() {
    const {
      isWindowReady,
      isWindowClosing,
    } = this.state;

    return (
      <app onReady={this.handleAppReady}>
        <menu id="a">
          <menu id="b">
          </menu>
        </menu>

        <dialog ref={c => { this._appDialog = c }} />
        <window
          file="index.html"
          onReadyToShow={() => this.setState({ isWindowReady: true })}
          onClose={() => this.setState({ isWindowClosing: true })}
          show={isWindowReady}
          onShow={this.handleShow}
        >
          <dialog ref={c => { this._windowDialog = c }} />
        </window>
      </app>
    );
  }
}

Ionize.start(
  <TestApp />,
  () => {
    console.log("--- Finished Ionize.start()");
  }
);
<|endoftext|>


<commit_before>var _ = require('lodash');

var buildCreep = exports.buildCreep = function(spawn, type, parts) {
    var id = Math.random().toString(32).substr(2, 8);
    console.log(type, 'Created', id);
    Game.spawns.Spawn1.createCreep(
        parts,
        type + '-' + id,
        {
            id: id,
            role: type,
            spawnName: spawn.name
        }
    );
};

var typesInfo = {
    harvester: {
        minCount: 1,
        parts: [Game.WORK, Game.CARRY, Game.MOVE]
    },
    attack: {
        minCount: 0,
        parts: [Game.ATTACK, Game.RANGED_ATTACK, Game.MOVE]
    },
    rangedGuard: {
        minCount: 1,
        parts: [Game.RANGED_ATTACK, Game.MOVE]
    },
    guard: {
        minCount: 1,
        parts: [Game.ATTACK, Game.MOVE]
    }
};
var orderedTypes = ['harvester', 'attack', 'guard', 'rangedGuard'];

exports.run = function(spawn){
    if (!spawn || spawn.spawning) {
        return;
    }
    var counts = getCounts();
    for (var i = 0; i < orderedTypes.length; i++) {
        var type = orderedTypes[i],
            typeInfo = typesInfo[type];

        console.log("All Counts:", JSON.stringify(counts));
        if (counts[type] === undefined) {
            counts[type] = 0;
        }
        console.log("All Counts:", JSON.stringify(counts));
        console.log('Checking', type, 'count:', counts[type]);
        if (counts[type] < typeInfo.minCount) {
            return buildCreep(spawn, type, typeInfo.parts);
        }
    }
};

function getCounts() {
    var counts = {};

    for(var i in Game.creeps) {
        var creep = Game.creeps[i];
        if (!creep.my) {
            continue;
        }

        var role = creep.memory.role;

        if (counts[role] === undefined) {
            counts[role] = 1;
        } else {
            counts[role] += 1;
        }
    }

    return counts;
}
<commit_msg>Remove debug code.<commit_after>var _ = require('lodash');

var buildCreep = exports.buildCreep = function(spawn, type, parts) {
    var id = Math.random().toString(32).substr(2, 8);
    console.log(type, 'Created', id);
    Game.spawns.Spawn1.createCreep(
        parts,
        type + '-' + id,
        {
            id: id,
            role: type,
            spawnName: spawn.name
        }
    );
};

var typesInfo = {
    harvester: {
        minCount: 1,
        parts: [Game.WORK, Game.CARRY, Game.MOVE]
    },
    attack: {
        minCount: 0,
        parts: [Game.ATTACK, Game.RANGED_ATTACK, Game.MOVE]
    },
    rangedGuard: {
        minCount: 1,
        parts: [Game.RANGED_ATTACK, Game.MOVE]
    },
    guard: {
        minCount: 1,
        parts: [Game.ATTACK, Game.MOVE]
    }
};
var orderedTypes = ['harvester', 'attack', 'guard', 'rangedGuard'];

exports.run = function(spawn){
    if (!spawn || spawn.spawning) {
        return;
    }
    var counts = getCounts();
    for (var i = 0; i < orderedTypes.length; i++) {
        var type = orderedTypes[i],
            typeInfo = typesInfo[type];

        if (counts[type] === undefined) {
            counts[type] = 0;
        }
        if (counts[type] < typeInfo.minCount) {
            return buildCreep(spawn, type, typeInfo.parts);
        }
    }
};

function getCounts() {
    var counts = {};

    for(var i in Game.creeps) {
        var creep = Game.creeps[i];
        if (!creep.my) {
            continue;
        }

        var role = creep.memory.role;

        if (counts[role] === undefined) {
            counts[role] = 1;
        } else {
            counts[role] += 1;
        }
    }

    return counts;
}
<|endoftext|>


<commit_before>var _ = require('lodash');

var buildCreep = exports.buildCreep = function(spawn, type, parts) {
    var id = Math.random().toString(32).substr(2, 8);
    console.log(type, 'Created', id);
    Game.spawns.Spawn1.createCreep(
        parts,
        type + '-' + id,
        {
            id: id,
            role: type,
            spawnName: spawn.name
        }
    );
};

var typesInfo = {
    harvester: {
        minCount: 1,
        niceCount: 1,
        parts: [Game.WORK, Game.CARRY, Game.MOVE]
    },
    attack: {
        minCount: 0,
        niceCount: 0,
        parts: [Game.ATTACK, Game.RANGED_ATTACK, Game.MOVE]
    },
    rangedGuard: {
        minCount: 1,
        niceCount: 2,
        parts: [Game.RANGED_ATTACK, Game.MOVE]
    },
    guard: {
        minCount: 1,
        niceCount: 2,
        parts: [Game.ATTACK, Game.MOVE]
    }
};
var orderedTypes = ['harvester', 'attack', 'guard', 'rangedGuard'];

exports.run = function(spawn){
    if (!spawn || spawn.spawning) {
        return;
    }
    var counts = getCounts();
    for (var i = 0; i < orderedTypes.length; i++) {
        var type = orderedTypes[i],
            typeInfo = typesInfo[type];

        if (counts[type] === undefined) {
            counts[type] = 0;
        }
        if (counts[type] < typeInfo.minCount) {
            return buildCreep(spawn, type, typeInfo.parts);
        }
    }

    if (spawn.energy > 1000) {
        for (var i = 0; i < orderedTypes.length; i++) {
            var type = orderedTypes[i],
                typeInfo = typesInfo[type];
            if (counts[type] < typeInfo.niceCount) {
                return buildCreep(spawn, type, typeInfo.parts);
            }
        }
    }
};

function getCounts() {
    var counts = {};

    for(var i in Game.creeps) {
        var creep = Game.creeps[i];
        if (!creep.my) {
            continue;
        }

        var role = creep.memory.role;

        if (counts[role] === undefined) {
            counts[role] = 1;
        } else {
            counts[role] += 1;
        }
    }

    return counts;
}
<commit_msg>Only log construction when constructing.<commit_after>var _ = require('lodash');

var buildCreep = exports.buildCreep = function(spawn, type, parts) {
    var id = Math.random().toString(32).substr(2, 8);

    var result = Game.spawns.Spawn1.createCreep(
        parts,
        type + '-' + id,
        {
            id: id,
            role: type,
            spawnName: spawn.name
        }
    );

    if (result === Game.OK) {
        console.log('Created', type+'-'+id);
    }
};

var typesInfo = {
    harvester: {
        minCount: 1,
        niceCount: 1,
        parts: [Game.WORK, Game.CARRY, Game.MOVE]
    },
    attack: {
        minCount: 0,
        niceCount: 0,
        parts: [Game.ATTACK, Game.RANGED_ATTACK, Game.MOVE]
    },
    rangedGuard: {
        minCount: 1,
        niceCount: 2,
        parts: [Game.RANGED_ATTACK, Game.MOVE]
    },
    guard: {
        minCount: 1,
        niceCount: 2,
        parts: [Game.ATTACK, Game.MOVE]
    }
};
var orderedTypes = ['harvester', 'attack', 'guard', 'rangedGuard'];

exports.run = function(spawn){
    if (!spawn || spawn.spawning) {
        return;
    }
    var counts = getCounts();
    for (var i = 0; i < orderedTypes.length; i++) {
        var type = orderedTypes[i],
            typeInfo = typesInfo[type];

        if (counts[type] === undefined) {
            counts[type] = 0;
        }
        if (counts[type] < typeInfo.minCount) {
            return buildCreep(spawn, type, typeInfo.parts);
        }
    }

    if (spawn.energy > 1000) {
        for (var i = 0; i < orderedTypes.length; i++) {
            var type = orderedTypes[i],
                typeInfo = typesInfo[type];
            if (counts[type] < typeInfo.niceCount) {
                return buildCreep(spawn, type, typeInfo.parts);
            }
        }
    }
};

function getCounts() {
    var counts = {};

    for(var i in Game.creeps) {
        var creep = Game.creeps[i];
        if (!creep.my) {
            continue;
        }

        var role = creep.memory.role;

        if (counts[role] === undefined) {
            counts[role] = 1;
        } else {
            counts[role] += 1;
        }
    }

    return counts;
}
<|endoftext|>


<commit_before><commit_msg>Anchor links in the description are not content editable.<commit_after><|endoftext|>


<commit_before><commit_msg>描画ツール、カラーパレット、線幅ツールについて、PaintBBS風の連携を実現した。<commit_after><|endoftext|>