<commit_before>// newrelic is not working with latest npm
//if(config.has('newrelic')) require('newrelic');

import path from 'path';
import fs from 'fs';
import Koa from 'koa';
import mount from 'koa-mount';
import helmet from 'koa-helmet';
import koa_logger from 'koa-logger';
import prod_logger from './prod_logger';
import favicon from 'koa-favicon';
import staticCache from 'koa-static-cache';
import useRedirects from './redirects';
import useGeneralApi from './api/general';
import useAccountRecoveryApi from './api/account_recovery';
import useNotificationsApi from './api/notifications';
import useEnterAndConfirmEmailPages from './server_pages/enter_confirm_email';
import useEnterAndConfirmMobilePages from './server_pages/enter_confirm_mobile';
import useUserJson from './json/user_json';
import usePostJson from './json/post_json';
import isBot from 'koa-isbot';
import session from './utils/cryptoSession';
import csrf from 'koa-csrf';
import flash from 'koa-flash';
import minimist from 'minimist';
import config from 'config';
import { routeRegex } from 'app/ResolveRoute';
import { blockedUsers } from 'app/utils/IllegalContent';
import secureRandom from 'secure-random';
import { APP_NAME_LATIN } from 'app/client_config';

console.log('application server starting, please wait.');

const app = new Koa();
app.name = APP_NAME_LATIN + ' app';
const env = process.env.NODE_ENV || 'development';
// cache of a thousand days
const cacheOpts = { maxAge: 86400000, gzip: true };

app.keys = [config.get('session_key')];

const crypto_key = config.get('server_session_secret');

session(app, {
    maxAge: 1000 * 3600 * 24 * 60,
    crypto_key,
    key: config.get('session_cookie_key')
});
csrf(app);
// app.use(csrf.middleware);
app.use(flash({ key: 'flash' }));

function convertEntriesToArrays(obj) {
    return Object.keys(obj).reduce((result, key) => {
        result[key] = obj[key].split(/\s+/);
        return result;
    }, {});
}

// some redirects
app.use(function*(next) {
    // redirect to home page/feed if known account
    if (this.method === 'GET' && this.url === '/' && this.session.a) {
        this.status = 302;
        this.redirect(`/@${this.session.a}/feed`);
        return;
    }
    // normalize user name url from cased params
    if (
        this.method === 'GET' &&
            (routeRegex.UserProfile1.test(this.url) ||
                routeRegex.PostNoCategory.test(this.url))
    ) {
        const p = this.originalUrl.toLowerCase();
		let userCheck = "";
		if (routeRegex.Post.test(this.url)) {
			userCheck = p.split("/")[2].slice(1);
		} else {
			userCheck = p.split("/")[1].slice(1);
		}
		if (blockedUsers.includes(userCheck)) {
			console.log('Illegal content user found blocked', `@${userCheck}`);
			this.status = 451;
			return;
		}
        if (p !== this.originalUrl) {
            this.status = 301;
            this.redirect(p);
            return;
        }
    }
    // normalize top category filtering from cased params
    if (this.method === 'GET' && routeRegex.CategoryFilters.test(this.url)) {
        const p = this.originalUrl.toLowerCase();
        if (p !== this.originalUrl) {
            this.status = 301;
            this.redirect(p);
            return;
        }
    }
    // start registration process if user get to create_account page and has no id in session yet
    if (this.url === '/create_account' && !this.session.user) {
        this.status = 302;
        this.redirect('/enter_email');
        return;
    }
    // remember ch, cn, r url params in the session and remove them from url
    if (this.method === 'GET' && /\?[^\w]*(ch=|cn=|r=)/.test(this.url)) {
        let redir = this.url.replace(/((ch|cn|r)=[^&]+)/gi, r => {
            const p = r.split('=');
            if (p.length === 2) this.session[p[0]] = p[1];
            return '';
        });
        redir = redir.replace(/&&&?/, '');
        redir = redir.replace(/\?&?$/, '');
        console.log(`server redirect ${this.url} -> ${redir}`);
        this.status = 302;
        this.redirect(redir);
    } else {
        yield next;
    }
});

// load production middleware
if (env === 'production') {
    app.use(require('koa-conditional-get')());
    app.use(require('koa-etag')());
    app.use(require('koa-compressor')());
}

// Logging
if (env === 'production') {
    app.use(prod_logger());
} else {
    app.use(koa_logger());
}

app.use(helmet());

app.use(mount('/static', staticCache(path.join(__dirname, '../app/assets/static'), cacheOpts)));

app.use(
    mount('/robots.txt', function*() {
        this.set('Cache-Control', 'public, max-age=86400000');
        this.type = 'text/plain';
        this.body = 'User-agent: *\nAllow: /';
    })
);

app.use(
    mount('/service-worker.js', function*() {
        this.set('Cache-Control', 'public, max-age=7200000');
        this.type = 'application/javascript';
        const file_content = fs
            .readFileSync(path.join(__dirname, './service-worker.js'))
            .toString();
        // TODO: use APP_DOMAIN from client_config.js
        // actually use a config value for it
        this.body = file_content.replace(
            /\{DEFAULT_URL\}/i,
            'https://' + this.request.header.host
        );
    })
);

// set user's uid - used to identify users in logs and some other places
// FIXME SECURITY PRIVACY cycle this uid after a period of time
app.use(function*(next) {
    if (! /(\.js(on)?|\.css|\.map|\.ico|\.png|\.jpe?g)$/.test(this.url)) {
        const last_visit = this.session.last_visit;
        this.session.last_visit = new Date().getTime() / 1000 | 0;
        if (!this.session.uid) {
            this.session.uid = secureRandom.randomBuffer(13).toString('hex');
            this.session.new_visit = true;
        } else {
            this.session.new_visit = this.session.last_visit - last_visit > 1800;
        }
    }
    yield next;
});

useRedirects(app);
useEnterAndConfirmEmailPages(app);
useEnterAndConfirmMobilePages(app);
useUserJson(app);
usePostJson(app);

useAccountRecoveryApi(app);
useGeneralApi(app);
useNotificationsApi(app);

// helmet wants some things as bools and some as lists, makes config difficult.
// our config uses strings, this splits them to lists on whitespace.

if (env === 'production') {
    const helmetConfig = {
        directives: convertEntriesToArrays(config.get('helmet.directives')),
        reportOnly: config.get('helmet.reportOnly'),
        setAllHeaders: config.get('helmet.setAllHeaders')
    };
    helmetConfig.directives.reportUri = '/api/v1/csp_violation';
    app.use(helmet.contentSecurityPolicy(helmetConfig));
}

app.use(favicon(path.join(__dirname, '../app/assets/images/favicons/favicon.ico')));
app.use(mount('/favicons', staticCache(path.join(__dirname, '../app/assets/images/favicons'), cacheOpts)));
app.use(mount('/images', staticCache(path.join(__dirname, '../app/assets/images'), cacheOpts)));
app.use(mount('/legal', staticCache(path.join(__dirname, '../app/assets/legal'), cacheOpts)));
app.use(mount('/sitemap.xml', staticCache(path.join(__dirname, '../app/assets/sitemap.xml'), cacheOpts)));
app.use(mount('/robots.txt', staticCache(path.join(__dirname, '../app/assets/robots.txt'), cacheOpts)));
app.use(isBot());

// Proxy asset folder to webpack development server in development mode
if (env === 'development') {
    const webpack_dev_port = process.env.PORT
        ? parseInt(process.env.PORT) + 1
        : 8081;
    const proxyhost = `http://${(process.platform === 'win32') ? '127.0.0.1' : '0.0.0.0'}:${webpack_dev_port}`;
    console.log('proxying to webpack dev server at ' + proxyhost);
    const proxy = require('koa-proxy')({
        host: proxyhost,
        map: filePath => 'assets/' + filePath
    });
    app.use(mount('/assets', proxy));
} else {
    app.use(mount('/assets', staticCache(path.join(__dirname, '../dist'), cacheOpts)));
}

if (env !== 'test') {
    const appRender = require('./app_render');
    app.use(function*() {
        yield appRender(this);
        // if (app_router.dbStatus.ok) recordWebEvent(this, 'page_load');
        const bot = this.state.isBot;
        if (bot) {
            console.log(
                `  --> ${this.method} ${this.originalUrl} ${this.status} (BOT '${bot}')`
            );
        }
    });

    const argv = minimist(process.argv.slice(2));

    const port = process.env.PORT ? parseInt(process.env.PORT) : 8080;

    app.listen(port);

    // Tell parent process koa-server is started
    if (process.send) process.send('online');
    console.log(`Application started on port ${port}`);
}

module.exports = app;
<commit_msg>Add proxy routes<commit_after>// newrelic is not working with latest npm
//if(config.has('newrelic')) require('newrelic');

import path from 'path';
import fs from 'fs';
import Koa from 'koa';
import mount from 'koa-mount';
import helmet from 'koa-helmet';
import koa_logger from 'koa-logger';
import prod_logger from './prod_logger';
import favicon from 'koa-favicon';
import staticCache from 'koa-static-cache';
import useRedirects from './redirects';
import useGeneralApi from './api/general';
import useAccountRecoveryApi from './api/account_recovery';
import useNotificationsApi from './api/notifications';
import {proxyRoutes as useProxyRoutes} from './api/proxy';
import useEnterAndConfirmEmailPages from './server_pages/enter_confirm_email';
import useEnterAndConfirmMobilePages from './server_pages/enter_confirm_mobile';
import useUserJson from './json/user_json';
import usePostJson from './json/post_json';
import isBot from 'koa-isbot';
import session from './utils/cryptoSession';
import csrf from 'koa-csrf';
import flash from 'koa-flash';
import minimist from 'minimist';
import config from 'config';
import { routeRegex } from 'app/ResolveRoute';
import { blockedUsers } from 'app/utils/IllegalContent';
import secureRandom from 'secure-random';
import { APP_NAME_LATIN } from 'app/client_config';

console.log('application server starting, please wait.');

const app = new Koa();
app.name = APP_NAME_LATIN + ' app';
const env = process.env.NODE_ENV || 'development';
// cache of a thousand days
const cacheOpts = { maxAge: 86400000, gzip: true };

app.keys = [config.get('session_key')];

const crypto_key = config.get('server_session_secret');

session(app, {
    maxAge: 1000 * 3600 * 24 * 60,
    crypto_key,
    key: config.get('session_cookie_key')
});
csrf(app);
// app.use(csrf.middleware);
app.use(flash({ key: 'flash' }));

function convertEntriesToArrays(obj) {
    return Object.keys(obj).reduce((result, key) => {
        result[key] = obj[key].split(/\s+/);
        return result;
    }, {});
}

// some redirects
app.use(function*(next) {
    // redirect to home page/feed if known account
    if (this.method === 'GET' && this.url === '/' && this.session.a) {
        this.status = 302;
        this.redirect(`/@${this.session.a}/feed`);
        return;
    }
    // normalize user name url from cased params
    if (
        this.method === 'GET' &&
            (routeRegex.UserProfile1.test(this.url) ||
                routeRegex.PostNoCategory.test(this.url))
    ) {
        const p = this.originalUrl.toLowerCase();
		let userCheck = "";
		if (routeRegex.Post.test(this.url)) {
			userCheck = p.split("/")[2].slice(1);
		} else {
			userCheck = p.split("/")[1].slice(1);
		}
		if (blockedUsers.includes(userCheck)) {
			console.log('Illegal content user found blocked', `@${userCheck}`);
			this.status = 451;
			return;
		}
        if (p !== this.originalUrl) {
            this.status = 301;
            this.redirect(p);
            return;
        }
    }
    // normalize top category filtering from cased params
    if (this.method === 'GET' && routeRegex.CategoryFilters.test(this.url)) {
        const p = this.originalUrl.toLowerCase();
        if (p !== this.originalUrl) {
            this.status = 301;
            this.redirect(p);
            return;
        }
    }
    // start registration process if user get to create_account page and has no id in session yet
    if (this.url === '/create_account' && !this.session.user) {
        this.status = 302;
        this.redirect('/enter_email');
        return;
    }
    // remember ch, cn, r url params in the session and remove them from url
    if (this.method === 'GET' && /\?[^\w]*(ch=|cn=|r=)/.test(this.url)) {
        let redir = this.url.replace(/((ch|cn|r)=[^&]+)/gi, r => {
            const p = r.split('=');
            if (p.length === 2) this.session[p[0]] = p[1];
            return '';
        });
        redir = redir.replace(/&&&?/, '');
        redir = redir.replace(/\?&?$/, '');
        console.log(`server redirect ${this.url} -> ${redir}`);
        this.status = 302;
        this.redirect(redir);
    } else {
        yield next;
    }
});

// load production middleware
if (env === 'production') {
    app.use(require('koa-conditional-get')());
    app.use(require('koa-etag')());
    app.use(require('koa-compressor')());
}

// Logging
if (env === 'production') {
    app.use(prod_logger());
} else {
    app.use(koa_logger());
}

app.use(helmet());

app.use(mount('/static', staticCache(path.join(__dirname, '../app/assets/static'), cacheOpts)));

app.use(
    mount('/robots.txt', function*() {
        this.set('Cache-Control', 'public, max-age=86400000');
        this.type = 'text/plain';
        this.body = 'User-agent: *\nAllow: /';
    })
);

app.use(
    mount('/service-worker.js', function*() {
        this.set('Cache-Control', 'public, max-age=7200000');
        this.type = 'application/javascript';
        const file_content = fs
            .readFileSync(path.join(__dirname, './service-worker.js'))
            .toString();
        // TODO: use APP_DOMAIN from client_config.js
        // actually use a config value for it
        this.body = file_content.replace(
            /\{DEFAULT_URL\}/i,
            'https://' + this.request.header.host
        );
    })
);

// set user's uid - used to identify users in logs and some other places
// FIXME SECURITY PRIVACY cycle this uid after a period of time
app.use(function*(next) {
    if (! /(\.js(on)?|\.css|\.map|\.ico|\.png|\.jpe?g)$/.test(this.url)) {
        const last_visit = this.session.last_visit;
        this.session.last_visit = new Date().getTime() / 1000 | 0;
        if (!this.session.uid) {
            this.session.uid = secureRandom.randomBuffer(13).toString('hex');
            this.session.new_visit = true;
        } else {
            this.session.new_visit = this.session.last_visit - last_visit > 1800;
        }
    }
    yield next;
});

useRedirects(app);
useEnterAndConfirmEmailPages(app);
useEnterAndConfirmMobilePages(app);
useUserJson(app);
usePostJson(app);

useAccountRecoveryApi(app);
useGeneralApi(app);
useNotificationsApi(app);
useProxyRoutes(app);

// helmet wants some things as bools and some as lists, makes config difficult.
// our config uses strings, this splits them to lists on whitespace.

if (env === 'production') {
    const helmetConfig = {
        directives: convertEntriesToArrays(config.get('helmet.directives')),
        reportOnly: config.get('helmet.reportOnly'),
        setAllHeaders: config.get('helmet.setAllHeaders')
    };
    helmetConfig.directives.reportUri = '/api/v1/csp_violation';
    app.use(helmet.contentSecurityPolicy(helmetConfig));
}

app.use(favicon(path.join(__dirname, '../app/assets/images/favicons/favicon.ico')));
app.use(mount('/favicons', staticCache(path.join(__dirname, '../app/assets/images/favicons'), cacheOpts)));
app.use(mount('/images', staticCache(path.join(__dirname, '../app/assets/images'), cacheOpts)));
app.use(mount('/legal', staticCache(path.join(__dirname, '../app/assets/legal'), cacheOpts)));
app.use(mount('/sitemap.xml', staticCache(path.join(__dirname, '../app/assets/sitemap.xml'), cacheOpts)));
app.use(mount('/robots.txt', staticCache(path.join(__dirname, '../app/assets/robots.txt'), cacheOpts)));
app.use(isBot());

// Proxy asset folder to webpack development server in development mode
if (env === 'development') {
    const webpack_dev_port = process.env.PORT
        ? parseInt(process.env.PORT) + 1
        : 8081;
    const proxyhost = `http://${(process.platform === 'win32') ? '127.0.0.1' : '0.0.0.0'}:${webpack_dev_port}`;
    console.log('proxying to webpack dev server at ' + proxyhost);
    const proxy = require('koa-proxy')({
        host: proxyhost,
        map: filePath => 'assets/' + filePath
    });
    app.use(mount('/assets', proxy));
} else {
    app.use(mount('/assets', staticCache(path.join(__dirname, '../dist'), cacheOpts)));
}

if (env !== 'test') {
    const appRender = require('./app_render');
    app.use(function*() {
        yield appRender(this);
        // if (app_router.dbStatus.ok) recordWebEvent(this, 'page_load');
        const bot = this.state.isBot;
        if (bot) {
            console.log(
                `  --> ${this.method} ${this.originalUrl} ${this.status} (BOT '${bot}')`
            );
        }
    });

    const argv = minimist(process.argv.slice(2));

    const port = process.env.PORT ? parseInt(process.env.PORT) : 8080;

    app.listen(port);

    // Tell parent process koa-server is started
    if (process.send) process.send('online');
    console.log(`Application started on port ${port}`);
}

module.exports = app;
<|endoftext|>


<commit_before>let should = require('should');
let expect = require('chai').expect;
let jsdom = require('jsdom');
let {JSDOM} = jsdom;
let Shell;
describe('Shell', () => {
    let {document} = (new JSDOM('<!doctype html>')).window;
    global.document = document;
    global.window = document.defaultView;

    before(() => {
        Shell = require('../lib/shell');
    });

    it('should initialize without error', () => {
        (() => expect(new Shell()).to.be.an.instanceof(Shell) ).should.not.throw();
    });

    describe('Element', () => {
        context('when not present', () => {
            it('should be empty', () => {
                expect(new Shell()).to.have.property('el', null);
            });
        });

        context('when present', () => {
            let div;
            let shell;

            before(() => {
                div = document.createElement('div');
                div.setAttribute('id', 'shell');
                document.body.appendChild(div);
                shell = new Shell('#shell');
            });

            it('should be the DOM object of the element', () => {
                expect(shell.el[0]).to.not.be.undefined;
                expect(shell.el[0]).to.equal(div);
            });
        });
    });
});<commit_msg>Change required library with minified one<commit_after>let should = require('should');
let expect = require('chai').expect;
let jsdom = require('jsdom');
let {JSDOM} = jsdom;
let Shell;
describe('Shell', () => {
    let {document} = (new JSDOM('<!doctype html>')).window;
    global.document = document;
    global.window = document.defaultView;

    before(() => {
        Shell = require('../lib/shell.min');
    });

    it('should initialize without error', () => {
        (() => expect(new Shell()).to.be.an.instanceof(Shell) ).should.not.throw();
    });

    describe('Element', () => {
        context('when not present', () => {
            it('should be empty', () => {
                expect(new Shell()).to.have.property('el', null);
            });
        });

        context('when present', () => {
            let div;
            let shell;

            before(() => {
                div = document.createElement('div');
                div.setAttribute('id', 'shell');
                document.body.appendChild(div);
                shell = new Shell('#shell');
            });

            it('should be the DOM object of the element', () => {
                expect(shell.el[0]).to.not.be.undefined;
                expect(shell.el[0]).to.equal(div);
            });
        });
    });
});<|endoftext|>


<commit_before>// Mocha test file.

const maowtm = require('..');
const should = require('should');
const request = require('supertest');
const lwip = require('lwip');

const DB = process.env.MONGODB, REDIS = process.env.REDIS;

try {
    DB.should.be.a.String().and.should.not.be.empty();
    REDIS.should.be.a.String().and.should.not.be.empty();
} catch (e) {
    console.log("You need to provide env MONGODB and REDIS. E.g. MONGODB=127.0.0.1 REDIS=127.0.0.1");
    process.exit(1);
}

describe('new maowtm(...)', function() {
    it('should initialize', function(done) {
        var destory;
        new maowtm({
            db: DB,
            redis: REDIS,
            callback: function (err, app, finalize) {
                destory = finalize;
                if (err) {
                    done(err);
                    return;
                }
                done();
            }
        });
        after(function () {
            destory.should.be.a.Function();
            destory();
        });
    });

    function makeErrorCallback(done, match) {
        return function (err, app, destory) {
            if (!err) {
                done(destory, new Error("No error was thrown"));
            } else {
                if (app)
                    done(destory, new Error("Error was thrown, but app is not null."));
                else {
                    err.should.be.an.Object();
                    err.message.should.match(match);
                    done(destory);
                }
            }
        };
    }

    it('should throw error when db is not open', function(done) {
        var destory;
        new maowtm({
            db: "127.255.255.255",
            redis: REDIS,
            callback: makeErrorCallback(function (d, err) {
                destory = d;
                done(err);
            }, /connect/)
        });
        after(function () {
            destory.should.be.a.Function();
            destory();
        });
    });
    it('should throw error when no SSL certificate was given', function(done) {
        var destory;
        new maowtm({
            db: DB,
            redis: REDIS,
            listen: "127.6.0.233",
            callback: makeErrorCallback(function (d, err) {
                destory = d;
                done(err);
            }, /SSL/)
        });
        after(function () {
            destory.should.be.a.Function();
            destory();
        });
    });

    it('should answer acme-challenge', function(done) {
        var testACME, destory;
        var acmeString = "stubstubstub";
        new maowtm({
            db: DB,
            redis: REDIS,
            callback: function (err, app, finalize) {
                destory = finalize;
                if (err) {
                    done(err);
                    return;
                }
                testACME(app);
            },
            acme: acmeString
        });
        after(function () {
            destory.should.be.a.Function();
            destory();
        });

        testACME = function(app) {
            request(app)
                .get('/.well-known/acme-challenge/acmehhh')
                .expect(200)
                .expect(acmeString)
                .end(done);
        };
    });
    it('should redirect http to https', function(done) {
        var destory, test;
        new maowtm({
            db: DB,
            redis: REDIS,
            callback: function (err, app, finalize) {
                destory = finalize;
                if (err) {
                    done(err);
                    return;
                }
                test(app);
            }
        });
        after(function () {
            destory.should.be.a.Function();
            destory();
        });
        var test = function(app) {
            request(app)
                .get('/somefilename')
                .expect(302)
                .expect('Location', /^https:\/\//)
                .end(done);
        }
    });
});

(function() {
    var destory, appTest;
    new maowtm({
        db: DB,
        redis: REDIS,
        callback: function (err, app, finalize) {
            destory = finalize;
            if (err) {
                throw err;
            }
            appTest(app);
        },
        mockSecure: true
    });

    function appTest(app) {
        describe('Application', function() {
            after(function() {
                destory();
            });

            it('should send http protection headers', function(done) {
                function setExpects(agent, next) {
                    agent.expect("Strict-Transport-Security", /max-age=\d+/);
                    agent.expect("Strict-Transport-Security", /includeSubdomains/);
                    agent.expect("Strict-Transport-Security", /preload/);
                    agent.expect("X-XSS-Protection", /1/);
                    agent.expect("X-Frame-Options", /sameorigin/);
                    agent.expect("X-Content-Type-Options", /nosniff/);
                    agent.end(function (err) {
                        switch (true) {
                            case err:
                                done(err);
                                break;
                            case next:
                                next();
                                break;
                            default:
                                done();
                                break;
                        }
                    });
                    return agent;
                }
                var req = request(app);
                var tests = {
                    root: function() {
                        setExpects(req.get('/'), tests.notfind);
                    },
                    notfind: function() {
                        setExpects(req.get('/404'));
                    }
                };
                tests.root();
            });

            it('should redirect to directory', function (done) {
                request(app)
                    .get('/404')
                    .expect(302)
                    .expect('Location', '/404/')
                    .end(function (err) {
                        if (err) {
                            done(err);
                            return;
                        }
                        request(app)
                            .get('/404/')
                            .expect(404)
                            .end(done);
                    });
            });

            function notRedirected(res) {
                if (res.header.location)
                    throw new Error("Location header should not exist");
                res.status.should.not.be.exactly(302);
            }
            it('should not redirect to directory (img.maowtm.org)', function (done) {
                request(app)
                    .get('/404')
                    .set('Host', 'img.maowtm.org')
                    .expect(notRedirected)
                    .expect(404)
                    .end(function (err) {
                        if (err) {
                            done(err);
                            return;
                        }
                        request(app)
                            .get('/404/')
                            .set('Host', 'img.maowtm.org')
                            .expect(notRedirected)
                            .end(done);
                    });
            });
            it('should not redirect to directory (static.maowtm.org)', function (done) {
                request(app)
                    .get('/404')
                    .set('Host', 'static.maowtm.org')
                    .expect(notRedirected)
                    .end(function (err) {
                        if (err) {
                            done(err);
                            return;
                        }
                        request(app)
                            .get('/404/')
                            .set('Host', 'static.maowtm.org')
                            .expect(notRedirected)
                            .end(done);
                    });
            });
        });
    }
})();

(function() {
    var destory;
    var maow = new maowtm({
        db: DB,
        redis: REDIS,
        callback: function (err, app, finalize) {
            destory = finalize;
            if (err) {
                throw err;
            }
            imageTest(app);
        },
        mockSecure: true
    });
    after(function() {
        destory();
    });

    function imageTest(app) {
        const imageTypeMatch = /^image\/[a-z]+$/;
        function assertWidthAtLeast(res, done, widthTest, withIn) {
            try {
                res.type.should.match(imageTypeMatch);
                var ext = res.type.split('/')[1];
                ext.should.be.a.String().and.should.not.be.empty();
                lwip.open(res.body, ext, function(err, lwipImg) {
                    if (err) {
                        done(err);
                        return;
                    }
                    var width = lwipImg.width();
                    if (width >= widthTest && width - widthTest <= withIn) {
                        done();
                    } else {
                        done(new Error("expected width to be " + widthTest + "(+" + withIn + "), but " + width + " get."));
                    }
                });
            } catch (e) {
                done(e);
            }
        }
        var image = maow.db.model('image');
        var cachedScale = maow.db.model('cachedScale');
        describe('static::image fetching', function() {
            before(function (done) {
                if (!image || !cachedScale) {
                    done(new Error("database not working."));
                    return;
                }
                console.log(" -> Removing all cachedScale of avatar.png");
                image.findOne({name: "avatar.png"}, function (err, imgDoc) {
                    if (err) {
                        done(err);
                    } else {
                        if (imgDoc) {
                            cachedScale.remove({imgId: imgDoc._id}, done);
                        }
                    }
                })
            });
            it('should contain avatar.png', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .expect(200)
                    .expect("Content-Type", imageTypeMatch)
                    .end(done);
            });
            it('should return image with the width specified', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: 100})
                    .expect(200)
                    .expect("Content-Type", imageTypeMatch)
                    .end(function (err, res) {
                        if (err) {
                            done(err);
                            return;
                        }
                        assertWidthAtLeast(res, done, 100, 50);
                    });
            });
            it('should redirect for width bigger than the image itself', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: 10000})
                    .expect(302)
                    .expect("Location", "/avatar.png")
                    .end(done);
            });
            it('should redirect for illegal width (0)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: 0})
                    .expect(302)
                    .expect("Location", "/avatar.png")
                    .end(done);
            });
            it('should redirect for illegal width (negative)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: -10000})
                    .expect(302)
                    .expect("Location", "/avatar.png")
                    .end(done);
            });
            it('should redirect for illegal width (not number)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: "null"})
                    .expect(302)
                    .expect("Location", "/avatar.png")
                    .end(done);
            });
            it('should redirect for not integer width', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: 100.25})
                    .expect(302)
                    .expect("Location", "/avatar.png?width=100")
                    .end(done);
            });
            it('should redirect for illegal width (not number, preserve other arguments)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('host', 'img.maowtm.org')
                    .query({width: "null", other: "yes"})
                    .expect(302)
                    .expect("location", "/avatar.png?other=yes")
                    .end(done);
            });
            it('should redirect for not integer width (preserve other arguments)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .query({width: 100.25, other: "yes"})
                    .set('Host', 'img.maowtm.org')
                    .expect(302)
                    .expect("Location", /^\/avatar.png\?(width|other)=/)
                    .expect("Location", /width=100/)
                    .expect("Location", /other=yes/)
                    .expect("Location", /(100|yes)$/)
                    .end(done);
            });
            it('should give 404 for no existing image', function(done) {
                request(app)
                    .get('/404')
                    .set('Host', 'img.maowtm.org')
                    .expect(404)
                    .end(done);
            });
            it('should give 404 for no existing image (with width given)', function(done) {
                request(app)
                    .get('/404')
                    .query({width: 100})
                    .set('Host', 'img.maowtm.org')
                    .expect(404)
                    .end(done);
            });
            it('should return cached version if possible', function(done) {
                var stub = "Stub!";
                function before (done) {
                    image.findOne({name: "avatar.png"}, function(err, imgDoc) {
                        if (err) {
                            done(err);
                            return;
                        }
                        if (!imgDoc) {
                            done(new Error("Image wasn't cached"));
                            return;
                        }
                        var cache = new cachedScale({
                            imgId: imgDoc._id,
                            scale: 300,
                            data: new Buffer(stub, "utf-8")
                        });
                        cache.save(function (err) {
                            if (err) {
                                done(err);
                                return;
                            }
                            console.log(" -> saved fake cache.");
                            done();
                        });
                    });
                };
                before(function(err) {
                    if (err) {
                        done(err);
                        return;
                    }
                    request(app)
                        .get('/avatar.png')
                        .set('Host', 'img.maowtm.org')
                        .query({width: 300})
                        .expect(200)
                        .expect("Content-Type", imageTypeMatch)
                        .end(function (err, res) {
                            if (err) {
                                done(err);
                                return;
                            }
                            var bufstr = res.body.toString("utf-8");
                            if (bufstr == stub) {
                                done();
                            } else {
                                debugger;
                                done(new Error("Image was not read from cache."));
                            }
                        });
                });
            });
        });
    }
})();
<commit_msg>After in "it" will not work.<commit_after>// Mocha test file.

const maowtm = require('..');
const should = require('should');
const request = require('supertest');
const lwip = require('lwip');

const DB = process.env.MONGODB, REDIS = process.env.REDIS;

try {
    DB.should.be.a.String().and.should.not.be.empty();
    REDIS.should.be.a.String().and.should.not.be.empty();
} catch (e) {
    console.log("You need to provide env MONGODB and REDIS. E.g. MONGODB=127.0.0.1 REDIS=127.0.0.1");
    process.exit(1);
}

describe('new maowtm(...)', function() {
    function makeDone(_done, destory) {
        return function(err) {
            try {
                destory.should.be.a.Function();
                destory();
                console.log(" -> Destroyed maowtm instance.");
            } catch (e) {
                _done(e);
                return;
            }
            _done(err);
        };
    }
    it('should initialize', function(done) {
        var destory;
        done = makeDone(done, function() {
            destory();
        });
        new maowtm({
            db: DB,
            redis: REDIS,
            callback: function (err, app, finalize) {
                destory = finalize;
                if (err) {
                    done(err);
                    return;
                }
                done();
            }
        });
    });

    function makeErrorCallback(done, match) {
        return function (err, app, destory) {
            if (!err) {
                done(destory, new Error("No error was thrown"));
            } else {
                if (app)
                    done(destory, new Error("Error was thrown, but app is not null."));
                else {
                    err.should.be.an.Object();
                    err.message.should.match(match);
                    done(destory);
                }
            }
        };
    }

    it('should throw error when db is not open', function(done) {
        var destory;
        done = makeDone(done, function() {
            destory();
        });
        new maowtm({
            db: "127.255.255.255",
            redis: REDIS,
            callback: makeErrorCallback(function (d, err) {
                destory = d;
                done(err);
            }, /connect/)
        });
    });
    it('should throw error when no SSL certificate was given', function(done) {
        var destory;
        done = makeDone(done, function() {
            destory();
        });
        new maowtm({
            db: DB,
            redis: REDIS,
            listen: "127.6.0.233",
            callback: makeErrorCallback(function (d, err) {
                destory = d;
                done(err);
            }, /SSL/)
        });
    });

    it('should answer acme-challenge', function(done) {
        var testACME;
        var destory;
        done = makeDone(done, function() {
            destory();
        });
        var acmeString = "stubstubstub";
        new maowtm({
            db: DB,
            redis: REDIS,
            callback: function (err, app, finalize) {
                destory = finalize;
                if (err) {
                    done(err);
                    return;
                }
                testACME(app);
            },
            acme: acmeString
        });

        testACME = function(app) {
            request(app)
                .get('/.well-known/acme-challenge/acmehhh')
                .expect(200)
                .expect(acmeString)
                .end(done);
        };
    });
    it('should redirect http to https', function(done) {
        var test;
        var destory;
        done = makeDone(done, function() {
            destory();
        });
        new maowtm({
            db: DB,
            redis: REDIS,
            callback: function (err, app, finalize) {
                destory = finalize;
                if (err) {
                    done(err);
                    return;
                }
                test(app);
            }
        });
        var test = function(app) {
            request(app)
                .get('/somefilename')
                .expect(302)
                .expect('Location', /^https:\/\//)
                .end(done);
        }
    });
});

(function() {
    var destory, appTest;
    new maowtm({
        db: DB,
        redis: REDIS,
        callback: function (err, app, finalize) {
            destory = finalize;
            if (err) {
                throw err;
            }
            appTest(app);
        },
        mockSecure: true
    });

    function appTest(app) {
        describe('Application', function() {
            after(function() {
                destory();
                console.log(" -> Destroyed maowtm instance.");
            });

            it('should send http protection headers', function(done) {
                function setExpects(agent, next) {
                    agent.expect("Strict-Transport-Security", /max-age=\d+/);
                    agent.expect("Strict-Transport-Security", /includeSubdomains/);
                    agent.expect("Strict-Transport-Security", /preload/);
                    agent.expect("X-XSS-Protection", /1/);
                    agent.expect("X-Frame-Options", /sameorigin/);
                    agent.expect("X-Content-Type-Options", /nosniff/);
                    agent.end(function (err) {
                        switch (true) {
                            case err:
                                done(err);
                                break;
                            case next:
                                next();
                                break;
                            default:
                                done();
                                break;
                        }
                    });
                    return agent;
                }
                var req = request(app);
                var tests = {
                    root: function() {
                        setExpects(req.get('/'), tests.notfind);
                    },
                    notfind: function() {
                        setExpects(req.get('/404'));
                    }
                };
                tests.root();
            });

            it('should redirect to directory', function (done) {
                request(app)
                    .get('/404')
                    .expect(302)
                    .expect('Location', '/404/')
                    .end(function (err) {
                        if (err) {
                            done(err);
                            return;
                        }
                        request(app)
                            .get('/404/')
                            .expect(404)
                            .end(done);
                    });
            });

            function notRedirected(res) {
                if (res.header.location)
                    throw new Error("Location header should not exist");
                res.status.should.not.be.exactly(302);
            }
            it('should not redirect to directory (img.maowtm.org)', function (done) {
                request(app)
                    .get('/404')
                    .set('Host', 'img.maowtm.org')
                    .expect(notRedirected)
                    .expect(404)
                    .end(function (err) {
                        if (err) {
                            done(err);
                            return;
                        }
                        request(app)
                            .get('/404/')
                            .set('Host', 'img.maowtm.org')
                            .expect(notRedirected)
                            .end(done);
                    });
            });
            it('should not redirect to directory (static.maowtm.org)', function (done) {
                request(app)
                    .get('/404')
                    .set('Host', 'static.maowtm.org')
                    .expect(notRedirected)
                    .end(function (err) {
                        if (err) {
                            done(err);
                            return;
                        }
                        request(app)
                            .get('/404/')
                            .set('Host', 'static.maowtm.org')
                            .expect(notRedirected)
                            .end(done);
                    });
            });
        });
    }
})();

(function() {
    var destory;
    var maow = new maowtm({
        db: DB,
        redis: REDIS,
        callback: function (err, app, finalize) {
            destory = finalize;
            if (err) {
                throw err;
            }
            imageTest(app);
        },
        mockSecure: true
    });

    function imageTest(app) {
        const imageTypeMatch = /^image\/[a-z]+$/;
        function assertWidthAtLeast(res, done, widthTest, withIn) {
            try {
                res.type.should.match(imageTypeMatch);
                var ext = res.type.split('/')[1];
                ext.should.be.a.String().and.should.not.be.empty();
                lwip.open(res.body, ext, function(err, lwipImg) {
                    if (err) {
                        done(err);
                        return;
                    }
                    var width = lwipImg.width();
                    if (width >= widthTest && width - widthTest <= withIn) {
                        done();
                    } else {
                        done(new Error("expected width to be " + widthTest + "(+" + withIn + "), but " + width + " get."));
                    }
                });
            } catch (e) {
                done(e);
            }
        }
        var image = maow.db.model('image');
        var cachedScale = maow.db.model('cachedScale');
        describe('static::image fetching', function() {
            before(function (done) {
                if (!image || !cachedScale) {
                    done(new Error("database not working."));
                    return;
                }
                console.log(" -> Removing all cachedScale of avatar.png");
                image.findOne({name: "avatar.png"}, function (err, imgDoc) {
                    if (err) {
                        done(err);
                    } else {
                        if (imgDoc) {
                            cachedScale.remove({imgId: imgDoc._id}, done);
                        }
                    }
                })
            });
            after(function() {
                destory();
                console.log(" -> Destroyed maowtm instance.");
            });
            it('should contain avatar.png', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .expect(200)
                    .expect("Content-Type", imageTypeMatch)
                    .end(done);
            });
            it('should return image with the width specified', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: 100})
                    .expect(200)
                    .expect("Content-Type", imageTypeMatch)
                    .end(function (err, res) {
                        if (err) {
                            done(err);
                            return;
                        }
                        assertWidthAtLeast(res, done, 100, 50);
                    });
            });
            it('should redirect for width bigger than the image itself', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: 10000})
                    .expect(302)
                    .expect("Location", "/avatar.png")
                    .end(done);
            });
            it('should redirect for illegal width (0)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: 0})
                    .expect(302)
                    .expect("Location", "/avatar.png")
                    .end(done);
            });
            it('should redirect for illegal width (negative)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: -10000})
                    .expect(302)
                    .expect("Location", "/avatar.png")
                    .end(done);
            });
            it('should redirect for illegal width (not number)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: "null"})
                    .expect(302)
                    .expect("Location", "/avatar.png")
                    .end(done);
            });
            it('should redirect for not integer width', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('Host', 'img.maowtm.org')
                    .query({width: 100.25})
                    .expect(302)
                    .expect("Location", "/avatar.png?width=100")
                    .end(done);
            });
            it('should redirect for illegal width (not number, preserve other arguments)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .set('host', 'img.maowtm.org')
                    .query({width: "null", other: "yes"})
                    .expect(302)
                    .expect("location", "/avatar.png?other=yes")
                    .end(done);
            });
            it('should redirect for not integer width (preserve other arguments)', function(done) {
                request(app)
                    .get('/avatar.png')
                    .query({width: 100.25, other: "yes"})
                    .set('Host', 'img.maowtm.org')
                    .expect(302)
                    .expect("Location", /^\/avatar.png\?(width|other)=/)
                    .expect("Location", /width=100/)
                    .expect("Location", /other=yes/)
                    .expect("Location", /(100|yes)$/)
                    .end(done);
            });
            it('should give 404 for no existing image', function(done) {
                request(app)
                    .get('/404')
                    .set('Host', 'img.maowtm.org')
                    .expect(404)
                    .end(done);
            });
            it('should give 404 for no existing image (with width given)', function(done) {
                request(app)
                    .get('/404')
                    .query({width: 100})
                    .set('Host', 'img.maowtm.org')
                    .expect(404)
                    .end(done);
            });
            it('should return cached version if possible', function(done) {
                var stub = "Stub!";
                function before (done) {
                    image.findOne({name: "avatar.png"}, function(err, imgDoc) {
                        if (err) {
                            done(err);
                            return;
                        }
                        if (!imgDoc) {
                            done(new Error("Image wasn't cached"));
                            return;
                        }
                        var cache = new cachedScale({
                            imgId: imgDoc._id,
                            scale: 300,
                            data: new Buffer(stub, "utf-8")
                        });
                        cache.save(function (err) {
                            if (err) {
                                done(err);
                                return;
                            }
                            console.log(" -> saved fake cache.");
                            done();
                        });
                    });
                };
                before(function(err) {
                    if (err) {
                        done(err);
                        return;
                    }
                    request(app)
                        .get('/avatar.png')
                        .set('Host', 'img.maowtm.org')
                        .query({width: 300})
                        .expect(200)
                        .expect("Content-Type", imageTypeMatch)
                        .end(function (err, res) {
                            if (err) {
                                done(err);
                                return;
                            }
                            var bufstr = res.body.toString("utf-8");
                            if (bufstr == stub) {
                                done();
                            } else {
                                debugger;
                                done(new Error("Image was not read from cache."));
                            }
                        });
                });
            });
        });
    }
})();
<|endoftext|>


<commit_before>var restify = require('restify');
var ecstatic = require('ecstatic');
var dataStoreController = require('./controllers/DataStoreController.js');
var dbController = new dataStoreController({username:'ubuntu', password:'', hostname:'54.186.20.243'});
var gameMGMT = require('./models/GameManagement.js');

var server = restify.createServer();
server.pre(ecstatic({ root: __dirname + '/public'}));

server.listen(process.env.PORT || 80, process.env.IP);
console.log("Server started & listening on port 80");

server.use(restify.queryParser());

server.get("/queueForGame", function(request, response, next){
	//We need to Setup a new game in the database between two players
	//Create a flat file for the board data
	//Then send back the board object
	console.log("Queue request received from Client " + request.params.fun);
	response.writeHead(200, {"content-type": "application/json"});
	response.end(JSON.stringify({}));
	return next();
});

server.get("/createNewGame", function(request, response, next){
	//We need to Setup a new game in the database between two players
	//Create a flat file for the board data
	//Then send back the board object
	console.log("New game request received from Client " + request.params.fun);
	response.writeHead(200, {"content-type": "application/json"});
	response.end("Game created Successfully");
	return next();
});

server.get("/initialize", function(request, response, next) {
	console.log("Received initialize request from Client " + request.params.userid);
	//Setup a Client Id if the id passed was not found in the database
	//We have to verify that the user id passed is valid (i.e. > 0 or undefined)
	//**Account for the fact that a user id might be a string** - Right now only numbers are allowed
	//Validate the dbController Object
	var text = {};
	var id = request.params.userid;
	if (id === undefined || id === 'undefined' || id > 0) {
		//valid values: either the user doesn't have an id or the user does
		if (id !== undefined && id !== 'undefined')
		{
			console.log('Server gets here 1: ' + id);
			//call DataStoreController and get a the user's information
			dbController.getUserInformation(id, function(newUserInfo){
				var userInfo = newUserInfo[0];
				console.log('Server gets here 2: ' + userInfo.userID);

				//Get a list of games on the server
				dbController.getListOfGames(function(gameList){
					var games = gameList;
					console.log("List of games returns " + games);
					/*
					//get a list of active games for the user
					//use Jason's method
					gameMGMT.findByUser(userInfo.userID, function(activeGames){
						//for now, send back the user and game list
						console.log("Game MGMT returns " + activeGames);
						debugger
						text = {'user': userInfo, 'availableGames': games, 'active': activeGames};

						response.writeHead( 200, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
						response.write(JSON.stringify(text));
						response.end();
						return next();
					});*/
					text = {'user': userInfo, 'availableGames': games, 'active': {}};

					response.writeHead( 200, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
					response.write(JSON.stringify(text));
					response.end();
					return next();
				});
			});
		}
		else
		{
			console.log('Server gets here 3: ' + id);
			//call DatabaseController and get a new userID for the user
			dbController.getNewUserInfo( function(newUserInfo){
				var userInfo = newUserInfo[0];
				console.log('Server gets here 4: ' + userInfo.userID);

				//Get a list of games on the server
				dbController.getListOfGames(function(gameList){
					var games = gameList;
					console.log("List of games returns " + games);
					/*
					//get a list of active games for the user
					//use Jason's method
					gameMGMT.findByUser(userInfo.userID, function(activeGames){
						//for now, send back the user and game list
						console.log("Game MGMT returns " + activeGames);
						debugger
						text = {'user': userInfo, 'availableGames': games, 'active': activeGames};

						response.writeHead( 200, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
						response.write(JSON.stringify(text));
						response.end();
						return next();
					});*/
					text = {'user': userInfo, 'availableGames': games, 'active': {}};

					response.writeHead( 200, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
					response.write(JSON.stringify(text));
					response.end();
					return next();
				});
			});
		}
	}
	else
	{
		//response not found (404) but I guess any error code would work
		response.writeHead( 404, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
		response.write(JSON.stringify(text));
		response.end();
		return next();
	}
	//return next();
});

server.get("/listOfGames", function(request, response, next)
{
	console.log("List of games request received from the Client");

	//Validate the dbController Object
	dbController.getListOfGames(function(games){
		response.writeHead(200, {"content-type": "application/json", 'Access-Control-Allow-Origin' : '*'});
		response.write(JSON.stringify(games));
		response.end();
	});
	return next();
});

<commit_msg>Modified the server to parse a user's clientID to an Integer before sending it to the dataStoreController<commit_after>var restify = require('restify');
var ecstatic = require('ecstatic');
var dataStoreController = require('./controllers/DataStoreController.js');
var dbController = new dataStoreController({username:'ubuntu', password:'', hostname:'54.186.20.243'});
var gameMGMT = require('./models/GameManagement.js');

var server = restify.createServer();
server.pre(ecstatic({ root: __dirname + '/public'}));

server.listen(process.env.PORT || 80, process.env.IP);
console.log("Server started & listening on port 80");

server.use(restify.queryParser());

server.get("/queueForGame", function(request, response, next){
	//We need to Setup a new game in the database between two players
	//Create a flat file for the board data
	//Then send back the board object
	console.log("Queue request received from Client " + request.params.fun);
	response.writeHead(200, {"content-type": "application/json"});
	response.end(JSON.stringify({}));
	return next();
});

server.get("/createNewGame", function(request, response, next){
	//We need to Setup a new game in the database between two players
	//Create a flat file for the board data
	//Then send back the board object
	console.log("New game request received from Client " + request.params.fun);
	response.writeHead(200, {"content-type": "application/json"});
	response.end("Game created Successfully");
	return next();
});

server.get("/initialize", function(request, response, next) {
	console.log("Received initialize request from Client " + request.params.userid);
	//Setup a Client Id if the id passed was not found in the database
	//We have to verify that the user id passed is valid (i.e. > 0 or undefined)
	//**Account for the fact that a user id might be a string** - Right now only numbers are allowed
	//Validate the dbController Object
	var text = {};
	var id = request.params.userid;
	if (id === undefined || id === 'undefined' || id > 0) {
		//valid values: either the user doesn't have an id or the user does
		if (id !== undefined && id !== 'undefined')
		{
			console.log('Server gets here 1: ' + id);
			//call DataStoreController and get a the user's information
			dbController.getUserInformation( parseInt(id), function(newUserInfo){
				var userInfo = newUserInfo[0];
				console.log('Server gets here 2: ' + userInfo.userID);

				//Get a list of games on the server
				dbController.getListOfGames(function(gameList){
					var games = gameList;
					console.log("List of games returns " + games);
					/*
					//get a list of active games for the user
					//use Jason's method
					gameMGMT.findByUser(userInfo.userID, function(activeGames){
						//for now, send back the user and game list
						console.log("Game MGMT returns " + activeGames);
						debugger
						text = {'user': userInfo, 'availableGames': games, 'active': activeGames};

						response.writeHead( 200, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
						response.write(JSON.stringify(text));
						response.end();
						return next();
					});*/
					text = {'user': userInfo, 'availableGames': games, 'active': {}};

					response.writeHead( 200, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
					response.write(JSON.stringify(text));
					response.end();
					return next();
				});
			});
		}
		else
		{
			console.log('Server gets here 3: ' + id);
			//call DatabaseController and get a new userID for the user
			dbController.getNewUserInfo( function(newUserInfo){
				var userInfo = newUserInfo[0];
				console.log('Server gets here 4: ' + userInfo.userID);

				//Get a list of games on the server
				dbController.getListOfGames(function(gameList){
					var games = gameList;
					console.log("List of games returns " + games);
					/*
					//get a list of active games for the user
					//use Jason's method
					gameMGMT.findByUser(userInfo.userID, function(activeGames){
						//for now, send back the user and game list
						console.log("Game MGMT returns " + activeGames);
						debugger
						text = {'user': userInfo, 'availableGames': games, 'active': activeGames};

						response.writeHead( 200, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
						response.write(JSON.stringify(text));
						response.end();
						return next();
					});*/
					text = {'user': userInfo, 'availableGames': games, 'active': {}};

					response.writeHead( 200, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
					response.write(JSON.stringify(text));
					response.end();
					return next();
				});
			});
		}
	}
	else
	{
		//response not found (404) but I guess any error code would work
		response.writeHead( 404, {'content-type': 'application/json', 'Access-Control-Allow-Origin' : '*'});
		response.write(JSON.stringify(text));
		response.end();
		return next();
	}
	//return next();
});

server.get("/listOfGames", function(request, response, next)
{
	console.log("List of games request received from the Client");

	//Validate the dbController Object
	dbController.getListOfGames(function(games){
		response.writeHead(200, {"content-type": "application/json", 'Access-Control-Allow-Origin' : '*'});
		response.write(JSON.stringify(games));
		response.end();
	});
	return next();
});

<|endoftext|>


<commit_before>var color = require(".."),
	assert = require("assert");

assert.deepEqual(color("blue").toRgbaArray(), [0, 0, 255, 1]);
assert.deepEqual(color("blue").toHslaArray(), [240, 100, 50, 1]);
assert.deepEqual(color("blue").toHexString(), '#0000ff');
assert.deepEqual(color("rgb(255, 255, 255)").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("rgb(100%, 100%, 100%)").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("rgb(100%, 100%, 100%)").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("rgba(100%, 100%, 100%, .5)").toHexString(), '#ffffff7f');
assert.deepEqual(color("rgba(255, 255, 255, .5)").toRgbaArray(), [255, 255, 255, .5]);
assert.deepEqual(color("rgba(255, 255, 255, .5)").toHslaArray(), [0, 0, 100, .5]);
assert.equal(color().fromRgb([255, 255, 255]).toRgbString(), 'rgb(255, 255, 255)');
assert.equal(color().fromRgba([255, 255, 255, 1]).toRgbString(), 'rgb(255, 255, 255)');
assert.equal(color().fromRgba([255, 255, 255, .5]).toRgbString(), 'rgba(255, 255, 255, 0.5)');
assert.equal(color().fromRgba([255, 255, 255, 1]).toHslString(), 'hsl(0, 0%, 100%)');
assert.equal(color().fromRgba([255, 255, 255, .5]).toHslString(), 'hsla(0, 0%, 100%, 0.5)');
assert.equal(color().fromRgba([255, 255, 255, 1]).toHexString(), '#ffffff');
assert.equal(color().fromRgba([255, 255, 255, .5]).toHexString(), '#ffffff7f');
assert.deepEqual(color("hsl(0, 0%, 100%)").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("hsl(0, 0%, 100%)").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("hsla(0, 0%, 100%, .5)").toHslaArray(), [0, 0, 100, .5]);
assert.deepEqual(color("hsla(0, 0%, 100%, .5)").toRgbaArray(), [255, 255, 255, .5]);
assert.equal(color().fromHsl([0, 0, 100]).toHslString(), 'hsl(0, 0%, 100%)');
assert.equal(color().fromHsla([0, 0, 100, 1]).toRgbString(), 'rgb(255, 255, 255)');
assert.equal(color().fromHsla([0, 0, 100, .5]).toRgbString(), 'rgba(255, 255, 255, 0.5)');
assert.equal(color().fromHsla([0, 0, 100, 1]).toHslString(), 'hsl(0, 0%, 100%)');
assert.equal(color().fromHsla([0, 0, 100, .5]).toHslString(), 'hsla(0, 0%, 100%, 0.5)');
assert.equal(color().fromHsla([0, 0, 100, 1]).toHexString(), '#ffffff');
assert.equal(color().fromHsla([0, 0, 100, .5]).toHexString(), '#ffffff7f');
assert.deepEqual(color("#ffffff").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("#ffffff").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("#ffffffff").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("#ffffffff").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("#fff").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("#fff").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("#ffff").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("#ffff").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("#ffffff7f").toRgbaArray(), [255, 255, 255, .5]);
assert.deepEqual(color("#ffffff7f").toHslaArray(), [0, 0, 100, .5]);
assert.deepEqual(color("#ffffff").toHexString(), '#ffffff');
assert.equal(color("#ffffff").toRgbString(), 'rgb(255, 255, 255)');
assert.equal(color("#ffffff7f").toRgbString(), 'rgba(255, 255, 255, 0.5)');
assert.equal(color("#ffffff").toHslString(), 'hsl(0, 0%, 100%)');
assert.equal(color("#ffffff7f").toHslString(), 'hsla(0, 0%, 100%, 0.5)');
assert.equal(color("#ffffff").toHexString(), '#ffffff');
assert.equal(color("#ffffff7f").toHexString(), '#ffffff7f');
<commit_msg>add tests for alpha=0<commit_after>var color = require(".."),
	assert = require("assert");

assert.deepEqual(color("blue").toRgbaArray(), [0, 0, 255, 1]);
assert.deepEqual(color("blue").toHslaArray(), [240, 100, 50, 1]);
assert.deepEqual(color("blue").toHexString(), '#0000ff');
assert.deepEqual(color("rgb(255, 255, 255)").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("rgb(100%, 100%, 100%)").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("rgb(100%, 100%, 100%)").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("rgba(100%, 100%, 100%, .5)").toHexString(), '#ffffff7f');
assert.deepEqual(color("rgba(255, 255, 255, .5)").toRgbaArray(), [255, 255, 255, .5]);
assert.deepEqual(color("rgba(255, 255, 255, .5)").toHslaArray(), [0, 0, 100, .5]);
assert.equal(color().fromRgb([255, 255, 255]).toRgbString(), 'rgb(255, 255, 255)');
assert.equal(color().fromRgba([255, 255, 255, 1]).toRgbString(), 'rgb(255, 255, 255)');
assert.equal(color().fromRgba([255, 255, 255, .5]).toRgbString(), 'rgba(255, 255, 255, 0.5)');
assert.equal(color().fromRgba([255, 255, 255, 1]).toHslString(), 'hsl(0, 0%, 100%)');
assert.equal(color().fromRgba([255, 255, 255, .5]).toHslString(), 'hsla(0, 0%, 100%, 0.5)');
assert.equal(color().fromRgba([255, 255, 255, 1]).toHexString(), '#ffffff');
assert.equal(color().fromRgba([255, 255, 255, .5]).toHexString(), '#ffffff7f');
assert.deepEqual(color("hsl(0, 0%, 100%)").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("hsl(0, 0%, 100%)").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("hsla(0, 0%, 100%, .5)").toHslaArray(), [0, 0, 100, .5]);
assert.deepEqual(color("hsla(0, 0%, 100%, .5)").toRgbaArray(), [255, 255, 255, .5]);
assert.equal(color().fromHsl([0, 0, 100]).toHslString(), 'hsl(0, 0%, 100%)');
assert.equal(color().fromHsla([0, 0, 100, 1]).toRgbString(), 'rgb(255, 255, 255)');
assert.equal(color().fromHsla([0, 0, 100, .5]).toRgbString(), 'rgba(255, 255, 255, 0.5)');
assert.equal(color().fromHsla([0, 0, 100, 1]).toHslString(), 'hsl(0, 0%, 100%)');
assert.equal(color().fromHsla([0, 0, 100, .5]).toHslString(), 'hsla(0, 0%, 100%, 0.5)');
assert.equal(color().fromHsla([0, 0, 100, 1]).toHexString(), '#ffffff');
assert.equal(color().fromHsla([0, 0, 100, .5]).toHexString(), '#ffffff7f');
assert.deepEqual(color("#ffffff").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("#ffffff").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("#ffffffff").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("#ffffffff").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("#fff").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("#fff").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("#ffff").toRgbaArray(), [255, 255, 255, 1]);
assert.deepEqual(color("#ffff").toHslaArray(), [0, 0, 100, 1]);
assert.deepEqual(color("#ffffff7f").toRgbaArray(), [255, 255, 255, .5]);
assert.deepEqual(color("#ffffff7f").toHslaArray(), [0, 0, 100, .5]);
assert.deepEqual(color("#ffffff").toHexString(), '#ffffff');
assert.equal(color("#ffffff").toRgbString(), 'rgb(255, 255, 255)');
assert.equal(color("#ffffff7f").toRgbString(), 'rgba(255, 255, 255, 0.5)');
assert.equal(color("#ffffff").toHslString(), 'hsl(0, 0%, 100%)');
assert.equal(color("#ffffff7f").toHslString(), 'hsla(0, 0%, 100%, 0.5)');
assert.equal(color("#ffffff").toHexString(), '#ffffff');
assert.equal(color("#ffffff7f").toHexString(), '#ffffff7f');
assert.deepEqual(color([0, 0, 0, 0]).toRgbaArray(), [0, 0, 0, 0]);
assert.deepEqual(color('rgba(0, 0, 0, 0)').toRgbaArray(), [0, 0, 0, 0]);
assert.deepEqual(color([3, 2, 1, 0]).toRgbaArray(), [3, 2, 1, 0]);
assert.deepEqual(color('rgba(3, 2, 1, 0)').toRgbaArray(), [3, 2, 1, 0]);
<|endoftext|>


<commit_before>var assert = require('assert');
var husl = require('../husl.js');
var snapshot = require('./snapshot.js');

function manySamples(assertion) {
    var samples = '0123456789abcdef'.split('');
    samples.map(function (r) {
        samples.map(function (g) {
            samples.map(function (b) {
                assertion('#' + r + r + g + g + b + b);
            });
        });
    });
}

describe('HUSL consistency', function () {
    it('should convert between HUSL and hex', function () {
        manySamples(function (hex) {
            assert.deepEqual(hex, husl.toHex.apply(this, husl.fromHex(hex)));
        });
    });
    it('should convert between HUSLp and hex', function () {
        manySamples(function (hex) {
            assert.deepEqual(hex, husl.p.toHex.apply(this, husl.p.fromHex(hex)));
        });
    });
});

var rgbRangeTolerance = 0.00000000001;
var snapshotTolerance = 0.00000000001;

describe('Fits within RGB ranges', function () {
    return it('should fit', function () {
        var H = 0;
        var S = 0;
        var L = 0;

        var channel;
        while (H <= 360) {
            while (S <= 100) {
                while (L <= 100) {
                    var RGB = husl.toRGB(H, S, L);
                    for (var i = 0; i < RGB.length; i++) {
                        channel = RGB[i];
                        assert(-rgbRangeTolerance <= channel && channel <= 1 + rgbRangeTolerance, 'HUSL: ' + [H, S, L] + ' -> ' + RGB);
                    }

                    RGB = husl.p.toRGB(H, S, L);
                    for (var j = 0; j < RGB.length; j++) {
                        channel = RGB[j];
                        assert(-rgbRangeTolerance <= channel && channel <= 1 + rgbRangeTolerance, 'HUSLp: ' + [H, S, L] + ' -> ' + RGB);
                    }
                    L += 5;
                }
                S += 5;
            }
            H += 5;
        }
    });
});

describe('HUSL snapshot', function () {
    return it('should match the stable snapshot', function () {
        var stableSamples;
        var currentSamples;
        var stableTuple;
        var currentTuple;
        var diff;
        this.timeout(10000);

        var current = snapshot.snapshot();
        var stable = require('./snapshot-rev4.json');

        Object.keys(stable).map(function (hex) {
            stableSamples = stable[hex];
            currentSamples = current[hex];
            Object.keys(stableSamples).map(function (tag) {
                stableTuple = stableSamples[tag];
                currentTuple = currentSamples[tag];
                [0, 1, 2].map(function (i) {
                    diff = Math.abs(currentTuple[i] - stableTuple[i]);
                    assert(diff < snapshotTolerance, 'The snapshots for ' + hex + ' don\'t match at ' + tag + '\nStable:  ' + stableTuple + '\nCurrent: ' + currentTuple);
                });
            });
        });
    });
});

<commit_msg>Ignore case when testing hex<commit_after>var assert = require('assert');
var husl = require('../husl.min.js');
var snapshot = require('./snapshot.js');

function manySamples(assertion) {
    var samples = '0123456789abcdef'.split('');
    samples.map(function (r) {
        samples.map(function (g) {
            samples.map(function (b) {
                assertion('#' + r + r + g + g + b + b);
            });
        });
    });
}

describe('HUSL consistency', function () {
    it('should convert between HUSL and hex', function () {
        manySamples(function (hex) {
            assert.deepEqual(hex, husl.toHex.apply(this, husl.fromHex(hex)).toLowerCase());
        });
    });
    it('should convert between HUSLp and hex', function () {
        manySamples(function (hex) {
            assert.deepEqual(hex, husl.p.toHex.apply(this, husl.p.fromHex(hex)).toLowerCase());
        });
    });
});

var rgbRangeTolerance = 0.00000000001;
var snapshotTolerance = 0.00000000001;

describe('Fits within RGB ranges', function () {
    return it('should fit', function () {
        var H = 0;
        var S = 0;
        var L = 0;

        var channel;
        while (H <= 360) {
            while (S <= 100) {
                while (L <= 100) {
                    var RGB = husl.toRGB(H, S, L);
                    for (var i = 0; i < RGB.length; i++) {
                        channel = RGB[i];
                        assert(-rgbRangeTolerance <= channel && channel <= 1 + rgbRangeTolerance, 'HUSL: ' + [H, S, L] + ' -> ' + RGB);
                    }

                    RGB = husl.p.toRGB(H, S, L);
                    for (var j = 0; j < RGB.length; j++) {
                        channel = RGB[j];
                        assert(-rgbRangeTolerance <= channel && channel <= 1 + rgbRangeTolerance, 'HUSLp: ' + [H, S, L] + ' -> ' + RGB);
                    }
                    L += 5;
                }
                S += 5;
            }
            H += 5;
        }
    });
});

describe('HUSL snapshot', function () {
    return it('should match the stable snapshot', function () {
        var stableSamples;
        var currentSamples;
        var stableTuple;
        var currentTuple;
        var diff;
        this.timeout(10000);

        var current = snapshot.snapshot();
        var stable = require('./snapshot-rev4.json');

        Object.keys(stable).map(function (hex) {
            stableSamples = stable[hex];
            currentSamples = current[hex];
            Object.keys(stableSamples).map(function (tag) {
                stableTuple = stableSamples[tag];
                currentTuple = currentSamples[tag];
                [0, 1, 2].map(function (i) {
                    diff = Math.abs(currentTuple[i] - stableTuple[i]);
                    assert(diff < snapshotTolerance, 'The snapshots for ' + hex + ' don\'t match at ' + tag + '\nStable:  ' + stableTuple + '\nCurrent: ' + currentTuple);
                });
            });
        });
    });
});

<|endoftext|>


<commit_before>var http = require('http');
var tinder = require('tinderjs');
var client = new tinder.TinderClient();
var sentiment = require('sentiment');
var _ = require('underscore');
var horoscope = require('horoscope');
var fs = require('fs');
var login = require('./login');

var server = http.createServer(function(request, response) {
  if (request.method === 'GET') {
    if (request.url === '/') {
      response.setHeader('Content-Type', 'text/html');
      return response.end(fs.readFileSync(__dirname + '/../client/index.html'));
    }
    if (request.url.match(/.js$|.html$|.css$|.woff|.woff2|.tff$/)) {
      // Very clever way of setting the content type CruzZZ
      response.setHeader('Content-Type', 'text/' + request.url.match(/js$|html$|css$|woff|woff2|tff$/))
      return response.end(fs.readFileSync(__dirname + '/../client' + request.url));
    }
  }
  if (request.method === 'POST' && request.url === '/login'){
    return login.login(response, request);
  }
}).listen(3000)
<commit_msg>Lets try this<commit_after>var http = require('http');
var tinder = require('tinderjs');
var client = new tinder.TinderClient();
var sentiment = require('sentiment');
var _ = require('underscore');
var horoscope = require('horoscope');
var fs = require('fs');
var login = require('./login');

var server = http.createServer(function(request, response) {
  if (request.method === 'GET') {
    if (request.url === '/') {
      response.setHeader('Content-Type', 'text/html');
      return response.end(fs.readFileSync(__dirname + '/../client/index.html'));
    }
    if (request.url.match(/.js$|.html$|.css$|.woff|.woff2|.tff$/)) {
      // Very clever way of setting the content type CruzZ
      response.setHeader('Content-Type', 'text/' + request.url.match(/js$|html$|css$|woff|woff2|tff$/))
      return response.end(fs.readFileSync(__dirname + '/../client' + request.url));
    }
  }
  if (request.method === 'POST' && request.url === '/login'){
    return login.login(response, request);
  }
}).listen(3000)
<|endoftext|>


<commit_before>var should = require('should');
var request = require('request');
var utils = require('./utils');
var Couch = require('../lib/couch.js');
var testPort = 12500;
var dbName = 'ws_mocks';
var dbConfig = {pathname: dbName};
var serverConfig = {db: dbName, port: testPort};
var newId = '';

var Graft = require('graftjs/server');
require('graftjs/middleware/REST.graft.js');
require('../middleware/CouchDB.graft.js');
Graft.load(__dirname);
Graft.start(serverConfig);

function cleanup(done) {
    this.dbDel(function(err) {
        done();
    });
}

// Install and destroy database.
// -----------------------------
describe('install', function() {
    var db = new Couch(dbConfig);

    before(cleanup.bind(db));
    after(cleanup.bind(db));

    it('should install the database', function(done) {
    	utils.install(dbConfig, done);
    });

    it('check that database exists', function(done) {
        db.get('_design/backbone', function(err, doc) {
            if (err) throw err;
            should.ok(doc._rev);
            should.ok(doc.language);
            should.ok(doc.views);
            should.ok(doc.rewrites);
            done();
        });
    });

    it('should delete the database', function(done) {
        db.dbDel(done);
    });

    it('check that database does not exist anymore', function(done) {
        db.get('_design/backbone', function(err, doc) {
            should.deepEqual(err.error, 'not_found');
            done();
        });
    });

});

describe('Reading model', function() {
		var db = new Couch(dbConfig);

	    before(cleanup.bind(db));
	    after(cleanup.bind(db));

	describe('Install DB', function() {

	    it('should install the database', function(done) {
	    	utils.install(dbConfig, done);
	    });
	});

	describe('POST /api/Mock', function() {
		var doc = {
			"id": 'one',
			"someVal": "Ronald McDonald",
            "favColor": "yello"
		};
		before(utils.requestUrl(testPort, '/api/Mock', 'POST', doc));

		// This is for the new location the server told us to go.
        var newLocation = '';
        it ('should have a location', function() {
            this.resp.should.have.header('Location');
        });

        it ('should return status 303', function() {
            this.resp.should.have.status(303);
        });

        it('response should be json', function() {
            this.resp.should.be.json;
        });

        it ('should have a body', function() {
            should.exist(this.body);
        });
	});

	describe('GET /api/Mock/one', function() {
		before(utils.requestUrl(testPort, '/api/Mock/one'));

		it ('should return status 200', function() {
            this.resp.should.have.status(200);
        });

        it('response should be json', function() {
            this.resp.should.be.json;
        });

        it ('should have a body', function() {
            should.exist(this.body);
        });

        it('should have the correct id', function() {
            this.body.should.have.property('id', 'one');
        });

        it('should have the correct someVal', function() {
            this.body.should.have.property('someVal', 'Ronald McDonald');
        });

        it ('should respect the default values', function() {
            this.body.should.have.property('name', 'name');
        });
	});

});

// describe('Delete model', function() {

// 	describe('Install DB', function() {
// 		var db = new Couch(dbConfig);

// 	    before(cleanup.bind(db));

// 	    it('should install the database', function(done) {
// 	    	utils.install(dbConfig, done);
// 	    });
// 	});

// 	describe('POST /api/Mock', function() {
// 		var doc = {
// 			"id": 'one',
// 			"someVal": "Ronald McDonald", // was "Emily Baker"
//             "favColor": "yello" // new field
// 		};
// 		before(utils.requestUrl(testPort, '/api/Mock', 'POST', doc));

// 		// This is for the new location the server told us to go.
//         var newLocation = '';
//         it ('should have a location', function() {
//             this.resp.should.have.header('Location');
//         });

//         it ('should return status 303', function() {
//             this.resp.should.have.status(303);
//         });

//         it('response should be json', function() {
//             this.resp.should.be.json;
//         });

//         it ('should have a body', function() {
//             should.exist(this.body);
//         });
// 	});

// 	describe('DELETE /api/Mock/one', function() {
// 		before(utils.requestUrl(testPort, '/api/Mock/one', 'DELETE'));

// 	    it ('should return status 204', function() {
// 	        this.resp.should.have.status(204);
// 	    });

// 	    describe('GET /api/Mock/one', function() {
// 	        before(utils.requestUrl(testPort, '/api/Account/1'));
// 	        it ('should return status 404', function() {
// 	            this.resp.should.have.status(404);
// 	        });
// 	    });

// 	    // describe('GET /api/Mock', function() {
// 	    //     before(utils.requestUrl(testPort, '/api/Mock'));
// 	    //     it ('should return status 200', function() {
// 	    //         this.resp.should.have.status(200);
// 	    //     });

// 	    //     it('response should be json', function() {
// 	    //         this.resp.should.be.json;
// 	    //     });

// 	    //     it ('should have a body', function() {
// 	    //         should.exist(this.body);
// 	    //     });

// 	    //     it ('should only be 6 in length', function() {
// 	    //         this.body.should.have.length(6);
// 	    //     });

// 	    //     it ('should not have a record with id 1', function() {
// 	    //         var record = _(this.body).findWhere({id: '1'});
// 	    //         if (record) {
// 	    //             should.fail(record, undefined, 'Should have been deleted');
// 	    //         }
// 	    //     });
// 	    // });
// 	});

// 	describe('destroy DB', function() {
// 		var db = new Couch(dbConfig);

// 	    it('should delete the database', function(done) {
// 	        db.dbDel(done);
// 	    });
// 	});
// });<commit_msg>added test for updateModel<commit_after>var should = require('should');
var request = require('request');
var utils = require('./utils');
var Couch = require('../lib/couch.js');
var testPort = 12500;
var dbName = 'ws_mocks';
var dbConfig = {pathname: dbName};
var serverConfig = {db: dbName, port: testPort};
var newId = '';

var Graft = require('graftjs/server');
require('graftjs/middleware/REST.graft.js');
require('../middleware/CouchDB.graft.js');
Graft.load(__dirname);
Graft.start(serverConfig);

function cleanup(done) {
    this.dbDel(function(err) {
        done();
    });
}

// Install and destroy database.
// -----------------------------
describe('install', function() {
    var db = new Couch(dbConfig);

    before(cleanup.bind(db));
    after(cleanup.bind(db));

    it('should install the database', function(done) {
    	utils.install(dbConfig, done);
    });

    it('check that database exists', function(done) {
        db.get('_design/backbone', function(err, doc) {
            if (err) throw err;
            should.ok(doc._rev);
            should.ok(doc.language);
            should.ok(doc.views);
            should.ok(doc.rewrites);
            done();
        });
    });

    it('should delete the database', function(done) {
        db.dbDel(done);
    });

    it('check that database does not exist anymore', function(done) {
        db.get('_design/backbone', function(err, doc) {
            should.deepEqual(err.error, 'not_found');
            done();
        });
    });

});

describe('Reading model', function() {
		var db = new Couch(dbConfig);

	    before(cleanup.bind(db));
	    after(cleanup.bind(db));

	describe('Install DB', function() {

	    it('should install the database', function(done) {
	    	utils.install(dbConfig, done);
	    });
	});

	describe('POST /api/Mock', function() {
		var doc = {
			"id": 'one',
			"someVal": "Ronald McDonald",
            "favColor": "yello"
		};
		before(utils.requestUrl(testPort, '/api/Mock', 'POST', doc));

		// This is for the new location the server told us to go.
        var newLocation = '';
        it ('should have a location', function() {
            this.resp.should.have.header('Location');
        });

        it ('should return status 303', function() {
            this.resp.should.have.status(303);
        });

        it('response should be json', function() {
            this.resp.should.be.json;
        });

        it ('should have a body', function() {
            should.exist(this.body);
        });
	});

	describe('GET /api/Mock/one', function() {
		before(utils.requestUrl(testPort, '/api/Mock/one'));

		it ('should return status 200', function() {
            this.resp.should.have.status(200);
        });

        it('response should be json', function() {
            this.resp.should.be.json;
        });

        it ('should have a body', function() {
            should.exist(this.body);
        });

        it('should have the correct id', function() {
            this.body.should.have.property('id', 'one');
        });

        it('should have the correct someVal', function() {
            this.body.should.have.property('someVal', 'Ronald McDonald');
        });

        it ('should respect the default values', function() {
            this.body.should.have.property('name', 'name');
        });
	});

});

describe('Updating model', function() {
	var db = new Couch(dbConfig);
    before(cleanup.bind(db));
    after(cleanup.bind(db));

	describe('Install DB', function() {

	    it('should install the database', function(done) {
	    	utils.install(dbConfig, done);
	    });
	});

	describe('POST /api/Mock', function() {
		var doc = {
			"id": 'one',
			"someVal": "Ronald McDonald",
            "favColor": "yello"
		};
		before(utils.requestUrl(testPort, '/api/Mock', 'POST', doc));

		// This is for the new location the server told us to go.
        it ('should have a location', function() {
            this.resp.should.have.header('Location');
        });

        it ('should return status 303', function() {
            this.resp.should.have.status(303);
        });

        it('response should be json', function() {
            this.resp.should.be.json;
        });

        it ('should have a body', function() {
            should.exist(this.body);
        });
	});

	describe('GET /api/Mock/one', function() {
		before(utils.requestUrl(testPort, '/api/Mock/one'));

		it ('should return status 200', function() {
            this.resp.should.have.status(200);
        });

        it('response should be json', function() {
            this.resp.should.be.json;
        });

        it ('should have a body', function() {
            should.exist(this.body);
        });

        it('should have the correct id', function() {
            this.body.should.have.property('id', 'one');
        });

        it('should have the correct someVal', function() {
            this.body.should.have.property('someVal', 'Ronald McDonald');
        });

        it ('should respect the default values', function() {
            this.body.should.have.property('name', 'name');
        });
	});

	describe('PUT /api/Mock/one', function() {
	    var data = {
	    	id: "one",
	        someVal: "Emily Mortimer",
	        favColor: "magenta"
	    }
	    before(utils.requestUrl(testPort, '/api/Mock/one', 'PUT', data));

	    it ('should return status 201', function() {
	        this.resp.should.have.status(201);
	    });

	    it('response should be json', function() {
	        this.resp.should.be.json;
	    });

	    it ('should have a body', function() {
	        should.exist(this.body);
	    });

	    it ('should return the changed object', function() {
	        this.body.should.have.property('someVal', 'Emily Mortimer');
	    });

	    it ('should have added a field', function() {
	        this.body.should.have.property('favColor', 'magenta');
	    });
	});

    describe('GET /api/Mock/one', function() {
        before(utils.requestUrl(testPort, '/api/Mock/one'));

        it ('should return status 200', function() {
            this.resp.should.have.status(200);
        });

        it('response should be json', function() {
            this.resp.should.be.json;
        });

        it ('should have a body', function() {
            should.exist(this.body);
        });

        it ('should have added a field', function() {
            this.body.should.have.property('favColor', 'magenta');
        });

        it ('should return the changed object', function() {
            this.body.should.have.property('someVal', 'Emily Mortimer');
        });
    });
    // describe('GET /api/Account', function() {
    //     before(utils.requestUrl(testPort, '/api/Account'));
    //     it ('should return status 200', function() {
    //         this.resp.should.have.status(200);
    //     });

    //     it('response should be json', function() {
    //         this.resp.should.be.json;
    //     });

    //     it ('should have a body', function() {
    //         should.exist(this.body);
    //     });

    //     it ('should not have changed fields not touched', function() {
    //         this.body[2].should.have.property('group', 'default');
    //     });

    //     it ('should have added a field', function() {
    //         this.body[2].should.have.property('favColor', 'magenta');
    //     });

    //     it ('should return the changed object in listing', function() {
    //         this.body[2].should.have.property('name', 'Emily Mortimer');
    //     });
    // });
});

// describe('Delete model', function() {

// 	describe('Install DB', function() {
// 		var db = new Couch(dbConfig);

// 	    before(cleanup.bind(db));

// 	    it('should install the database', function(done) {
// 	    	utils.install(dbConfig, done);
// 	    });
// 	});

// 	describe('POST /api/Mock', function() {
// 		var doc = {
// 			"id": 'one',
// 			"someVal": "Ronald McDonald", // was "Emily Baker"
//             "favColor": "yello" // new field
// 		};
// 		before(utils.requestUrl(testPort, '/api/Mock', 'POST', doc));

// 		// This is for the new location the server told us to go.
//         var newLocation = '';
//         it ('should have a location', function() {
//             this.resp.should.have.header('Location');
//         });

//         it ('should return status 303', function() {
//             this.resp.should.have.status(303);
//         });

//         it('response should be json', function() {
//             this.resp.should.be.json;
//         });

//         it ('should have a body', function() {
//             should.exist(this.body);
//         });
// 	});

// 	describe('DELETE /api/Mock/one', function() {
// 		before(utils.requestUrl(testPort, '/api/Mock/one', 'DELETE'));

// 	    it ('should return status 204', function() {
// 	        this.resp.should.have.status(204);
// 	    });

// 	    describe('GET /api/Mock/one', function() {
// 	        before(utils.requestUrl(testPort, '/api/Account/1'));
// 	        it ('should return status 404', function() {
// 	            this.resp.should.have.status(404);
// 	        });
// 	    });

// 	    // describe('GET /api/Mock', function() {
// 	    //     before(utils.requestUrl(testPort, '/api/Mock'));
// 	    //     it ('should return status 200', function() {
// 	    //         this.resp.should.have.status(200);
// 	    //     });

// 	    //     it('response should be json', function() {
// 	    //         this.resp.should.be.json;
// 	    //     });

// 	    //     it ('should have a body', function() {
// 	    //         should.exist(this.body);
// 	    //     });

// 	    //     it ('should only be 6 in length', function() {
// 	    //         this.body.should.have.length(6);
// 	    //     });

// 	    //     it ('should not have a record with id 1', function() {
// 	    //         var record = _(this.body).findWhere({id: '1'});
// 	    //         if (record) {
// 	    //             should.fail(record, undefined, 'Should have been deleted');
// 	    //         }
// 	    //     });
// 	    // });
// 	});

// 	describe('destroy DB', function() {
// 		var db = new Couch(dbConfig);

// 	    it('should delete the database', function(done) {
// 	        db.dbDel(done);
// 	    });
// 	});
// });<|endoftext|>