<commit_before>// Dependencies
var OArgv = require("../lib");

// Tests
var tests = [
    [{ r: true, _: ["target.zip", "somedir"]}, "zip"]
  , [{ d: "http://ionicabizau.net", tt: true, size: "600x800" }, "bat"]
  , [{ escaping: "She said: \"Hello World\"!" }, "foo"]
  , [{ noCommand: "foo", b: true }]
  , [{ __: "=", custom: "Separator"}, "foo"]
];

// Run tests
tests.forEach(function (c, i) {
    console.log(">> Test " + i);
    console.log("  " + JSON.stringify(c) + " ---> " + OArgv.apply(this, c));
});
<commit_msg>Added tests<commit_after>// Dependencies
var OArgv = require("../lib")
  , Assert = require("assert")
  ;

it("should support commands and args", function (cb) {
    Assert.equal(OArgv({
        r: true
      , _: ["target.zip", "somedir"]
    }, "zip"), "zip -r \"target.zip\" \"somedir\"");
    cb();
});

it("should support boolean args", function (cb) {
    Assert.equal(OArgv({
        d: "http://ionicabizau.net"
      , tt: true
      , size: "600x800"
    }, "bat"), "bat -d \"http://ionicabizau.net\" --tt -size \"600x800\"");
    cb();
});

it("should escape arguments", function (cb) {
    Assert.equal(OArgv({
        escaping: "She said: \"Hello World\"!"
    }, "foo"), "foo --escaping \"She said: \\\"Hello World\\\"!\"");
    cb();
});

it("should work without commands", function (cb) {
    Assert.equal(OArgv({
        noCommand: "foo",
        b: true
    }), "--noCommand \"foo\" -b");
    cb();
});

it("should support custom separators", function (cb) {
    Assert.equal(OArgv({
        __: "=",
        custom: "Separator"
    }, "foo"), "foo --custom=\"Separator\"")
});
<|endoftext|>


<commit_before>var fs = require('fs');
var assert = require('assert');
var facebook = require('../lib/facebook');

var SIGNED_REQUEST = 'vlXgu64BQGFSQrY0ZcJBZASMvYvTHu9GQ0YM9rjPSso.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsIjAiOiJwYXlsb2FkIn0';
// var SIGNED_REQUEST = 'WGvK-mUKB_Utg0l8gSPvf6smzacp46977pTtcRx0puE.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEyOTI4MjEyMDAsImlzc3VlZF9hdCI6MTI5MjgxNDgyMCwib2F1dGhfdG9rZW4iOiIxNTI1NDk2ODQ3NzczMDJ8Mi5ZV2NxV2k2T0k0U0h4Y2JwTWJRaDdBX18uMzYwMC4xMjkyODIxMjAwLTcyMTU5OTQ3NnxQaDRmb2t6S1IyamozQWlxVldqNXp2cTBmeFEiLCJ1c2VyIjp7ImxvY2FsZSI6ImVuX0dCIiwiY291bnRyeSI6ImF1In0sInVzZXJfaWQiOiI3MjE1OTk0NzYifQ';
var APP_SECRET = 'secret';
var EXPECTED_DATA = {
    'algorithm': 'HMAC-SHA256',
    '0': 'payload'
};

facebook.decodeSignedRequest(SIGNED_REQUEST, APP_SECRET);
// assert.deepEqual(facebook.decodeSignedRequest(SIGNED_REQUEST, APP_SECRET),
                 // EXPECTED_DATA);

var tests = fs.readFileSync(__dirname + '/data.txt').toString().split('\n');

tests.forEach(function (test) {
    if (!test || test[0] == '#') { return; }
    var line = test.split(' ');
    name = line[0];
    input = line[1];
    output = line[2];
    var data = facebook.decodeBase64URL(input);
    assert.strictEqual(data, output);
});<commit_msg>Add tests.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
//  Facebook Node.js SDK
//
//  Copyright 2011 Daniel Gasienica <daniel@gasienica.ch>
//  Copyright 2010 Facebook
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may
//  not use this file except in compliance with the License. You may obtain
//  a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
//  License for the specific language governing permissions and limitations
//  under the License.
//
//////////////////////////////////////////////////////////////////////////////
var assert = require('assert');
var facebook = require('../lib/facebook');
var fs = require('fs');

// Test: decodeSignedRequest
var tests = loadTests('signed-requests-data.json');
tests.forEach(function (test) {
    var actual = facebook.decodeSignedRequest(test.signedRequest, test.appSecret);
    var expected = test.expected;
    assert.deepEqual(actual, expected);
});

// Test: Base64 URL decode
var tests = loadTests('base64-url-decode-data.json');
tests.forEach(function (test) {
    var actual = facebook.base64URLDecode(test.input);
    var expected = test.output;
    assert[test['test']](actual, expected, test.name);
});

// Helpers
function loadTests(filename) {
    return JSON.parse(fs.readFileSync(__dirname + '/' + filename).toString());
}
<|endoftext|>


<commit_before>var express       = require('express');
var kanye         = require('../../kanye');
var google        = require('googleapis');
var config        = require('../../config');
var redis         = require('redis');
var async         = require('async');
var GmailState    = require('./gmailstate.js');
var article       = require('article');
var btoa          = require('btoa');
var gmail         = google.gmail('v1');
var OAuth2Client  = google.auth.OAuth2;
var app           = express();
var redisClient   = redis.createClient();
var scopes        = [
  "https://www.googleapis.com/auth/gmail.readonly",
  "https://www.googleapis.com/auth/gmail.compose"
];
var activeUsers   = {};

var CLIENT_ID     = config.DEBUG ? '846757558374-sjiu9cn3199qm24er1ludek0591lgj1i.apps.googleusercontent.com'
                                 : '846757558374-692q32ii9rvls9ip2sjsb5dt2p6vgc3i.apps.googleusercontent.com';
var CLIENT_SECRET = config.DEBUG ? '3q24Spyav4M5sO_7-xMcEuGf'
                                 : 'Cma4ab55ISAwIaXjBu24A94x';
var REDIRECT_URL  = config.DEBUG ? 'http://localhost:8000/oauth2callback'
                                 : 'http://getkanye.com/oauth2callback';

var redisTokenKey = function(userNumber) {
  return kanye.normalizeNumber(userNumber) + '_' + 'tokens';
}

/**
  This endpint is called first to get an authorization URL.
  After this you can get the actual tokens you need.
**/
app.get('/auth_url', function(req, res) {
  var oauth2Client  = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

  var url = oauth2Client.generateAuthUrl({
    access_type : 'offline',
    scope       : scopes
  });

  res.status(200).send(url);
});

app.get('/get_tokens', function(req, res) {
  var userNumber    = kanye.normalizeNumber(req.query.number);
  var redisKey      = redisTokenKey( userNumber );
  var oauth2Client  = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

  oauth2Client.getToken(req.query.code, function(err, tokens) {
    // Recall: redis only accepts string value. Be sure to parse JSON when reading.
    redisClient.set(redisKey, JSON.stringify( tokens ), function() {
      console.log('-> Stored tokens in key', redisKey);
      res.status(200).end()
    });
  });
});

var handleInbox = function(req, res, oauthClient) {
  // Setup the inbox state.
  activeUsers[ req.query.number ] = new GmailState();

  gmail.users.messages.list({
    userId: 'me',
    auth: oauthClient,
    maxResults: 5
  }, function(err, response) {
    if (err) {
      console.error('Retrieving messages error: %s');
      console.error( err );

      res.status(403).json({ error: 'Failed to retrieve inbox. Sorry bruh!' });
    } else {
      var messages          = response.messages;
      var nextPageToken     = response.nextPageToken;
      var currentState      = activeUsers[ req.query.number ];

      console.log('-> Retrieving %s message(s).', messages.length);

      // Record this in case they want to see more emails
      currentState.setNextPageToken( nextPageToken );

      // API requests to get details on each of the messages
      var getMessageJobs = [];
      for (var i = 0; i < messages.length; i++) {
        var messageId = messages[i].id;

        getMessageJobs.push((function(messageId) {
          console.log('-> Create job for message %s at %s', messageId, i);
          return function(callback) {
            gmail.users.messages.get({ userId: 'me', id: messageId, auth: oauthClient },
              function(err, response) {
                if (err) return callback(err);

                var emailMessageTitle;
                var emailMessageBody;
                var emailMessage = response;

                // Find the subject line and contents of the email
                for (var j = 0; j < emailMessage.payload.headers.length; j++) {
                  if (emailMessage.payload.headers[j].name === 'Subject') {
                    emailMessageTitle = emailMessage.payload.headers[j].value;
                    if (config.DEBUG) {
                      console.log('Found subject line: %s', emailMessageTitle);
                    }
                    break;
                  }
                }
                // Find the body of the message - it will be "attached" to the email
                // It's possible that the email is composed of multiple parts. In that case
                // just get the first part.
                var messageHtml;
                if (emailMessage.payload.body.data) {
                  messageHtml = (new Buffer(emailMessage.payload.body.data, 'base64').toString('ascii'));
                } else {
                  messageHtml = (new Buffer(emailMessage.payload.parts[0].body.data, 'base64').toString('ascii'));
                }

                currentState.addEmail({ subject: emailMessageTitle, body: emailMessageBody });
                callback(null, currentState);
              });
          };
        })(messageId));
      }

      if (messages.length === 0) {
        res.status(403).json({ error: 'You have no emails in your inbox.' });
      } else {
        // Get the message contents for all messages in the inbox.
        // Keep these stored, so if we read them later we dont do another API request.
        console.log('-> Starting %s parallel jobs to retrieve messages.', getMessageJobs.length);
        async.parallel(getMessageJobs, function(err, resultStates) {

          if (err) {
            res.status(500).json({ error: 'Failed to retrieve your emails.' });
          } else {
            // This should be filled out by this point. Build the message to send.
            var outgoingMessage = currentState.buildInboxMessage();
            res.status(200).json({
              message: outgoingMessage
            });
          }
        });
      }
    }
  });
};

var handleReadMessage = function(req, res, messageIndex, oauthClient) {
};

var handleSendMessage = function(req, res, message, oauthClient) {

  var request = gmail.users.messages.send({
    'userId' : message.to,
    'message' : {
      'raw' : btoa(message.body)
    }
  }, function(err, response) {
    var outgoingMessage;
    if (err) {
      outgoingMessage = "Mail send failed.";
    } else {
      outgoingMessage = "Mail successfully sent.";
    }

    res.status(200).json({
      message: outgoingMessage
    });
  });
};

app.get('/clear', function(req, res) {
  var userNumber = req.query.number;
  delete activeUsers[ userNumber ];
  console.log('Gmail: cleared session for %s', userNumber);
});

app.get('/sms', function(req, res) {
  var userNumber  = req.query.number;
  var textMessage = req.query.message;
  var redisKey    = redisTokenKey( userNumber );

  console.log('Gmail Query')
  console.log('-> redisKey: %s | userNumber: %s | textMessage: %s',
    redisKey, userNumber, textMessage)

  // Check if this user has authenticated.
  redisClient.get(redisKey, function(err, response) {
    if (err || response == null) {
      res.status(200).json({
        message: 'Go to www.getkanye.com to access this feature.',
        number: userNumber
      });
    } else {
      // We have tokens, let's log them in.
      var oauthClient = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
      var credentials = JSON.parse( response );
      var message     = textMessage;

      console.log('Found GMail tokens: %o', credentials);

      oauthClient.setCredentials(credentials);

      if (message.toLowerCase() === 'inbox') {
        handleInbox(req, res, oauthClient);
      } else if (kanye.isNumber(message)) {
        handleReadMessage(req, res, parseInt(message, 10), oauthClient);
      } else if (message && message.substring(0,7).toLowerCase() === 'compose') {
        // They want to send a message. Parse the string, ensure its valid, then try to send.
        var messageParts = message.split(/\s+/);

        if (messageParts.length >= 3 &&
            kanye.isValidEmail(messageParts[1])) {
          var message = {
            to: messageParts[1],
            body: messageParts.slice(2).join(' ')
          }

          handleSendMessage(req, res, message, oauthClient);
        } else {
          res.status(400).json({ error: 'Sorry, that wasn\'t what I was expecting. Here\'s an example: `compose hi@getkanye.com Hi Kanye!`' });
        }
      } else {
        res.status(400).json({ error: 'So I was trying to check your email. Type `inbox` followed by a number to access a message.' });
      }
    }
  });
});

app.listen(3003);
<commit_msg>Add auth<commit_after>var express       = require('express');
var kanye         = require('../../kanye');
var google        = require('googleapis');
var config        = require('../../config');
var redis         = require('redis');
var async         = require('async');
var GmailState    = require('./gmailstate.js');
var article       = require('article');
var btoa          = require('btoa');
var gmail         = google.gmail('v1');
var OAuth2Client  = google.auth.OAuth2;
var app           = express();
var redisClient   = redis.createClient();
var scopes        = [
  "https://www.googleapis.com/auth/gmail.readonly",
  "https://www.googleapis.com/auth/gmail.compose"
];
var activeUsers   = {};

var CLIENT_ID     = config.DEBUG ? '846757558374-sjiu9cn3199qm24er1ludek0591lgj1i.apps.googleusercontent.com'
                                 : '846757558374-692q32ii9rvls9ip2sjsb5dt2p6vgc3i.apps.googleusercontent.com';
var CLIENT_SECRET = config.DEBUG ? '3q24Spyav4M5sO_7-xMcEuGf'
                                 : 'Cma4ab55ISAwIaXjBu24A94x';
var REDIRECT_URL  = config.DEBUG ? 'http://localhost:8000/oauth2callback'
                                 : 'http://getkanye.com/oauth2callback';

var redisTokenKey = function(userNumber) {
  return kanye.normalizeNumber(userNumber) + '_' + 'tokens';
}

/**
  This endpint is called first to get an authorization URL.
  After this you can get the actual tokens you need.
**/
app.get('/auth_url', function(req, res) {
  var oauth2Client  = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

  var url = oauth2Client.generateAuthUrl({
    access_type : 'offline',
    scope       : scopes
  });

  res.status(200).send(url);
});

app.get('/get_tokens', function(req, res) {
  var userNumber    = kanye.normalizeNumber(req.query.number);
  var redisKey      = redisTokenKey( userNumber );
  var oauth2Client  = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

  oauth2Client.getToken(req.query.code, function(err, tokens) {
    // Recall: redis only accepts string value. Be sure to parse JSON when reading.
    redisClient.set(redisKey, JSON.stringify( tokens ), function() {
      console.log('-> Stored tokens in key', redisKey);
      res.status(200).end()
    });
  });
});

var handleInbox = function(req, res, oauthClient) {
  // Setup the inbox state.
  activeUsers[ req.query.number ] = new GmailState();

  gmail.users.messages.list({
    userId: 'me',
    auth: oauthClient,
    maxResults: 5
  }, function(err, response) {
    if (err) {
      console.error('Retrieving messages error: %s');
      console.error( err );

      res.status(403).json({ error: 'Failed to retrieve inbox. Sorry bruh!' });
    } else {
      var messages          = response.messages;
      var nextPageToken     = response.nextPageToken;
      var currentState      = activeUsers[ req.query.number ];

      console.log('-> Retrieving %s message(s).', messages.length);

      // Record this in case they want to see more emails
      currentState.setNextPageToken( nextPageToken );

      // API requests to get details on each of the messages
      var getMessageJobs = [];
      for (var i = 0; i < messages.length; i++) {
        var messageId = messages[i].id;

        getMessageJobs.push((function(messageId) {
          console.log('-> Create job for message %s at %s', messageId, i);
          return function(callback) {
            gmail.users.messages.get({ userId: 'me', id: messageId, auth: oauthClient },
              function(err, response) {
                if (err) return callback(err);

                var emailMessageTitle;
                var emailMessageBody;
                var emailMessage = response;

                // Find the subject line and contents of the email
                for (var j = 0; j < emailMessage.payload.headers.length; j++) {
                  if (emailMessage.payload.headers[j].name === 'Subject') {
                    emailMessageTitle = emailMessage.payload.headers[j].value;
                    if (config.DEBUG) {
                      console.log('Found subject line: %s', emailMessageTitle);
                    }
                    break;
                  }
                }
                // Find the body of the message - it will be "attached" to the email
                // It's possible that the email is composed of multiple parts. In that case
                // just get the first part.
                var messageHtml;
                if (emailMessage.payload.body.data) {
                  messageHtml = (new Buffer(emailMessage.payload.body.data, 'base64').toString('ascii'));
                } else {
                  messageHtml = (new Buffer(emailMessage.payload.parts[0].body.data, 'base64').toString('ascii'));
                }

                currentState.addEmail({ subject: emailMessageTitle, body: emailMessageBody });
                callback(null, currentState);
              });
          };
        })(messageId));
      }

      if (messages.length === 0) {
        res.status(403).json({ error: 'You have no emails in your inbox.' });
      } else {
        // Get the message contents for all messages in the inbox.
        // Keep these stored, so if we read them later we dont do another API request.
        console.log('-> Starting %s parallel jobs to retrieve messages.', getMessageJobs.length);
        async.parallel(getMessageJobs, function(err, resultStates) {

          if (err) {
            res.status(500).json({ error: 'Failed to retrieve your emails.' });
          } else {
            // This should be filled out by this point. Build the message to send.
            var outgoingMessage = currentState.buildInboxMessage();
            res.status(200).json({
              message: outgoingMessage
            });
          }
        });
      }
    }
  });
};

var handleReadMessage = function(req, res, messageIndex, oauthClient) {
};

var handleSendMessage = function(req, res, message, oauthClient) {

  var request = gmail.users.messages.send({
    userId : message.to,
    message : {
      raw : btoa(message.body)
    }
    auth : oauthClient,
  }, function(err, response) {
    var outgoingMessage;
    if (err) {
      outgoingMessage = "Mail send failed.";
    } else {
      outgoingMessage = "Mail successfully sent.";
    }

    res.status(200).json({
      message: outgoingMessage
    });
  });
};

app.get('/clear', function(req, res) {
  var userNumber = req.query.number;
  delete activeUsers[ userNumber ];
  console.log('Gmail: cleared session for %s', userNumber);
});

app.get('/sms', function(req, res) {
  var userNumber  = req.query.number;
  var textMessage = req.query.message;
  var redisKey    = redisTokenKey( userNumber );

  console.log('Gmail Query')
  console.log('-> redisKey: %s | userNumber: %s | textMessage: %s',
    redisKey, userNumber, textMessage)

  // Check if this user has authenticated.
  redisClient.get(redisKey, function(err, response) {
    if (err || response == null) {
      res.status(200).json({
        message: 'Go to www.getkanye.com to access this feature.',
        number: userNumber
      });
    } else {
      // We have tokens, let's log them in.
      var oauthClient = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
      var credentials = JSON.parse( response );
      var message     = textMessage;

      console.log('Found GMail tokens: %o', credentials);

      oauthClient.setCredentials(credentials);

      if (message.toLowerCase() === 'inbox') {
        handleInbox(req, res, oauthClient);
      } else if (kanye.isNumber(message)) {
        handleReadMessage(req, res, parseInt(message, 10), oauthClient);
      } else if (message && message.substring(0,7).toLowerCase() === 'compose') {
        // They want to send a message. Parse the string, ensure its valid, then try to send.
        var messageParts = message.split(/\s+/);

        if (messageParts.length >= 3 &&
            kanye.isValidEmail(messageParts[1])) {
          var message = {
            to: messageParts[1],
            body: messageParts.slice(2).join(' ')
          }

          handleSendMessage(req, res, message, oauthClient);
        } else {
          res.status(400).json({ error: 'Sorry, that wasn\'t what I was expecting. Here\'s an example: `compose hi@getkanye.com Hi Kanye!`' });
        }
      } else {
        res.status(400).json({ error: 'So I was trying to check your email. Type `inbox` followed by a number to access a message.' });
      }
    }
  });
});

app.listen(3003);
<|endoftext|>


<commit_before>/*global describe, before, it, should*/

'use strict';

var PouchDB = require('pouchdb'),
    model = require('modella'),
    adaptor = require('..'),
    User,
    user,
    pouch;

pouch = new PouchDB('users');

User = model('User')
    .attr('name')
    .attr('nick')
    .attr('_id');

User.use(adaptor(pouch));

describe('modella PouchDB', function () {
    after(function () {
        return pouch.destroy();
    });

    describe('sync layer operations', function () {
        it('defines the required sync layer operations', function (done) {
            User.save.should.be.a.function;
            User.update.should.be.a.function;
            User.remove.should.be.a.function;
            User.find.should.be.a.function;
            User.get.should.be.a.function;
            User.all.should.be.a.function;
            done();
        });
    });

    describe('save', function () {
        it('should save the model', function (done) {
            user = new User();
            user.name('foo');
            user.nick('baz');
            user.save(function (err, res) {
                user.primary().should.be.ok;
                res.should.be.ok;
                pouch.get(user.primary(), function (err, doc) {
                    doc.should.be.ok;
                    doc.should.have.property('name', 'foo');
                    doc.should.have.property('nick', 'baz');
                    done();
                });
            });
        });
    });

    describe('update', function () {
        it('should update the model', function (done) {
            user = new User({name: 'foo', nick: 'baz'});
            user.save(function (err, res) {
                user.primary().should.be.ok;
                user.name('bar');
                user.save(function (err, res) {
                    user.primary().should.be.ok;
                    res.should.be.ok;
                    pouch.get(user.primary(), function (err, doc) {
                        doc.should.be.ok;
                        doc.should.have.property('name', 'bar');
                        doc.should.have.property('nick', 'baz');
                        done();
                    });
                });
            });
        });
    });

    describe('get', function () {
        var user;

        before(function (done) {
            user = new User({name: 'chewie', nick: 'dobs'});
            user.save(function (err, res) {
                user.primary().should.be.ok;
                res.should.be.ok;
                done();
            });
        });

        it('should work with the oid as a string', function (done) {
            var id = user.primary();

            User.get(id, function (err, model) {
                if (err) {
                    return done(err);
                }
                model.name().should.equal(user.name());
                user.name().should.equal('chewie');
                done();
            });
        });
    });

    describe('all', function () {
        it('should get all models', function (done) {
            User.all(function (err, users) {
                (err === null).should.be.true;
                users.should.have.length(3);
                users[0].should.be.an.instanceof(User);
                done();
            });
        });
    });

    describe('remove', function () {
        it('should remove the model from the db', function (done) {
            user = new User({name: 'foo', nick: 'baz'});
            user.save(function (err, res) {
                user.primary().should.be.ok;
                res.should.be.ok;
                user.remove(function (err) {
                    (err === null).should.be.true;
                    pouch.get(user.primary(), function (err, doc) {
                        (doc === undefined).should.be.true;
                        err.should.be.ok;
                        err.should.have.property('message', 'deleted');
                        done();
                    });
                });
            });
        });
    });
});<commit_msg>test for missing primaryKeys<commit_after>/*global describe, before, it, should*/

'use strict';

var PouchDB = require('pouchdb'),
    model = require('modella'),
    adaptor = require('..'),
    UserTwo,
    User,
    user,
    pouch;

pouch = new PouchDB('users');

User = model('User')
    .attr('name')
    .attr('nick');

UserTwo = model('User')
    .attr('name')
    .attr('nick')
    .attr('id');

User.use(adaptor(pouch));
UserTwo.use(adaptor(pouch));

describe('modella PouchDB', function () {
    after(function () {
        return pouch.destroy();
    });

    describe('sync layer operations', function () {
        it('defines the required sync layer operations', function (done) {
            User.save.should.be.a.function;
            User.update.should.be.a.function;
            User.remove.should.be.a.function;
            User.find.should.be.a.function;
            User.get.should.be.a.function;
            User.all.should.be.a.function;
            done();
        });
    });

    describe('save', function () {
        it('should save the model without primaryKey attribute', function (done) {
            user = new User();
            user.name('foo');
            user.nick('baz');
            user.save(function (err, res) {
                user.primary().should.be.ok;
                res.should.be.ok;
                pouch.get(user.primary(), function (err, doc) {
                    doc.should.be.ok;
                    doc.should.have.property('name', 'foo');
                    doc.should.have.property('nick', 'baz');
                    done();
                });
            });
        });

        it('should save the model with primaryKey attribute', function (done) {
            user = new UserTwo();
            user.name('foo');
            user.nick('baz');
            user.save(function (err, res) {
                user.primary().should.be.ok;
                res.should.be.ok;
                pouch.get(user.primary(), function (err, doc) {
                    doc.should.be.ok;
                    doc.should.have.property('name', 'foo');
                    doc.should.have.property('nick', 'baz');
                    done();
                });
            });
        });
    });

    describe('update', function () {
        it('should update the model', function (done) {
            user = new User({name: 'foo', nick: 'baz'});
            user.save(function (err, res) {
                user.primary().should.be.ok;
                user.name('bar');
                user.save(function (err, res) {
                    user.primary().should.be.ok;
                    res.should.be.ok;
                    pouch.get(user.primary(), function (err, doc) {
                        doc.should.be.ok;
                        doc.should.have.property('name', 'bar');
                        doc.should.have.property('nick', 'baz');
                        done();
                    });
                });
            });
        });
    });

    describe('get', function () {
        var user;

        before(function (done) {
            user = new User({name: 'chewie', nick: 'dobs'});
            user.save(function (err, res) {
                user.primary().should.be.ok;
                res.should.be.ok;
                done();
            });
        });

        it('should work with the oid as a string', function (done) {
            var id = user.primary();

            User.get(id, function (err, model) {
                if (err) {
                    return done(err);
                }
                model.name().should.equal(user.name());
                user.name().should.equal('chewie');
                done();
            });
        });
    });

    describe('all', function () {
        it('should get all models', function (done) {
            User.all(function (err, users) {
                (err === null).should.be.true;
                users.should.have.length(4);
                users[0].should.be.an.instanceof(User);
                done();
            });
        });
    });

    describe('remove', function () {
        it('should remove the model from the db', function (done) {
            user = new User({name: 'foo', nick: 'baz'});
            user.save(function (err, res) {
                user.primary().should.be.ok;
                res.should.be.ok;
                user.remove(function (err) {
                    (err === null).should.be.true;
                    pouch.get(user.primary(), function (err, doc) {
                        (doc === undefined).should.be.true;
                        err.should.be.ok;
                        err.should.have.property('message', 'deleted');
                        done();
                    });
                });
            });
        });
    });
});<|endoftext|>


<commit_before>
if (!Detector.WebGL) Detector.addGetWebGLMessage();

var scene, camera, renderer;
var cube, cube2, plane, spotlight;
var controls;
var stats;

// Spotlight move
var reversed = false;

init();
animate();

function init() {

  var $surface = $('#surface');

  // set the scene size
  var WIDTH = 940,
      HEIGHT = 500;

  // set some camera attributes
  var VIEW_ANGLE = 50,
      ASPECT = WIDTH / HEIGHT,
      NEAR = 1,
      FAR = 10000;

  // Create a WebGL renderer
  renderer = new THREE.WebGLRenderer();
  renderer.setSize(WIDTH, HEIGHT);
  renderer.shadowMapEnabled = true;
  $surface.append(renderer.domElement);

  // scene
  scene = new THREE.Scene();

  // and a camera
  camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
  // camera.position.x = 100;
  camera.position.y = 400;
  camera.position.z = 1000;
  // camera.rotation.x = -0.1;
  // camera.rotation.y = 0.2;
  scene.add(camera);

  // The Plane
  plane = new THREE.Mesh(new THREE.PlaneGeometry(2000, 2000, 20, 20),
    new THREE.MeshLambertMaterial());
  plane.position.y = -100;
  plane.rotation.x = -1.6;
  plane.receiveShadow = true;
  scene.add(plane);

  // The Cube
  var geometry = new THREE.CubeGeometry(100,100,100);
  var material = new THREE.MeshPhongMaterial({color: 0x75d1c8, shading: THREE.FlatShading});
  cube = new THREE.Mesh(geometry, material);
  cube.position.x = -150;
  cube.castShadow = true;
  scene.add(cube);

  // The Cube2
  var material2 = new THREE.MeshLambertMaterial({color: 0xcfbe6e, shading: THREE.FlatShading});
  cube2 = new THREE.Mesh(geometry, material2);
  cube2.position.x = 150;
  cube2.castShadow = true;
  scene.add(cube2);

  // Lights
  // spotlight #1 -- yellow, dark shadow
  spotlight = new THREE.SpotLight(0xb0b0e5);
  spotlight.position.set(0,600,-200);
  spotlight.shadowCameraVisible = true;
  spotlight.shadowDarkness = 0.6;
  spotlight.intensity = 1;
  // must enable shadow casting ability for the light
  spotlight.castShadow = true;
  scene.add(spotlight);

  var hemiLight = new THREE.HemisphereLight( 0x444444, 0x444444, 0.7 );
  // hemiLight.color.setHSL( 0.6, 1, 0.6 );
  // hemiLight.groundColor.setHSL( 0.095, 1, 0.75 );
  hemiLight.position.set( 0, 500, -400 );
  hemiLight.castShadow = true;
  scene.add( hemiLight );

  // Ambient light
  // var ambientLight = new THREE.AmbientLight(0x222222);
  // ambientLight.position.set( 0, 200, 100 );
  // scene.add(ambientLight);

  // directional lighting
  var directionalLight = new THREE.DirectionalLight(0xffffff);
  directionalLight.position.set(100, 100, 300);
  scene.add(directionalLight);

  // create "light-ball" meshes
  var sphereGeometry = new THREE.SphereGeometry( 10, 16, 8 );
  var darkMaterial = new THREE.MeshBasicMaterial( { color: 0x000000 } );

  var wireframeMaterial = new THREE.MeshBasicMaterial(
    { color: 0xffff00, wireframe: true, transparent: true } );
  var shape = THREE.SceneUtils.createMultiMaterialObject(
    sphereGeometry, [ darkMaterial, wireframeMaterial ] );
  shape.position = hemiLight.position;
  scene.add( shape );

  // var wireframeMaterial = new THREE.MeshBasicMaterial(
  //   { color: 0xff0000, wireframe: true, transparent: true } );
  // var shape = THREE.SceneUtils.createMultiMaterialObject(
  //   sphereGeometry, [ darkMaterial, wireframeMaterial ] );
  // shape.position = ambientLight.position;
  // scene.add( shape );

  var wireframeMaterial = new THREE.MeshBasicMaterial(
    { color: 0x0000ff, wireframe: true, transparent: true } );
  var shape = THREE.SceneUtils.createMultiMaterialObject(
    sphereGeometry, [ darkMaterial, wireframeMaterial ] );
  shape.position = directionalLight.position;
  scene.add( shape );

  var wireframeMaterial = new THREE.MeshBasicMaterial(
    { color: 0x5c683f, wireframe: true, transparent: true } );
  var shape = THREE.SceneUtils.createMultiMaterialObject(
    sphereGeometry, [ darkMaterial, wireframeMaterial ] );
  shape.position = spotlight.position;
  scene.add( shape );

  // Point light
  // var pointLight = new THREE.PointLight(0xFFFFFF);
  // pointLight.position.x = 10;
  // pointLight.position.y = 50;
  // pointLight.position.z = 130;
  // scene.add(pointLight);

  // Skybox/Fog
  // var skyBoxGeometry = new THREE.CubeGeometry( 10000, 10000, 10000 );
  // var skyBoxMaterial = new THREE.MeshBasicMaterial( { color: 0xcccccc, side: THREE.BackSide } );
  // var skyBox = new THREE.Mesh( skyBoxGeometry, skyBoxMaterial );
  // scene.add(skyBox);
  // scene.fog = new THREE.FogExp2( 0xcccccc, 0.00025 );

  // Controls
  controls = new THREE.TrackballControls(camera);
  controls.rotateSpeed = 1.0;
  controls.zoomSpeed = 1.2;
  controls.panSpeed = 0.8;

  controls.noZoom = false;
  controls.noPan = false;

  controls.staticMoving = true;
  controls.dynamicDampingFactor = 0.3;

  controls.keys = [ 65, 83, 68 ];

  // Axes
  var axes = new THREE.AxisHelper(50);
  scene.add(axes);

  // Stats
  stats = new Stats();
  $surface.append(stats.domElement);
}

// Animate
function animate() {

  requestAnimationFrame(animate);

  render();
  stats.update();
}

// Render
function render() {

  var timer = new Date().getTime() * 0.0005;

  if (spotlight.position.x <= -200 && reversed == false) {
    reversed = true;
  }
  else if (spotlight.position.x >= 200 && reversed == true) {
    reversed = false;
  }
  if (reversed) {
    spotlight.position.x += 2;
  }
  else {
    spotlight.position.x -= 2;
  }

  cube.rotation.x += 0.005;
  cube.rotation.y += 0.008;

  cube2.rotation.y += 0.02;

  // camera.lookAt(scene.position);
  // camera.position.x = Math.floor(Math.cos(timer) * 500);
  // camera.position.z = Math.floor(Math.sin(timer) * 500);

  controls.update();

  renderer.render(scene, camera);
}<commit_msg>Enable threejs antialias<commit_after>
if (!Detector.WebGL) Detector.addGetWebGLMessage();

var scene, camera, renderer;
var cube, cube2, plane, spotlight;
var controls;
var stats;

// Spotlight move
var reversed = false;

init();
animate();

function init() {

  var $surface = $('#surface');

  // set the scene size
  var WIDTH = 940,
      HEIGHT = 500;

  // set some camera attributes
  var VIEW_ANGLE = 50,
      ASPECT = WIDTH / HEIGHT,
      NEAR = 1,
      FAR = 10000;

  // Create a WebGL renderer
  renderer = new THREE.WebGLRenderer({antialias: true});
  renderer.setSize(WIDTH, HEIGHT);
  renderer.shadowMapEnabled = true;
  $surface.append(renderer.domElement);

  // scene
  scene = new THREE.Scene();

  // and a camera
  camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
  // camera.position.x = 100;
  camera.position.y = 400;
  camera.position.z = 1000;
  // camera.rotation.x = -0.1;
  // camera.rotation.y = 0.2;
  scene.add(camera);

  // The Plane
  plane = new THREE.Mesh(new THREE.PlaneGeometry(2000, 2000, 20, 20),
    new THREE.MeshLambertMaterial());
  plane.position.y = -100;
  plane.rotation.x = -1.6;
  plane.receiveShadow = true;
  scene.add(plane);

  // The Cube
  var geometry = new THREE.CubeGeometry(100,100,100);
  var material = new THREE.MeshPhongMaterial({color: 0x75d1c8, shading: THREE.FlatShading});
  cube = new THREE.Mesh(geometry, material);
  cube.position.x = -150;
  cube.castShadow = true;
  scene.add(cube);

  // The Cube2
  var material2 = new THREE.MeshLambertMaterial({color: 0xcfbe6e, shading: THREE.FlatShading});
  cube2 = new THREE.Mesh(geometry, material2);
  cube2.position.x = 150;
  cube2.castShadow = true;
  scene.add(cube2);

  // Lights
  // spotlight #1 -- yellow, dark shadow
  spotlight = new THREE.SpotLight(0xb0b0e5);
  spotlight.position.set(0,600,-200);
  spotlight.shadowCameraVisible = true;
  spotlight.shadowDarkness = 0.6;
  spotlight.intensity = 1;
  // must enable shadow casting ability for the light
  spotlight.castShadow = true;
  scene.add(spotlight);

  var hemiLight = new THREE.HemisphereLight( 0x444444, 0x444444, 0.7 );
  // hemiLight.color.setHSL( 0.6, 1, 0.6 );
  // hemiLight.groundColor.setHSL( 0.095, 1, 0.75 );
  hemiLight.position.set( 0, 500, -400 );
  hemiLight.castShadow = true;
  scene.add( hemiLight );

  // Ambient light
  // var ambientLight = new THREE.AmbientLight(0x222222);
  // ambientLight.position.set( 0, 200, 100 );
  // scene.add(ambientLight);

  // directional lighting
  var directionalLight = new THREE.DirectionalLight(0xffffff);
  directionalLight.position.set(100, 100, 300);
  scene.add(directionalLight);

  // create "light-ball" meshes
  var sphereGeometry = new THREE.SphereGeometry( 10, 16, 8 );
  var darkMaterial = new THREE.MeshBasicMaterial( { color: 0x000000 } );

  var wireframeMaterial = new THREE.MeshBasicMaterial(
    { color: 0xffff00, wireframe: true, transparent: true } );
  var shape = THREE.SceneUtils.createMultiMaterialObject(
    sphereGeometry, [ darkMaterial, wireframeMaterial ] );
  shape.position = hemiLight.position;
  scene.add( shape );

  // var wireframeMaterial = new THREE.MeshBasicMaterial(
  //   { color: 0xff0000, wireframe: true, transparent: true } );
  // var shape = THREE.SceneUtils.createMultiMaterialObject(
  //   sphereGeometry, [ darkMaterial, wireframeMaterial ] );
  // shape.position = ambientLight.position;
  // scene.add( shape );

  var wireframeMaterial = new THREE.MeshBasicMaterial(
    { color: 0x0000ff, wireframe: true, transparent: true } );
  var shape = THREE.SceneUtils.createMultiMaterialObject(
    sphereGeometry, [ darkMaterial, wireframeMaterial ] );
  shape.position = directionalLight.position;
  scene.add( shape );

  var wireframeMaterial = new THREE.MeshBasicMaterial(
    { color: 0x5c683f, wireframe: true, transparent: true } );
  var shape = THREE.SceneUtils.createMultiMaterialObject(
    sphereGeometry, [ darkMaterial, wireframeMaterial ] );
  shape.position = spotlight.position;
  scene.add( shape );

  // Point light
  // var pointLight = new THREE.PointLight(0xFFFFFF);
  // pointLight.position.x = 10;
  // pointLight.position.y = 50;
  // pointLight.position.z = 130;
  // scene.add(pointLight);

  // Skybox/Fog
  // var skyBoxGeometry = new THREE.CubeGeometry( 10000, 10000, 10000 );
  // var skyBoxMaterial = new THREE.MeshBasicMaterial( { color: 0xcccccc, side: THREE.BackSide } );
  // var skyBox = new THREE.Mesh( skyBoxGeometry, skyBoxMaterial );
  // scene.add(skyBox);
  // scene.fog = new THREE.FogExp2( 0xcccccc, 0.00025 );

  // Controls
  controls = new THREE.TrackballControls(camera);
  controls.rotateSpeed = 1.0;
  controls.zoomSpeed = 1.2;
  controls.panSpeed = 0.8;

  controls.noZoom = false;
  controls.noPan = false;

  controls.staticMoving = true;
  controls.dynamicDampingFactor = 0.3;

  controls.keys = [ 65, 83, 68 ];

  // Axes
  var axes = new THREE.AxisHelper(50);
  scene.add(axes);

  // Stats
  stats = new Stats();
  $surface.append(stats.domElement);
}

// Animate
function animate() {

  requestAnimationFrame(animate);

  render();
  stats.update();
}

// Render
function render() {

  var timer = new Date().getTime() * 0.0005;

  if (spotlight.position.x <= -200 && reversed == false) {
    reversed = true;
  }
  else if (spotlight.position.x >= 200 && reversed == true) {
    reversed = false;
  }
  if (reversed) {
    spotlight.position.x += 2;
  }
  else {
    spotlight.position.x -= 2;
  }

  cube.rotation.x += 0.005;
  cube.rotation.y += 0.008;

  cube2.rotation.y += 0.02;

  // camera.lookAt(scene.position);
  // camera.position.x = Math.floor(Math.cos(timer) * 500);
  // camera.position.z = Math.floor(Math.sin(timer) * 500);

  controls.update();

  renderer.render(scene, camera);
}<|endoftext|>


<commit_before>// Load modules

var Lab = require('lab');
var Bossy = require('../');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var before = lab.before;
var after = lab.after;
var describe = lab.experiment;
var it = lab.test;
var expect = Lab.expect;

describe('Bossy', function () {

    describe('#parse', function () {

        var parse = function (line, definition, options) {

            var orig = process.argv;
            process.argv = [].concat('ignore', 'ignore', line.split(' '));
            var result = null;
            try {
                result = Bossy.parse(definition, options);
            }
            catch (err) {
                result = err;
            }
            process.argv = orig;
            return result;
        };

        it('parses command line', function (done) {

            var line = '-a -cb --aa -C 1 -d x -d 2 -e 1-4,6-7 -f arg1 arg2 arg3';
            var definition = {
                a: {
                    type: 'boolean'
                },
                A: {
                    alias: 'aa',
                    type: 'boolean'
                },
                b: {
                    type: 'boolean'
                },
                c: {
                    type: 'boolean',
                    require: true
                },
                C: {
                    type: 'number'
                },
                d: {
                    type: 'string'
                },
                e: {
                    type: 'range'
                },
                f: {

                },
                g: {
                    type: 'boolean'
                },
                h: {
                    type: 'string',
                    default: 'hello',
                    alias: 'H'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.not.be.instanceof(Error);
            expect(argv).to.deep.equal({ a: true,
                A: true,
                b: true,
                c: true,
                g: false,
                C: 1,
                d: [ 'x', '2' ],
                e: [1, 2, 3, 4, 6, 7],
                f: 'arg1',
                _: ['arg2', 'arg3'],
                aa: true,
                h: 'hello',
                H: 'hello'
            });

            done();
        });

        it('copies values into all of a key\'s aliases', function (done) {

            var line = '--path ./usr/home/bin -c -T 1-4,6-7 --time 9000';
            var definition = {
                p: {
                    alias: ['path', 'Path', '$PATH']
                },
                c: {
                    alias: 'command',
                    type: 'boolean'
                },
                C: {
                    type: 'number',
                    alias: ['change', 'time']
                },
                t: {
                    type: 'range',
                    alias: ['T', 'tes']
                },
                h: {
                    type: 'string',
                    default: 'hello',
                    alias: 'H'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.not.be.instanceof(Error);
            expect(argv).to.deep.equal({
                c: true,
                p: './usr/home/bin',
                t: [1, 2, 3, 4, 6, 7],
                path: './usr/home/bin',
                Path: './usr/home/bin',
                '$PATH': './usr/home/bin',
                C: 9000,
                change: 9000,
                command: true,
                time: 9000,
                T: [1, 2, 3, 4, 6, 7],
                tes: [1, 2, 3, 4, 6, 7],
                h: 'hello',
                H: 'hello'
            });

            done();
        });

        it('returns error message when required parameter is missing', function (done) {

            var line = '-a';
            var definition = {
                a: {
                    type: 'boolean'
                },
                b: {
                    type: 'number',
                    require: true
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when an unknown argument is used', function (done) {

            var line = '-ac';
            var definition = {
                a: {
                    type: 'boolean'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when an empty - is passed', function (done) {

            var line = '-';
            var definition = {
                a: {
                    type: 'boolean'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when an empty -- is passed', function (done) {

            var line = '--';
            var definition = {
                a: {
                    type: 'boolean'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when an empty value is passed', function (done) {

            var line = '-b -a';
            var definition = {
                a: {
                    type: 'string'
                },
                b: {
                    type: 'string'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when a non-number value is passed for a number argument', function (done) {

            var line = '-a hi';
            var definition = {
                a: {
                    type: 'number'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns undefined when an empty value is passed for a range', function (done) {

            var line = '-a';
            var definition = {
                a: {
                    type: 'range'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: undefined });

            done();
        });

        it('is able to parse a range plus an additional number', function (done) {

            var line = '-a 1-2,5';
            var definition = {
                a: {
                    type: 'range'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: [1, 2, 5] });

            done();
        });

        it('is able to parse a range in reverse order', function (done) {

            var line = '-a 5-1';
            var definition = {
                a: {
                    type: 'range'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: [5, 4, 3, 2, 1] });

            done();
        });

        it('allows a boolean to be defaulted to null', function (done) {

            var line = '';
            var definition = {
                a: {
                    type: 'boolean',
                    default: null
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: null, _: '' });

            done();
        });

        it('allows custom argv to be passed in options in place of process.argv', function (done) {

            var argv = ['node', 'cli', '-a', '1-2,5'];
            var definition = {
                a: {
                    type: 'range'
                }
            };

            var argv = Bossy.parse(definition, { argv: argv });
            expect(argv).to.deep.equal({ a: [1, 2, 5] });

            done();
        });

        it('returns error message when a value isn\'t found in the valid property', function (done) {

            var line = '-a 2';
            var definition = {
                a: {
                    type: 'number',
                    valid: 1
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when a value isn\'t found in array of valid values', function (done) {

            var line = '-a 4';
            var definition = {
                a: {
                    type: 'number',
                    valid: [1, 2, 3]
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('doesn\'t return an error when the value is in the valid array', function (done) {

            var line = '-a 2';
            var definition = {
                a: {
                    type: 'number',
                    valid: [1, 2, 3]
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: 2 });

            done();
        });

        it('doesn\'t return an error when the value is in equal to the valid value', function (done) {

            var line = '-a 0';
            var definition = {
                a: {
                    type: 'number',
                    valid: 0
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: 0 });

            done();
        });

        it('displays unrecognized arguments in error message ', function (done) {

            var line = '-a 0 -b';
            var definition = {
                a: {
                    type: 'number',
                    description: 'This needs a number'
                }
            };

            var argv = parse(line, definition);
            expect(argv.message).to.contain('Unknown option: b');

            done();
        });
    });

    describe('#usage', function () {

        it('returns formatted usage information', function (done) {

            var definition = {
                a: {
                    type: 'number',
                    description: 'This needs a number'
                },
                b: {
                    alias: 'beta',
                    require: true,
                    description: 'Description for b'
                },
                c: {
                    require: true
                }
            };

            var result = Bossy.usage(definition);
            expect(result).to.contain('-a');
            expect(result).to.contain('This needs a number');
            expect(result).to.contain('-b, --beta');
            done();
        });

        it('returns formatted usage header when provided', function (done) {

            var definition = {
                h: {
                    type: 'string',
                    description: 'Show help'
                }
            };

            var result = Bossy.usage(definition, 'bossy -h');
            expect(result).to.contain('Usage: bossy -h');
            expect(result).to.contain('-h');
            expect(result).to.contain('Show help');
            done();
        });

        it('returns formatted usage information with colors when enabled', function (done) {

            var definition = {
                a: {
                    alias: 'alpha',
                    require: true,
                    description: 'Description for b'
                }
            };

            var result = Bossy.usage(definition, { colors: true });

            expect(result).to.contain('-a');
            expect(result).to.contain('\u001b[0m');
            done();
        });

        it('when colors are missing defaults to true if tty supports colors', function (done) {

            var definition = {
                a: {
                    alias: 'alpha',
                    require: true,
                    description: 'Description for b'
                }
            };

            var Tty = require('tty');
            var currentIsAtty = Tty.isatty;

            Tty.isatty = function () {

                Tty.isatty = currentIsAtty;
                return true;
            };

            var result = Bossy.usage(definition);

            expect(result).to.contain('-a');
            expect(result).to.contain('\u001b[0m');
            done();
        });

        it('when colors are missing defaults to false if tty doesn\'t support colors', function (done) {

            var definition = {
                a: {
                    alias: 'alpha',
                    require: true,
                    description: 'Description for b'
                }
            };

            var Tty = require('tty');
            var currentIsAtty = Tty.isatty;

            Tty.isatty = function () {

                Tty.isatty = currentIsAtty;
                return false;
            };

            var result = Bossy.usage(definition);

            expect(result).to.contain('-a');
            expect(result).to.not.contain('\u001b[0m');
            done();
        });

        it('returns colors usage information when passed as parameter', function (done) {

            var definition = {
                a: {
                    alias: 'alpha',
                    require: true,
                    description: 'Description for b'
                }
            };

            var result = Bossy.usage(definition, 'bossy -c', { colors: true });

            expect(result).to.contain('bossy');
            expect(result).to.contain('-a');
            expect(result).to.contain('\u001b[0m');
            done();
        });

        it('formatted usage message orders as -s,--long in first column', function (done) {

            var definition = {
                a: {
                    type: 'number',
                    description: 'This needs a number'
                },
                b: {
                    alias: 'beta',
                    description: 'Description for b'
                },
                code: {
                    alias: 'c'
                },
                d: {
                    alias: ['']
                }
            };

            var result = Bossy.usage(definition);
            expect(result).to.contain('-a');
            expect(result).to.contain('-b, --beta');
            expect(result).to.contain('-c, --code');
            done();
        });
    });
});
<commit_msg>Cleaned up test.<commit_after>// Load modules

var Lab = require('lab');
var Bossy = require('../');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var describe = lab.experiment;
var it = lab.test;
var expect = Lab.expect;

describe('Bossy', function () {

    describe('parse()', function () {

        var parse = function (line, definition, options) {

            var orig = process.argv;
            process.argv = [].concat('ignore', 'ignore', line.split(' '));
            var result = null;
            try {
                result = Bossy.parse(definition, options);
            }
            catch (err) {
                result = err;
            }
            process.argv = orig;
            return result;
        };

        it('parses command line', function (done) {

            var line = '-a -cb --aa -C 1 -d x -d 2 -e 1-4,6-7 -f arg1 arg2 arg3';
            var definition = {
                a: {
                    type: 'boolean'
                },
                A: {
                    alias: 'aa',
                    type: 'boolean'
                },
                b: {
                    type: 'boolean'
                },
                c: {
                    type: 'boolean',
                    require: true
                },
                C: {
                    type: 'number'
                },
                d: {
                    type: 'string'
                },
                e: {
                    type: 'range'
                },
                f: {

                },
                g: {
                    type: 'boolean'
                },
                h: {
                    type: 'string',
                    default: 'hello',
                    alias: 'H'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.not.be.instanceof(Error);
            expect(argv).to.deep.equal({ a: true,
                A: true,
                b: true,
                c: true,
                g: false,
                C: 1,
                d: [ 'x', '2' ],
                e: [1, 2, 3, 4, 6, 7],
                f: 'arg1',
                _: ['arg2', 'arg3'],
                aa: true,
                h: 'hello',
                H: 'hello'
            });

            done();
        });

        it('copies values into all of a key\'s aliases', function (done) {

            var line = '--path ./usr/home/bin -c -T 1-4,6-7 --time 9000';
            var definition = {
                p: {
                    alias: ['path', 'Path', '$PATH']
                },
                c: {
                    alias: 'command',
                    type: 'boolean'
                },
                C: {
                    type: 'number',
                    alias: ['change', 'time']
                },
                t: {
                    type: 'range',
                    alias: ['T', 'tes']
                },
                h: {
                    type: 'string',
                    default: 'hello',
                    alias: 'H'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.not.be.instanceof(Error);
            expect(argv).to.deep.equal({
                c: true,
                p: './usr/home/bin',
                t: [1, 2, 3, 4, 6, 7],
                path: './usr/home/bin',
                Path: './usr/home/bin',
                '$PATH': './usr/home/bin',
                C: 9000,
                change: 9000,
                command: true,
                time: 9000,
                T: [1, 2, 3, 4, 6, 7],
                tes: [1, 2, 3, 4, 6, 7],
                h: 'hello',
                H: 'hello'
            });

            done();
        });

        it('returns error message when required parameter is missing', function (done) {

            var line = '-a';
            var definition = {
                a: {
                    type: 'boolean'
                },
                b: {
                    type: 'number',
                    require: true
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when an unknown argument is used', function (done) {

            var line = '-ac';
            var definition = {
                a: {
                    type: 'boolean'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when an empty - is passed', function (done) {

            var line = '-';
            var definition = {
                a: {
                    type: 'boolean'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when an empty -- is passed', function (done) {

            var line = '--';
            var definition = {
                a: {
                    type: 'boolean'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when an empty value is passed', function (done) {

            var line = '-b -a';
            var definition = {
                a: {
                    type: 'string'
                },
                b: {
                    type: 'string'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when a non-number value is passed for a number argument', function (done) {

            var line = '-a hi';
            var definition = {
                a: {
                    type: 'number'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns undefined when an empty value is passed for a range', function (done) {

            var line = '-a';
            var definition = {
                a: {
                    type: 'range'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: undefined });

            done();
        });

        it('is able to parse a range plus an additional number', function (done) {

            var line = '-a 1-2,5';
            var definition = {
                a: {
                    type: 'range'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: [1, 2, 5] });

            done();
        });

        it('is able to parse a range in reverse order', function (done) {

            var line = '-a 5-1';
            var definition = {
                a: {
                    type: 'range'
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: [5, 4, 3, 2, 1] });

            done();
        });

        it('allows a boolean to be defaulted to null', function (done) {

            var line = '';
            var definition = {
                a: {
                    type: 'boolean',
                    default: null
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: null, _: '' });

            done();
        });

        it('allows custom argv to be passed in options in place of process.argv', function (done) {

            var argv = ['node', 'cli', '-a', '1-2,5'];
            var definition = {
                a: {
                    type: 'range'
                }
            };

            var argv = Bossy.parse(definition, { argv: argv });
            expect(argv).to.deep.equal({ a: [1, 2, 5] });

            done();
        });

        it('returns error message when a value isn\'t found in the valid property', function (done) {

            var line = '-a 2';
            var definition = {
                a: {
                    type: 'number',
                    valid: 1
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('returns error message when a value isn\'t found in array of valid values', function (done) {

            var line = '-a 4';
            var definition = {
                a: {
                    type: 'number',
                    valid: [1, 2, 3]
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.be.instanceof(Error);

            done();
        });

        it('doesn\'t return an error when the value is in the valid array', function (done) {

            var line = '-a 2';
            var definition = {
                a: {
                    type: 'number',
                    valid: [1, 2, 3]
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: 2 });

            done();
        });

        it('doesn\'t return an error when the value is in equal to the valid value', function (done) {

            var line = '-a 0';
            var definition = {
                a: {
                    type: 'number',
                    valid: 0
                }
            };

            var argv = parse(line, definition);
            expect(argv).to.deep.equal({ a: 0 });

            done();
        });

        it('displays unrecognized arguments in error message ', function (done) {

            var line = '-a 0 -b';
            var definition = {
                a: {
                    type: 'number',
                    description: 'This needs a number'
                }
            };

            var argv = parse(line, definition);
            expect(argv.message).to.contain('Unknown option: b');

            done();
        });
    });

    describe('usage()', function () {

        it('returns formatted usage information', function (done) {

            var definition = {
                a: {
                    type: 'number',
                    description: 'This needs a number'
                },
                b: {
                    alias: 'beta',
                    require: true,
                    description: 'Description for b'
                },
                c: {
                    require: true
                }
            };

            var result = Bossy.usage(definition);
            expect(result).to.contain('-a');
            expect(result).to.contain('This needs a number');
            expect(result).to.contain('-b, --beta');
            done();
        });

        it('returns formatted usage header when provided', function (done) {

            var definition = {
                h: {
                    type: 'string',
                    description: 'Show help'
                }
            };

            var result = Bossy.usage(definition, 'bossy -h');
            expect(result).to.contain('Usage: bossy -h');
            expect(result).to.contain('-h');
            expect(result).to.contain('Show help');
            done();
        });

        it('returns formatted usage information with colors when enabled', function (done) {

            var definition = {
                a: {
                    alias: 'alpha',
                    require: true,
                    description: 'Description for b'
                }
            };

            var result = Bossy.usage(definition, { colors: true });

            expect(result).to.contain('-a');
            expect(result).to.contain('\u001b[0m');
            done();
        });

        it('when colors are missing defaults to true if tty supports colors', function (done) {

            var definition = {
                a: {
                    alias: 'alpha',
                    require: true,
                    description: 'Description for b'
                }
            };

            var Tty = require('tty');
            var currentIsAtty = Tty.isatty;

            Tty.isatty = function () {

                Tty.isatty = currentIsAtty;
                return true;
            };

            var result = Bossy.usage(definition);

            expect(result).to.contain('-a');
            expect(result).to.contain('\u001b[0m');
            done();
        });

        it('when colors are missing defaults to false if tty doesn\'t support colors', function (done) {

            var definition = {
                a: {
                    alias: 'alpha',
                    require: true,
                    description: 'Description for b'
                }
            };

            var Tty = require('tty');
            var currentIsAtty = Tty.isatty;

            Tty.isatty = function () {

                Tty.isatty = currentIsAtty;
                return false;
            };

            var result = Bossy.usage(definition);

            expect(result).to.contain('-a');
            expect(result).to.not.contain('\u001b[0m');
            done();
        });

        it('returns colors usage information when passed as parameter', function (done) {

            var definition = {
                a: {
                    alias: 'alpha',
                    require: true,
                    description: 'Description for b'
                }
            };

            var result = Bossy.usage(definition, 'bossy -c', { colors: true });

            expect(result).to.contain('bossy');
            expect(result).to.contain('-a');
            expect(result).to.contain('\u001b[0m');
            done();
        });

        it('formatted usage message orders as -s,--long in first column', function (done) {

            var definition = {
                a: {
                    type: 'number',
                    description: 'This needs a number'
                },
                b: {
                    alias: 'beta',
                    description: 'Description for b'
                },
                code: {
                    alias: 'c'
                },
                d: {
                    alias: ['']
                }
            };

            var result = Bossy.usage(definition);
            expect(result).to.contain('-a');
            expect(result).to.contain('-b, --beta');
            expect(result).to.contain('-c, --code');
            done();
        });
    });
});
<|endoftext|>


<commit_before>var verpostit=(function(){
function verpostit(){}
function inprivate(){
var request=new XMLHttpRequest();
var postitconfig="verify=user.application";
request.open("POST","../resources/postitload.php");
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.onload=function(){
if(request.status==200){
var postitString=JSON.stringify(eval("("+request.responseText+")"));
var postitJSON=JSON.parse(postitString);
for(var key in postitJSON){
if(postitJSON[key]!==null){
var division=document.createElement("div");
var image=document.createElement("img");
image.src="posted/user.application/"+postitJSON[key]+"/"+key+"";
image.className="posted";
image.id="user.application/"+postitJSON[key]+"/"+key+"";
image.addEventListener("drag",function(e){
e.preventDefault();
var deletepostit=new XMLHttpRequest();
var target="deletepostit="+this.id+"";
deletepostit.open("POST","../resources/postitunload.php");
deletepostit.setRequestHeader("Content-type","application/x-www-form-urlencoded");
deletepostit.onload=function(){
if(deletepostit.status==200 && deletepostit.responseText!==""){
var path=window.location.pathname;
var fileIndex=path.lastIndexOf('/')+1;
var fileName=path.substr(fileIndex);
window.location.replace(fileName);
}
};
deletepostit.send(target);
});
var section=document.getElementsByTagName("h1");
division.appendChild(image);
for(var i=0;i<section.length;i++){
if(section.item(i).innerHTML==postitJSON[key]){
section.item(i).parentNode.appendChild(division);
}
}
}
}
//Receive JSON with srcs and load postit in its section
}
};
request.send(postitconfig);
}
verpostit.prototype.inpublic=function(){
return inprivate.call(this);
};
return verpostit;
})();
var verobj=new verpostit();
verobj.inpublic();<commit_msg>Minor bug fix<commit_after>var verpostit=(function(){
function verpostit(){}
function inprivate(){
var request=new XMLHttpRequest();
var postitconfig="verify=user.application";
request.open("POST","../resources/postitload.php");
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.onload=function(){
if(request.status==200 && request.responseText!==""){
var postitString=JSON.stringify(eval("("+request.responseText+")"));
var postitJSON=JSON.parse(postitString);
for(var key in postitJSON){
if(postitJSON[key]!==null){
var division=document.createElement("div");
var image=document.createElement("img");
image.src="posted/user.application/"+postitJSON[key]+"/"+key+"";
image.className="posted";
image.id="user.application/"+postitJSON[key]+"/"+key+"";
image.addEventListener("drag",function(e){
e.preventDefault();
var deletepostit=new XMLHttpRequest();
var target="deletepostit="+this.id+"";
deletepostit.open("POST","../resources/postitunload.php");
deletepostit.setRequestHeader("Content-type","application/x-www-form-urlencoded");
deletepostit.onload=function(){
if(deletepostit.status==200 && deletepostit.responseText!==""){
var path=window.location.pathname;
var fileIndex=path.lastIndexOf('/')+1;
var fileName=path.substr(fileIndex);
window.location.replace(fileName);
}
};
deletepostit.send(target);
});
var section=document.getElementsByTagName("h1");
division.appendChild(image);
for(var i=0;i<section.length;i++){
if(section.item(i).innerHTML==postitJSON[key]){
section.item(i).parentNode.appendChild(division);
}
}
}
}
}
};
request.send(postitconfig);
}
verpostit.prototype.inpublic=function(){
return inprivate.call(this);
};
return verpostit;
})();
var verobj=new verpostit();
verobj.inpublic();<|endoftext|>


<commit_before>var heads               = require('robohydra').heads,
    RoboHydraHead       = require("robohydra").heads.RoboHydraHead,
    RoboHydraHeadStatic = heads.RoboHydraHeadStatic,
    token               = require('./tokens.js').token,
    apiPrefix           = "/api/v1";

exports.getBodyParts = function(config, modules) {
  archives = {
    'Photos': {
      "status" : "creating",
      "key" : "58-CXSS2Q",
      "size" : 50000,
      "checksum" : null,
      "created" : "2014-06-30T17:01:21.887Z",
      "url" : "http://stage.deepfreeze.io/api/v1/archives/58/",
      "upload" : "http://stage.deepfreeze.io/api/v1/archives/58/upload/",
      "title": "Photos"
    },
    'Other': {
      "status" : "creating",
      "key" : "58-CXSS2Q",
      "size" : 50000,
      "checksum" : null,
      "created" : "2014-06-30T17:01:21.887Z",
      "url" : "http://stage.deepfreeze.io/api/v1/archives/58/",
      "upload" : "http://stage.deepfreeze.io/api/v1/archives/58/upload/",
      "title": "Other"
    }
  }
  test_user = {
    "archives" : {
      "previous" : null,
      "next" : null,
      "count" : 1,
      "results" : [
        {
          "status" : "frozen",
          "key" : "55-45U2PD",
          "size" : 123,
          "checksum" : "3bffca7b1dfc604550df94213727b9bc",
          "created" : "2014-06-30T15:16:00.636Z",
          "url" : "http://stage.deepfreeze.io/api/v1/archives/55/",
          "upload" : "http://stage.deepfreeze.io/api/v1/archives/55/upload/",
          "title" : "some title"
        }
      ]
    },
    "email" : "koukopoulos@gmail.com",
    "displayname" : "Konstantinos Koukopoulos",
    "id" : 8,
    "date_joined" : "2014-06-30T14:55:43.645Z",
    "quota": {
      "size": 1000000000,
      "used": 150123
    },
    "avatar": {
      "avatar22": "http://gravatar.com/avatar/58fc8f2e1ffa8f4b01a86a6c66cb2100?d=mm&s=22",
      "avatar80": "http://gravatar.com/avatar/58fc8f2e1ffa8f4b01a86a6c66cb2100?d=mm",
      "avatar48": "http://gravatar.com/avatar/58fc8f2e1ffa8f4b01a86a6c66cb2100?d=mm&s=48"
    }
  }
  function meta(n){
    return {
      limit: 20,
      next: null,
      offset: 0,
      previous: null,
      total_count: n
    }
  }
  return {
    heads: [
      new RoboHydraHeadStatic({
        path: apiPrefix + '/user/',
        content: test_user
      }),
      new RoboHydraHeadStatic({
        path: apiPrefix + '/archives/1/',
        content: archives.Other
      }),
      new RoboHydraHeadStatic({
        path: apiPrefix + '/archives/',
        content: {
          meta: meta(2),
          results: [
            archives.Photos,
            archives.Other
          ]
        }
      }),
      new RoboHydraHead({
        path: apiPrefix + '/archives/',
        handler: function(req, res, next) {
          modules.assert.equal(req.method, "POST", "Upload resource supports only POST")
          content = JSON.parse(req.rawBody)
          modules.assert.ok("title" in content)
          modules.assert.ok("user_id" in content)
          modules.assert.ok("size" in content)
          res.status = '201';
          date = new Date();
          var archive = {
            "status" : "creating",
            "key" : "58-CXSS2Q",
            "size" : content.size,
            "checksum" : null,
            "created" : date,
            "url" : "http://stage.deepfreeze.io/api/v1/archives/58/",
            "upload" : "http://stage.deepfreeze.io/api/v1/archives/58/upload/",
            "title": content.title
          }
          res.write(JSON.stringify(archive));
          res.end();
        }
      })
    ]
  }
}
<commit_msg>Add robohydra heads for uploads and fix head for creating archive<commit_after>var heads               = require('robohydra').heads,
    RoboHydraHead       = require("robohydra").heads.RoboHydraHead,
    RoboHydraHeadStatic = heads.RoboHydraHeadStatic,
    apiPrefix           = "/api/v1";

exports.getBodyParts = function(config, modules) {
  archives = {
    'Photos': {
      "status" : "creating",
      "key" : "58-CXSS2Q",
      "size" : 50000,
      "checksum" : null,
      "created" : "2014-06-30T17:01:21.887Z",
      "url" : "http://stage.deepfreeze.io/api/v1/archives/58/",
      "upload" : "http://stage.deepfreeze.io/api/v1/archives/58/upload/",
      "title": "Photos"
    },
    'Other': {
      "status" : "creating",
      "key" : "58-CXSS2Q",
      "size" : 50000,
      "checksum" : null,
      "created" : "2014-06-30T17:01:21.887Z",
      "url" : "http://stage.deepfreeze.io/api/v1/archives/58/",
      "upload" : "http://stage.deepfreeze.io/api/v1/archives/58/upload/",
      "title": "Other"
    }
  }
  test_user = {
    "archives" : {
      "previous" : null,
      "next" : null,
      "count" : 1,
      "results" : [
        {
          "status" : "frozen",
          "key" : "55-45U2PD",
          "size" : 123,
          "checksum" : "3bffca7b1dfc604550df94213727b9bc",
          "created" : "2014-06-30T15:16:00.636Z",
          "url" : "http://stage.deepfreeze.io/api/v1/archives/55/",
          "upload" : "http://stage.deepfreeze.io/api/v1/archives/55/upload/",
          "title" : "some title"
        }
      ]
    },
    "email" : "koukopoulos@gmail.com",
    "displayname" : "Konstantinos Koukopoulos",
    "id" : 8,
    "date_joined" : "2014-06-30T14:55:43.645Z",
    "quota": {
      "size": 1000000000,
      "used": 150123
    },
    "avatar": {
      "avatar22": "http://gravatar.com/avatar/58fc8f2e1ffa8f4b01a86a6c66cb2100?d=mm&s=22",
      "avatar80": "http://gravatar.com/avatar/58fc8f2e1ffa8f4b01a86a6c66cb2100?d=mm",
      "avatar48": "http://gravatar.com/avatar/58fc8f2e1ffa8f4b01a86a6c66cb2100?d=mm&s=48"
    }
  }
  upload = {
    'archive': 'http://localhost:8000/api/v1/archives/83/',
    'comment': '',
    'created': '2015-02-04T11:53:35.237Z',
    's3': {
      'bucket': '',
      'prefix': '/upload/2015-02-04-11-53-18/',
      'token_access_key': '',
      'token_expiration': '2015-02-05T11:53:36Z',
      'token_secret_key': '',
      'token_session': '',
      'token_uid': 'lacli'
    },
    'status': 'pending',
    'url': 'http://localhost:8000/api/v1/uploads/18/'
  }

  function meta(n){
    return {
      limit: 20,
      next: null,
      offset: 0,
      previous: null,
      total_count: n
    }
  }
  return {
    heads: [
      new RoboHydraHeadStatic({
        path: apiPrefix + '/user/',
        content: test_user
      }),
      new RoboHydraHeadStatic({
        path: apiPrefix + '/archives/1/',
        content: archives.Other
      }),
      new RoboHydraHead({
        path: apiPrefix + '/archives/',
        handler: function(req, res, next) {
          if (req.method == 'POST'){
            content = JSON.parse(req.rawBody)
            modules.assert.ok("title" in content)
            modules.assert.ok("user_id" in content)
            modules.assert.ok("size" in content)
            res.status = '201';
            date = new Date();
            var archive = {
              "status" : "creating",
              "key" : "58-CXSS2Q",
              "size" : content.size,
              "checksum" : null,
              "created" : date,
              "url" : "http://stage.deepfreeze.io/api/v1/archives/58/",
              "upload" : "http://stage.deepfreeze.io/api/v1/archives/58/upload/",
              "title": content.title
            }
            res.write(JSON.stringify(archive));
            res.end();
          } else if (req.method == 'GET'){
            var content = {
              meta: meta(2),
              results: [
                archives.Photos,
                archives.Other
              ]
            }
            res.status = '200';
            res.write(JSON.stringify(content));
            res.end();
          }
        }
      }),
      new RoboHydraHead({
        path: apiPrefix + '/uploads/1/',
        handler: function(req, res, next) {
          if (req.method == 'GET'){
            res.status = '200';
            res.write(JSON.stringify(upload));
            res.end();
          } else if (req.method == 'PATCH'){
            content = JSON.parse(req.rawBody)
            modules.assert.ok("status" in content)
            var patched_upload = upload;
            patched_upload.status = content.status;
            res.write(JSON.stringify(patched_upload));
            res.end();
          } else if (req.method == 'DELETE'){
            res.status = '204';
            res.end();
          }
        }
      })
    ]
  }
}
<|endoftext|>


<commit_before>/*global describe*/

'use strict';

require('source-map-support').install();

global.sinon = require("sinon");

var chai = global.chai = require("chai");

chai.use(require("sinon-chai"));
chai.should();

var Promise   = global.testPromise = require('bluebird');
global.expect = chai.expect;
global.d      = new Date();

Promise.longStackTraces();

describe('Query Building Tests', function() {
  this.timeout(process.env.KNEX_TEST_TIMEOUT || 5000);

  require('./unit/query/builder')
  require('./unit/schema/mysql')('mysql')
  require('./unit/schema/mysql')('maria')
  require('./unit/schema/mysql')('mysql2')
  require('./unit/schema/postgres')
  require('./unit/schema/sqlite3')
  require('./unit/schema/oracle')
  require('./unit/schema/mssql')
  require('./unit/schema/oracledb')
})

var config = require('./knexfile');
if (config.oracledb) {
  describe('Oracledb driver tests', function() {
    this.timeout(process.env.KNEX_TEST_TIMEOUT || 5000);
    require('./unit/dialects/oracledb');
  });
}

describe('Integration Tests', function() {
  this.timeout(process.env.KNEX_TEST_TIMEOUT || 5000);
  require('./integration')
})
<commit_msg>move oracle driver specific test to bottom<commit_after>/*global describe*/

'use strict';

require('source-map-support').install();

global.sinon = require("sinon");

var chai = global.chai = require("chai");

chai.use(require("sinon-chai"));
chai.should();

var Promise   = global.testPromise = require('bluebird');
global.expect = chai.expect;
global.d      = new Date();

Promise.longStackTraces();

describe('Query Building Tests', function() {
  this.timeout(process.env.KNEX_TEST_TIMEOUT || 5000);

  require('./unit/query/builder')
  require('./unit/schema/mysql')('mysql')
  require('./unit/schema/mysql')('maria')
  require('./unit/schema/mysql')('mysql2')
  require('./unit/schema/postgres')
  require('./unit/schema/sqlite3')
  require('./unit/schema/oracle')
  require('./unit/schema/mssql')
  require('./unit/schema/oracledb')
})

describe('Integration Tests', function() {
  this.timeout(process.env.KNEX_TEST_TIMEOUT || 5000);
  require('./integration')
})

var config = require('./knexfile');
if (config.oracledb) {
  describe('Oracledb driver tests', function() {
    this.timeout(process.env.KNEX_TEST_TIMEOUT || 5000);
    require('./unit/dialects/oracledb');
  });
}
<|endoftext|>


<commit_before>define([
    'jquery',
    'knockout',
    'knockout.validation',
    'app',
    'models/user',
    'models/user_session'
], function (
    $,
    ko,
    validation,
    app,
    User,
    UserSession
) {
    var registerPage = ko.validatedObservable({
        email: ko.observable(),
        register: function () {
            $.ajax({
                type: 'POST',
                url: '/api/users',
                data: JSON.stringify({
                    email: this.email()
                }),
                contentType: 'application/json',
                processData: false
            }).done(function (data) {
                var user = User.create(data);
                $.ajax({
                    type: 'POST',
                    url: user.user_sessions.uri(),
                    data: JSON.stringify({}),
                    contentType: 'application/json',
                    processData: false
                }).done(function (data) {
                    app.user(user);
                    app.session(UserSession.create(data));
                    app.router.redirect((app.pager.last_page().originalPath && app.pager.last_page().originalPath) || '/');
                });
            });
        }
    });

    return registerPage();
});
<commit_msg>Fix registering (and add really bad error feedback)<commit_after>define([
    'jquery',
    'knockout',
    'knockout.validation',
    'app',
    'models/user',
    'models/user_session'
], function (
    $,
    ko,
    validation,
    app,
    User,
    UserSession
) {
    var registerPage = ko.validatedObservable({
        email: ko.observable(),
        register: function () {
            $.ajax({
                type: 'POST',
                url: '/api/users',
                data: JSON.stringify({
                    email: this.email()
                }),
                contentType: 'application/json',
                processData: false
            }).done(function (data) {
                if (data.error) {
                    alert(JSON.stringify(data.errors));
                } else {
                    var user = User.create(data);
                    $.ajax({
                        type: 'POST',
                        url: user.user_sessions().uri(),
                        data: JSON.stringify({}),
                        contentType: 'application/json',
                        processData: false
                    }).done(function (data) {
                        app.user(user);
                        app.session(UserSession.create(data));
                        app.router.redirect((app.pager.last_page() && app.pager.last_page().originalPath) || '/');
                    });
                }
            });
        }
    });

    return registerPage();
});
<|endoftext|>


<commit_before>$(".top-bar .account-info > .usercontainer > .name").click(function (e) {
  e.stopPropagation();
  e.preventDefault();
  let optionsbox = $(".top-bar .account-options");
  let tween = TweenLite.to(optionsbox, 0.75, {
    ease: Expo.easeOut,
    boxShadow: "0px 3px 5px rgba(0, 0, 0, 0.35)",
    top: "3rem",
    opacity: 1
  });

  if (optionsbox.css(display) === "none") {
    tween.play();
  } else {
    tween.reverse();
  }
});<commit_msg>Fixes JS error in web:<commit_after>$(".top-bar .account-info > .usercontainer > .name").click(function (e) {
  e.stopPropagation();
  e.preventDefault();
  let optionsbox = $(".top-bar .account-options");
  let tween = TweenLite.to(optionsbox, 0.75, {
    ease: Power4.easeOut,
    boxShadow: "0px 3px 5px rgba(0, 0, 0, 0.35)",
    top: "3rem",
    opacity: 1
  });

  if (optionsbox.css(display) === "none") {
    tween.play();
  } else {
    tween.reverse();
  }
});<|endoftext|>


<commit_before>var assert = require('assert')
var req = require('../')

// require a directory
var configs = req('./configs')
assert.ok(configs.root === 'yaml is good')

// require a directory
var configs = req('./configs/foo/')
assert.ok(configs.bar === 'tada')

// require a empty directory
var configs = req('./configs/foo/empty')
assert.ok(configs === undefined)

// require a json file
var json = req('./configs/humans/lowb/me.json')
assert.ok(json.nice === true)

// require a no extension json file
var json = req('./configs/humans/lowb/me')
assert.ok(json.nice === true)

// require a empty json file
var json = req('./configs/foo/nothing.json')
assert.ok(json === undefined)

// require a yml file
var yml = req('./configs/humans/human.b.yml')
assert.ok(yml.head === true)

// require a no extension yml file
var yml = req('./configs/humans/human-a')
assert.ok(yml.head === true)

// require a empty yml file
var yml = req('./configs/foo/nothing.yml')
assert.ok(yml === undefined)

// require a yaml file
var yaml = req('./configs/humans/humanC.yaml')
assert.ok(yaml.head === true)

// require a no extension yaml file
var yaml = req('./configs/humans/humanC')
assert.ok(yaml.head === true)

// iterator
var iterator = function(json) {
	if (json.head) delete json.head
	json.inject = 'everywhere'
	return json
}
var yml = req('./configs', iterator)
assert.equal(yml.humans.humanC.head)
assert.ok(yml.foo.sth.inject === 'everywhere')

// async
req('./configs', null, function(yml){
	assert.ok(yml.foo.bar)
})

console.log('test ok.')<commit_msg>add test to the new code<commit_after>var assert = require('assert')
var req = require('../')

// require a directory
var configs = req('./configs')
assert.ok(configs.root === 'yaml is good')

// require a directory
var configs = req('./configs/foo/')
assert.ok(configs.bar === 'tada')

// require a empty directory
var configs = req('./configs/foo/empty')
assert.ok(configs === undefined)

// require a json file
var json = req('./configs/humans/lowb/me.json')
assert.ok(json.nice === true)

// require a no extension json file
var json = req('./configs/humans/lowb/me')
assert.ok(json.nice === true)

// require a empty json file
var json = req('./configs/foo/nothing.json')
assert.ok(json === undefined)

// require a yml file
var yml = req('./configs/humans/human.b.yml')
assert.ok(yml.head === true)

// require a no extension yml file
var yml = req('./configs/humans/human-a')
assert.ok(yml.head === true)

// require a empty yml file
var yml = req('./configs/foo/nothing.yml')
assert.ok(yml === undefined)

// require a yaml file
var yaml = req('./configs/humans/humanC.yaml')
assert.ok(yaml.head === true)

// require a no extension yaml file
var yaml = req('./configs/humans/humanC')
assert.ok(yaml.head === true)

// iterator
var iterator = function(json) {
	if (json.head) delete json.head
	json.inject = 'everywhere'
	return json
}
var yml = req('./configs', iterator)
assert.equal(yml.humans.humanC.head)
assert.ok(yml.foo.sth.inject === 'everywhere')

var mockError = new Error('oups!')
var err
req.onLoadError = function(e) { err = e }
var yml = req('./configs', function(json) { throw mockError })
assert.ok(err === mockError)
req.onLoadError = function() {}

// async
req('./configs', null, function(yml){
	assert.ok(yml.foo.bar)
})

console.log('test ok.')
<|endoftext|>


<commit_before>'use strict'

const os = require('os')
const assert = require('chai').assert
const uuid = require('uuid/v4')
const index = require('../src/index')

const fsify = require('fsify')({
	cwd: os.tmpdir()
})

describe('index()', function() {

	it('should return an error when called with invalid options', function() {

		return index(null, '').then((data) => {

			throw new Error('Returned without error')

		}, (err) => {

			assert.strictEqual(`'opts' must be an object, null or undefined`, err.message)

		})

	})

	it('should render a page with siteData', function() {

		this.timeout(20000)

		const opts = {
			lang: uuid(),
			title: uuid(),
			description: uuid()
		}

		return index(null, opts).then((data) => {

			assert.include(data, `<html lang="${ opts.lang }">`)
			assert.include(data, `<title>${ opts.title }</title>`)
			assert.include(data, `<meta name="description" content="${ opts.description }">`)

		})

	})

	it('should render a page with components', function() {

		this.timeout(20000)

		const componentName = uuid()

		const structure = [
			{
				type: fsify.DIRECTORY,
				name: uuid(),
				contents: [
					{
						type: fsify.FILE,
						name: `${ componentName }.njk`,
						contents: 'Hello World!'
					},
					{
						type: fsify.FILE,
						name: `${ componentName }.data.json`,
						contents: JSON.stringify({})
					},
					{
						type: fsify.FILE,
						name: `${ componentName }.md`,
						contents: '# Hello World'
					}
				]
			}
		]

		return fsify(structure).then((structure) => {

			const opts = {
				src: structure[0].name
			}

			return index(null, opts)

		}).then((data) => {

			assert.include(data, componentName)

		})

	})

})<commit_msg>Test with no components<commit_after>'use strict'

const os = require('os')
const assert = require('chai').assert
const uuid = require('uuid/v4')
const index = require('../src/index')

const fsify = require('fsify')({
	cwd: os.tmpdir()
})

describe('index()', function() {

	it('should return an error when called with invalid options', function() {

		return index(null, '').then((data) => {

			throw new Error('Returned without error')

		}, (err) => {

			assert.strictEqual(`'opts' must be an object, null or undefined`, err.message)

		})

	})

	it('should render a page with siteData', function() {

		this.timeout(20000)

		const opts = {
			lang: uuid(),
			title: uuid(),
			description: uuid()
		}

		return index(null, opts).then((data) => {

			assert.include(data, `<html lang="${ opts.lang }">`)
			assert.include(data, `<title>${ opts.title }</title>`)
			assert.include(data, `<meta name="description" content="${ opts.description }">`)

		})

	})

	it('should render a page without components', function() {

		this.timeout(20000)

		const structure = [
			{
				type: fsify.DIRECTORY,
				name: uuid(),
				contents: []
			}
		]

		return fsify(structure).then((structure) => {

			const opts = {
				src: structure[0].name
			}

			return index(null, opts)

		}).then((data) => {

			assert.include(data, 'No components found')

		})

	})

	it('should render a page with components', function() {

		this.timeout(20000)

		const componentName = uuid()

		const structure = [
			{
				type: fsify.DIRECTORY,
				name: uuid(),
				contents: [
					{
						type: fsify.FILE,
						name: `${ componentName }.njk`,
						contents: 'Hello World!'
					},
					{
						type: fsify.FILE,
						name: `${ componentName }.data.json`,
						contents: JSON.stringify({})
					},
					{
						type: fsify.FILE,
						name: `${ componentName }.md`,
						contents: '# Hello World'
					}
				]
			}
		]

		return fsify(structure).then((structure) => {

			const opts = {
				src: structure[0].name
			}

			return index(null, opts)

		}).then((data) => {

			assert.include(data, componentName)

		})

	})

})<|endoftext|>