<commit_before>var connect = require('connect');
var req     = require('supertest');
var chai    = require('chai');
var assert  = chai.assert;

var headgear = require('../cov/headgear');

var testResponse = function(request, response, next) {
  response.end('This is a test');
};

var makeServer = function(fn) {
  var app = connect();
  var server = app.listen(3000, function() {
    server.use(testResponse());
    fn(server);
  });
};

suite('Headgear', function() {

  suite('#removePoweredBy', function() {
    test('removes header value', function() {
       makeServer(function(app) {
         app.use(function(request, response, next) {
           response.setHeader('X-Powered-By', 'Headgear-test');
           next();
         });
         app.use(headgear.removePoweredBy());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.isUndefined(response.header['x-powered-by']);
             }
           });
       });
    });

    test('doesn\'t fail when header isn\'t present', function() {
      makeServer(function(app) {
        app.use(headgear.removePoweredBy());
        assert.doesNotThrow(function() {
          req(app)
            .get('/')
            .end(function(error) {
              if(error) {
                throw error;
              }
            });
        });
      });
    });
  });

  suite('#noSniff', function() {
    test('has no sniff header value', function() {
       makeServer(function(app) {
         app.use(headgear.noSniff());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-content-type-options'], 'nosniff');
             }
           });
       });
    });
  });

  suite('#frameOption', function() {
    test('throws for unknown option', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption('fake'));
         assert.throws(function() {
           req(app)
             .get('/')
             .end(function(error) {
               if(error) {
                 throw error;
               }
             });
         });
       });
    });

    test('throws for non-string allowed', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption('allow-from', {}));
         assert.throws(function() {
           req(app)
             .get('/')
             .end(function(error) {
               if(error) {
                 throw error;
               }
             });
         });
       });
    });

    test('uses default value', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-frame-options'], 'sameorigin');
             }
           });
       });
    });

    test('sets given value', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption('deny'));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-frame-options'], 'deny');
             }
           });
       });
    });

    test('sets allowed url', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption('allow-from', 'http://*.fake.com'));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-frame-options'], 'deny');
             }
           });
       });
    });

  });

  suite('#downloadOption', function() {
    test('has no open header', function() {
       makeServer(function(app) {
         app.use(headgear.downloadOption());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-download-options'], 'noopen');
             }
           });
       });
    });
  });

  suite('#transportSecurity', function() {
    test('has sec transport header', function() {
      makeServer(function(app) {
        app.use(headgear.transportSecurity(20000));
        req(app)
          .get('/')
          .end(function(error, response) {
            if(error) {
              console.log(error.stack);
            }
            else {
              assert.strictEqual(response.header['strict-transport-security'], 'max-age=20000');
            }
          });
      });
    });

    test('has sec transport header with subdomains', function() {
      makeServer(function(app) {
        app.use(headgear.transportSecurity(20000, true));
        req(app)
          .get('/')
          .end(function(error, response) {
            if(error) {
              console.log(error.stack);
            }
            else {
              assert.strictEqual(response.header['strict-transport-security'], 'max-age=20000; includeSubDomains;');
            }
          });
      });
    });
  });

  suite('#xssProtect', function() {
    test('has xss protect header', function() {
       makeServer(function(app) {
         app.use(headgear.xssProtect());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-xss-protection'], '1; mode=block;');
             }
           });
       });
    });
  });

  suite('#noCache', function() {
    test('has no cache header', function() {
       makeServer(function(app) {
         app.use(headgear.noCache());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['cache-control'], 'no-cache');
             }
           });
       });
    });
  });

  suite('#contentSecurity', function() {
    test('throw for null options', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity());
         assert.throws(function() {
           req(app)
             .get('/')
             .end(function(error) {
               if(error) {
                 throw error;
               }
             });
         });
       });
    });

    test('throw for non-object options', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity('test'));
         assert.throws(function() {
           req(app)
             .get('/')
             .end(function(error) {
               if(error) {
                 throw error;
               }
             });
         });
       });
    });

    test('has normal header', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity({connectSrc: ['self', 'https:']}));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.isDefined(response.header['content-security-policy']);
             }
           });
       });
    });

     test('has report only header', function() {
        makeServer(function(app) {
          app.use(headgear.contentSecurity({connectSrc: ['self', 'https:'], report: true}));
          req(app)
            .get('/')
            .end(function(error, response) {
              if(error) {
                console.log(error.stack);
              }
              else {
                assert.isDefined(response.header['content-security-policy-report-only']);
              }
            });
        });
     });

    test('has given header value', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity({connectSrc: ['self', 'https:'], report: true}));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['content-security-policy'], 'connect-src \'self\' https:;');
             }
           });
       });
    });

    test('correctly adds quotes to the needed values', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity({connectSrc: ['none', 'self', 'unsafe-inline', 'unsafe-eval'], report: true}));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['content-security-policy'], 'connect-src \'none\' \'self\' \'unsafe-inline\' \'unsafe-eval\'');
             }
           });
       });
    });

    test('correctly adds upgrade-insecure-requests of 1', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity({upgradeInsecureRequests: true}));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['content-security-policy'], 'upgrade-insecure-requests 1');
             }
           });
       });
    });
  });

});
<commit_msg>Removed 'cov' from test include<commit_after>var connect = require('connect');
var req     = require('supertest');
var chai    = require('chai');
var assert  = chai.assert;

var headgear = require('../lib/headgear');

var testResponse = function(request, response, next) {
  response.end('This is a test');
};

var makeServer = function(fn) {
  var app = connect();
  var server = app.listen(3000, function() {
    server.use(testResponse());
    fn(server);
  });
};

suite('Headgear', function() {

  suite('#removePoweredBy', function() {
    test('removes header value', function() {
       makeServer(function(app) {
         app.use(function(request, response, next) {
           response.setHeader('X-Powered-By', 'Headgear-test');
           next();
         });
         app.use(headgear.removePoweredBy());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.isUndefined(response.header['x-powered-by']);
             }
           });
       });
    });

    test('doesn\'t fail when header isn\'t present', function() {
      makeServer(function(app) {
        app.use(headgear.removePoweredBy());
        assert.doesNotThrow(function() {
          req(app)
            .get('/')
            .end(function(error) {
              if(error) {
                throw error;
              }
            });
        });
      });
    });
  });

  suite('#noSniff', function() {
    test('has no sniff header value', function() {
       makeServer(function(app) {
         app.use(headgear.noSniff());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-content-type-options'], 'nosniff');
             }
           });
       });
    });
  });

  suite('#frameOption', function() {
    test('throws for unknown option', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption('fake'));
         assert.throws(function() {
           req(app)
             .get('/')
             .end(function(error) {
               if(error) {
                 throw error;
               }
             });
         });
       });
    });

    test('throws for non-string allowed', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption('allow-from', {}));
         assert.throws(function() {
           req(app)
             .get('/')
             .end(function(error) {
               if(error) {
                 throw error;
               }
             });
         });
       });
    });

    test('uses default value', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-frame-options'], 'sameorigin');
             }
           });
       });
    });

    test('sets given value', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption('deny'));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-frame-options'], 'deny');
             }
           });
       });
    });

    test('sets allowed url', function() {
       makeServer(function(app) {
         app.use(headgear.frameOption('allow-from', 'http://*.fake.com'));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-frame-options'], 'deny');
             }
           });
       });
    });

  });

  suite('#downloadOption', function() {
    test('has no open header', function() {
       makeServer(function(app) {
         app.use(headgear.downloadOption());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-download-options'], 'noopen');
             }
           });
       });
    });
  });

  suite('#transportSecurity', function() {
    test('has sec transport header', function() {
      makeServer(function(app) {
        app.use(headgear.transportSecurity(20000));
        req(app)
          .get('/')
          .end(function(error, response) {
            if(error) {
              console.log(error.stack);
            }
            else {
              assert.strictEqual(response.header['strict-transport-security'], 'max-age=20000');
            }
          });
      });
    });

    test('has sec transport header with subdomains', function() {
      makeServer(function(app) {
        app.use(headgear.transportSecurity(20000, true));
        req(app)
          .get('/')
          .end(function(error, response) {
            if(error) {
              console.log(error.stack);
            }
            else {
              assert.strictEqual(response.header['strict-transport-security'], 'max-age=20000; includeSubDomains;');
            }
          });
      });
    });
  });

  suite('#xssProtect', function() {
    test('has xss protect header', function() {
       makeServer(function(app) {
         app.use(headgear.xssProtect());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['x-xss-protection'], '1; mode=block;');
             }
           });
       });
    });
  });

  suite('#noCache', function() {
    test('has no cache header', function() {
       makeServer(function(app) {
         app.use(headgear.noCache());
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['cache-control'], 'no-cache');
             }
           });
       });
    });
  });

  suite('#contentSecurity', function() {
    test('throw for null options', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity());
         assert.throws(function() {
           req(app)
             .get('/')
             .end(function(error) {
               if(error) {
                 throw error;
               }
             });
         });
       });
    });

    test('throw for non-object options', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity('test'));
         assert.throws(function() {
           req(app)
             .get('/')
             .end(function(error) {
               if(error) {
                 throw error;
               }
             });
         });
       });
    });

    test('has normal header', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity({connectSrc: ['self', 'https:']}));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.isDefined(response.header['content-security-policy']);
             }
           });
       });
    });

     test('has report only header', function() {
        makeServer(function(app) {
          app.use(headgear.contentSecurity({connectSrc: ['self', 'https:'], report: true}));
          req(app)
            .get('/')
            .end(function(error, response) {
              if(error) {
                console.log(error.stack);
              }
              else {
                assert.isDefined(response.header['content-security-policy-report-only']);
              }
            });
        });
     });

    test('has given header value', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity({connectSrc: ['self', 'https:'], report: true}));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['content-security-policy'], 'connect-src \'self\' https:;');
             }
           });
       });
    });

    test('correctly adds quotes to the needed values', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity({connectSrc: ['none', 'self', 'unsafe-inline', 'unsafe-eval'], report: true}));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['content-security-policy'], 'connect-src \'none\' \'self\' \'unsafe-inline\' \'unsafe-eval\'');
             }
           });
       });
    });

    test('correctly adds upgrade-insecure-requests of 1', function() {
       makeServer(function(app) {
         app.use(headgear.contentSecurity({upgradeInsecureRequests: true}));
         req(app)
           .get('/')
           .end(function(error, response) {
             if(error) {
               console.log(error.stack);
             }
             else {
               assert.strictEqual(response.header['content-security-policy'], 'upgrade-insecure-requests 1');
             }
           });
       });
    });
  });

});
<|endoftext|>


<commit_before>
/**Bibliotecas de test******************************************/
var mocha = require('mocha');//Framework Mocha
var chai = require('chai');//Biblioteca para Mocha, llamada Chai
var expect = chai.expect//Estilo de programción expect, dentro de Chai
var request = require('supertest');//Biblioteca para comprobar servidores web

/**Bibliotecas del proyecto*************************************/
var io = require('socket.io/node_modules/socket.io-client');
var express = require('express');
var app = express();

/**Variables auxiliares*****************************************/
var urlServidor = "http://localhost:3001";//URL donde se ejecuta el servidor

var options ={//Opctiones del servidor
  transports: ['websocket'],
  'force new connection': true
};

/**TEST*********************************************************/

/**Arrancamos el servidor**/
beforeEach(function (done) {
    server = require('../app/app.js').server;
    done();
});

/**Pruebas de servidor**/
describe('Pruebas de servidor online', function () {
  /**Comprobando que la web está online**/
  it('Comprobando que la página responde (200)', function (done) {
    request(urlServidor).get('/').expect(200).end(function(err, res){
      if (err) return done(err)
        done();
      });
    });
})

describe('GET /', function(){
  it('Responde con texto plano', function(done){
    request(urlServidor)
    .get('/')
    .set('Accept', 'text/plain')
    .expect('Content-Type', "text/html; charset=utf-8")
    .expect(200, done);
  })
})
<commit_msg>Update test.js<commit_after>
/**Bibliotecas de test******************************************/
var mocha = require('mocha');//Framework Mocha
var chai = require('chai');//Biblioteca para Mocha, llamada Chai
var expect = chai.expect//Estilo de programción expect, dentro de Chai
var request = require('supertest');//Biblioteca para comprobar servidores web

/**Bibliotecas del proyecto*************************************/
var io = require('socket.io/node_modules/socket.io-client');
var express = require('express');
var app = express();

/**Variables auxiliares*****************************************/
var urlServidor = "http://localhost:8080";//URL donde se ejecuta el servidor

var options ={//Opctiones del servidor
  transports: ['websocket'],
  'force new connection': true
};

/**TEST*********************************************************/

/**Arrancamos el servidor**/
beforeEach(function (done) {
    server = require('../app/app.js').server;
    done();
});

/**Pruebas de servidor**/
describe('Pruebas de servidor online', function () {
  /**Comprobando que la web está online**/
  it('Comprobando que la página responde (200)', function (done) {
    request(urlServidor).get('/').expect(200).end(function(err, res){
      if (err) return done(err)
        done();
      });
    });
})

describe('GET /', function(){
  it('Responde con texto plano', function(done){
    request(urlServidor)
    .get('/')
    .set('Accept', 'text/plain')
    .expect('Content-Type', "text/html; charset=utf-8")
    .expect(200, done);
  })
})
<|endoftext|>


<commit_before>var erm = require('../lib/express-restify-mongoose');

var setup = require('./setup');

var assert   = require('assertmessage'),
    express  = require('express'),
    mongoose = require('mongoose'),
    restify  = require('restify'),
    request  = require('request'),
    Schema   = mongoose.Schema;

var util = require('util');

require('sugar');

var testPort = 30023,
    testUrl  = 'http://localhost:' + testPort;

var expressApp = express();
expressApp.use(express.bodyParser());
expressApp.use(express.methodOverride());
expressApp.describe = 'Express';

var restifyApp = restify.createServer();
restifyApp.use(restify.bodyParser());
restifyApp.describe = 'Restify';

[expressApp, restifyApp].each(function (app) {
    describe(app.describe, function () {

        var savedCustomer, server;
        setup();

        before(function (done) {
            erm.serve(app, setup.customerModel);
            server = app.listen(testPort, done);
        });

        after(function (done) {
            mongoose.connection.close(done);
        });
        after(function (done) {
            if (app.close) {
                return app.close(done);
            }
            server.close(done);
        });

        it('200 get Customers', function (done) {
            request.get({
                url: util.format('%s/api/v1/Customers', testUrl)
            }, function (err, res, body) {
                assert.equal(res.statusCode, 200, 'Wrong status code');
                done();
            });
        });

        it('200 get Customers/count', function (done) {
            request.get({
                url: util.format('%s/api/v1/Customers/count', testUrl),
                json: true
            }, function (err, res, body) {
                assert.equal(res.statusCode, 200, 'Wrong status code');
                assert.equal(body.count, 0, 'Wrong count');
                done();
            });
        });

        it('200 post Customers', function (done) {
            request.post({
                url: util.format('%s/api/v1/Customers', testUrl),
                json: {
                    name: 'Test',
                    comment: 'Comment'
                }
            }, function (err, res, body) {
                assert.equal(res.statusCode, 200, 'Wrong status code');
                assert.equal(body.name, 'Test');
                assert.equal(body.comment, 'Comment');
                savedCustomer = body;
                done();
            });
        });

        it('200 GET Customers?name=Test', function (done) {
            request.get({
                url: util.format('%s/api/v1/Customers?name=Test', testUrl),
                json: true
            }, function (err, res, body) {
                assert.equal(res.statusCode, 200, 'Wrong status code');
                assert.equal(body.length, 1,
					'Wrong count of customers returned');
                assert.deepEqual(savedCustomer, body[0]);
                done();
            });
        });

        it('200 GET Customers/:id', function (done) {
            request.get({
                url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                json: true
            }, function (err, res, body) {
                assert.equal(res.statusCode, 200, 'Wrong status code');
                assert.deepEqual(savedCustomer, body);
                done();
            });
        });

        it('200 PUT Customers/:id', function (done) {
            savedCustomer.name = 'Test 2';
            request.put({
                url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                json: savedCustomer
            }, function (err, res, body) {
                assert.equal(res.statusCode, 200, 'Wrong status code');
                assert.deepEqual(savedCustomer, body);
                done();
            });
        });

        it('200 DEL Customers/:id', function (done) {
            request.del({
                url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                json: true
            }, function (err, res) {
                assert.equal(res.statusCode, 200, 'Wrong status code');
                done();
            });
        });

        it('404s on deleted Customers/:id', function (done) {
            request.get({
                url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                json: true
            }, function (err, res, body) {
                assert.equal(res.statusCode, 404, 'Wrong status code');
                done();
            });
        });
    });
});

var expressApp = express();
expressApp.use(express.bodyParser());
expressApp.use(express.methodOverride());
expressApp.describe = 'Express';

var restifyApp = restify.createServer();
restifyApp.use(restify.bodyParser());
restifyApp.describe = 'Restify';

[expressApp, restifyApp].each(function (app) {
    describe(app.describe + ' with excluded comment field', function () {

        var savedCustomer, server;
        setup();

        before(function (done) {
            erm.serve(app, setup.customerModel, {
				exclude: 'comment'
			});
            server = app.listen(testPort, function () {
				request.post({
					url: util.format('%s/api/v1/Customers', testUrl),
					json: {
						name: 'Test',
						comment: 'Comment'
					}
				}, function (err, res, body) {
					savedCustomer = body;

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

        after(function (done) {
            mongoose.connection.close(done);
        });
        after(function (done) {
            if (app.close) {
                return app.close(done);
            }
            server.close(done);
        });

        it('200 get Customers', function (done) {
            request.get({
                url: util.format('%s/api/v1/Customers', testUrl),
                json: true
            }, function (err, res, body) {
                assert.equal(res.statusCode, 200, 'Wrong status code');
				assert.ok(body[0], 'no items found');
				assert.ok(body[0].comment === undefined,
					'comment is not undefined');

                done();
            });
        });

        it('200 GET Customers/:id', function (done) {
            request.get({
                url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                json: true
            }, function (err, res, body) {
                assert.equal(res.statusCode, 200, 'Wrong status code');
				assert.ok(body, 'no item found');
                assert.deepEqual(savedCustomer, body);
				assert.ok(body.comment === undefined,
					'comment is not undefined');
                done();
            });
        });
    });
});

<commit_msg>better test organization<commit_after>var erm = require('../lib/express-restify-mongoose');

var setup = require('./setup');

var assert = require('assertmessage'),
    express = require('express'),
    mongoose = require('mongoose'),
    restify = require('restify'),
    request = require('request'),
    Schema = mongoose.Schema;

var util = require('util');

require('sugar');

var testPort = 30023,
    testUrl = 'http://localhost:' + testPort;

function Express() {
    var app = express();
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    return app;
}
function Restify() {
    var app = restify.createServer();
    app.use(restify.bodyParser());
    return app;
}

[Express, Restify].each(function (createFn) {
    describe(createFn.name, function () {
        describe('General', function () {
            var app = createFn();
            var savedCustomer, server;
            setup();

            before(function (done) {
                erm.serve(app, setup.customerModel);
                server = app.listen(testPort, done);
            });

            after(function (done) {
                mongoose.connection.close(done);
            });
            after(function (done) {
                if (app.close) {
                    return app.close(done);
                }
                server.close(done);
            });

            it('200 get Customers', function (done) {
                request.get({
                    url: util.format('%s/api/v1/Customers', testUrl)
                }, function (err, res, body) {
                    assert.equal(res.statusCode, 200, 'Wrong status code');
                    done();
                });
            });

            it('200 get Customers/count', function (done) {
                request.get({
                    url: util.format('%s/api/v1/Customers/count', testUrl),
                    json: true
                }, function (err, res, body) {
                    assert.equal(res.statusCode, 200, 'Wrong status code');
                    assert.equal(body.count, 0, 'Wrong count');
                    done();
                });
            });

            it('200 post Customers', function (done) {
                request.post({
                    url: util.format('%s/api/v1/Customers', testUrl),
                    json: {
                        name: 'Test',
                        comment: 'Comment'
                    }
                }, function (err, res, body) {
                    assert.equal(res.statusCode, 200, 'Wrong status code');
                    assert.equal(body.name, 'Test');
                    assert.equal(body.comment, 'Comment');
                    savedCustomer = body;
                    done();
                });
            });

            it('200 GET Customers?name=Test', function (done) {
                request.get({
                    url: util.format('%s/api/v1/Customers?name=Test', testUrl),
                    json: true
                }, function (err, res, body) {
                    assert.equal(res.statusCode, 200, 'Wrong status code');
                    assert.equal(body.length, 1,
                        'Wrong count of customers returned');
                    assert.deepEqual(savedCustomer, body[0]);
                    done();
                });
            });

            it('200 GET Customers/:id', function (done) {
                request.get({
                    url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                    json: true
                }, function (err, res, body) {
                    assert.equal(res.statusCode, 200, 'Wrong status code');
                    assert.deepEqual(savedCustomer, body);
                    done();
                });
            });

            it('200 PUT Customers/:id', function (done) {
                savedCustomer.name = 'Test 2';
                request.put({
                    url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                    json: savedCustomer
                }, function (err, res, body) {
                    assert.equal(res.statusCode, 200, 'Wrong status code');
                    assert.deepEqual(savedCustomer, body);
                    done();
                });
            });

            it('200 DEL Customers/:id', function (done) {
                request.del({
                    url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                    json: true
                }, function (err, res) {
                    assert.equal(res.statusCode, 200, 'Wrong status code');
                    done();
                });
            });

            it('404s on deleted Customers/:id', function (done) {
                request.get({
                    url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                    json: true
                }, function (err, res, body) {
                    assert.equal(res.statusCode, 404, 'Wrong status code');
                    done();
                });
            });
        });

        describe('Excluded comment field', function () {
            var app = createFn();
            var savedCustomer, server;
            setup();

            before(function (done) {
                erm.serve(app, setup.customerModel, {
                    exclude: 'comment'
                });
                server = app.listen(testPort, function () {
                    request.post({
                        url: util.format('%s/api/v1/Customers', testUrl),
                        json: {
                            name: 'Test',
                            comment: 'Comment'
                        }
                    }, function (err, res, body) {
                        savedCustomer = body;

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

            after(function (done) {
                mongoose.connection.close(done);
            });
            after(function (done) {
                if (app.close) {
                    return app.close(done);
                }
                server.close(done);
            });

            it('200 get Customers', function (done) {
                request.get({
                    url: util.format('%s/api/v1/Customers', testUrl),
                    json: true
                }, function (err, res, body) {
                    assert.equal(res.statusCode, 200, 'Wrong status code');
                    assert.ok(body[0], 'no items found');
                    assert.ok(body[0].comment === undefined,
                        'comment is not undefined');

                    done();
                });
            });

            it('200 GET Customers/:id', function (done) {
                request.get({
                    url: util.format('%s/api/v1/Customers/%s', testUrl,
                    savedCustomer._id),
                    json: true
                }, function (err, res, body) {
                    assert.equal(res.statusCode, 200, 'Wrong status code');
                    assert.ok(body, 'no item found');
                    assert.deepEqual(savedCustomer, body);
                    assert.ok(body.comment === undefined,
                        'comment is not undefined');
                    done();
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>
export default class GA {

    constructor(trackingCode){
        window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date
        ga('create', trackingCode, 'auto')
    }

    send(location){
        ga('send', {
            hitType: 'pageview',
            page: location.pathname,
            location: window.location.origin + location.pathname + location.search,
            title: document.title
        })
    }
}

<commit_msg>edit ga pageview data<commit_after>
export default class GA {

    constructor(trackingCode){
        window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date
        ga('create', trackingCode, 'auto')
    }

    send(location){
        ga('send', {
            hitType: 'pageview',
            page: location.pathname+location.search,
            location: window.location.origin + location.pathname,
            title: document.title
        })
    }
}

<|endoftext|>


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

var plugin = require('../');

var test = function (input, output, opts, done) {
    postcss([ plugin(opts) ]).process(input).then(function (result) {
        expect(result.css).to.eql(output);
        expect(result.warnings()).to.be.empty;
        done();
    }).catch(function (error) {
        done(error);
    });
};

describe('postcss-position-alt', function () {

    /* Write tests here

    it('does something', function (done) {
        test('a{ }', 'a{ }', { }, done);
    });*/

});
<commit_msg>add test<commit_after>var postcss = require('postcss');
var expect  = require('chai').expect;

var plugin = require('../');

var test = function (input, output, opts, done) {
    postcss([ plugin(opts) ]).process(input).then(function (result) {
        expect(result.css).to.eql(output);
        expect(result.warnings()).to.be.empty;
        done();
    }).catch(function (error) {
        done(error);
    });
};

describe('postcss-position-alt', function () {

    it('test position absolute', function (done) {
      test('a{ absolute: top 10px left 20px right 30px bottom 40px; }',
           'a{ position: absolute; top: 10px; left: 20px; right: 30px; bottom: 40px; }', { }, done);
    });
    it('test position absolute no value', function (done) {
      test('a{ absolute: top left; }',
           'a{ position: absolute; top: 0; left: 0; }', { }, done);
    });

    it('test position fixed', function (done) {
      test('a{ fixed: bottom 10% right 4em; }',
           'a{ position: fixed; bottom: 10%; right: 4em; }', { }, done);
    });

    it('test auto and inherit value', function (done) {
      test('a{ fixed: bottom auto right inherit left; }',
           'a{ position: fixed; bottom: auto; right: inherit; left: 0; }', { }, done);
    });

    it('test relative', function (done) {
      test('a{ relative: top -1px; }',
           'a{ position: relative; top: -1px; }', { }, done);
    });

});
<|endoftext|>


<commit_before>'use strict';

delete require.cache[require.resolve('..')];
var japaneseNumeralsToNumber = require('..');
var assert = require('assert');

describe('japanese-numerals-to-number', function () {
  it('one digit', function () {
    assert(japaneseNumeralsToNumber('一') === 1);
    assert(japaneseNumeralsToNumber('二') === 2);
  });
  it('two digits', function () {
    assert(japaneseNumeralsToNumber('三〇') === 30);
    assert(japaneseNumeralsToNumber('六八') === 68);
  });
});
<commit_msg>refactor: one assertion per test<commit_after>'use strict';

delete require.cache[require.resolve('..')];
var japaneseNumeralsToNumber = require('..');
var assert = require('assert');

function testConv (spec) {
  var input = spec.input;
  var expected = spec.expected;
  it('input: ' + input + ', expected: ' + expected, function () {
    assert(japaneseNumeralsToNumber(input) === expected);
  });
}

describe('japanese-numerals-to-number', function () {
  describe('one digit', function () {
    testConv({ input: '一', expected: 1 });
    testConv({ input: '二', expected: 2 });
  });
  describe('two digits', function () {
    testConv({ input: '三〇', expected: 30 });
    testConv({ input: '六八', expected: 68 });
  });
});
<|endoftext|>


<commit_before>import _ from 'lodash'
import { TwitterClient } from '../../modules/twitter'

const defaultGetParams = {
  include_entities: true,
  tweet_mode: 'extended',
  count: 200
}

const state = {
  me: {},
  lists: [],
  tweetedIdStr: [],
  timeline: [],
  mentions: [],
  favorites: [],
  listsStatuses: []
}

const mutations = {
  ADD_ME (state, me) {
    state.me = me
  },
  ADD_LISTS (state, lists) {
    state.lists = lists
  },
  ADD_TIMELINE (state, tweets) {
    state.timeline = tweets.concat(state.timeline)
  },
  DELETE_TWEET (state, idx) {
    state.timeline.splice(idx, 1)
  },
  ADD_TWEETED_ID_STR (state, idStr) {
    state.tweetedIdStr.push(idStr)
  },
  REMOVE_TWEETS (state) {
    state.tweetedIdStr.forEach((idStr) => {
      state.timeline.splice(state.timeline.findIndex(TwitterClient.findItem, idStr), 1)
    })
    state.tweetedIdStr = []
  },
  ADD_MENTIONS (state, tweets) {
    state.mentions = tweets.concat(state.mentions)
  },
  ADD_FAVORITES (state, tweets) {
    state.favorites = tweets.concat(state.favorites)
  },
  ADD_LISTS_STATUSES (state, tweets) {
    state.listsStatuses = tweets.concat(state.listsStatuses)
  },
  UPDATE_FAVORITED (state, {idx, favorited}) {
    state.timeline[idx].favorited = favorited
  },
  UPDATE_RETWEETED (state, {idx, retweeted}) {
    state.timeline[idx].retweeted = retweeted
  }
}

const actions = {
  fetchAccount ({ commit }) {
    TwitterClient.fetchAccount()
      .then((user) => {
        commit('ADD_ME', user)
      })
  },
  fetchLists ({ commit }) {
    TwitterClient.fetchLists()
      .then((lists) => {
        commit('ADD_LISTS', lists)
      })
  },
  fetchTimeline ({ commit }) {
    commit('REMOVE_TWEETS')
    const params = _.cloneDeep(defaultGetParams)
    if (state.timeline.length > 0) {
      params.since_id = state.timeline[0].id_str
    }
    TwitterClient.fetchTweets('statuses/home_timeline', params)
      .then((tweets) => {
        if (tweets.length > 0) {
          commit('ADD_TIMELINE', tweets)
        }
      })
  },
  addTimeline ({ commit }, tweet) {
    commit('ADD_TIMELINE', [TwitterClient.parseTweet(tweet)])
    commit('ADD_TWEETED_ID_STR', tweet.id_str)
  },
  remoteTweets ({ commit }) {
    commit('REMOVE_TWEETS')
  },
  deleteTweet ({ commit }, idStr) {
    commit('DELETE_TWEET', state.timeline.findIndex(TwitterClient.findItem, idStr))
  },
  fetchMentions ({ commit }) {
    const params = _.cloneDeep(defaultGetParams)
    if (state.mentions.length > 0) {
      params.since_id = state.mentions[0].id_str
    }
    TwitterClient.fetchTweets('statuses/mentions_timeline', params)
      .then((tweets) => {
        if (tweets.length > 0) {
          commit('ADD_MENTIONS', tweets)
        }
      })
  },
  fetchFavorites ({ commit }) {
    const params = _.cloneDeep(defaultGetParams)
    if (state.favorites.length > 0) {
      params.since_id = state.favorites[0].id_str
    }
    TwitterClient.fetchTweets('favorites/list', params)
      .then((tweets) => {
        if (tweets.length > 0) {
          commit('ADD_FAVORITES', tweets)
        }
      })
  },
  updateFavorited ({ commit }, {idStr, favorited}) {
    commit('UPDATE_FAVORITED', {
      idx: state.timeline.findIndex(TwitterClient.findItem, idStr),
      favorited: favorited
    })
  },
  updateRetweeted ({ commit }, {idStr, retweeted}) {
    commit('UPDATE_RETWEETED', {
      idx: state.timeline.findIndex(TwitterClient.findItem, idStr),
      retweeted: retweeted
    })
  }
}

export default {
  state,
  mutations,
  actions
}
<commit_msg>Add actions<commit_after>import _ from 'lodash'
import { TwitterClient } from '../../modules/twitter'

const defaultGetParams = {
  include_entities: true,
  tweet_mode: 'extended',
  count: 200
}

const state = {
  me: {},
  lists: [],
  listId: '',
  tweetedIdStr: [],
  timeline: [],
  mentions: [],
  favorites: [],
  listsStatuses: []
}

const mutations = {
  ADD_ME (state, me) {
    state.me = me
  },
  ADD_LISTS (state, lists) {
    state.lists = lists
  },
  ADD_TIMELINE (state, tweets) {
    state.timeline = tweets.concat(state.timeline)
  },
  DELETE_TWEET (state, idx) {
    state.timeline.splice(idx, 1)
  },
  ADD_TWEETED_ID_STR (state, idStr) {
    state.tweetedIdStr.push(idStr)
  },
  REMOVE_TWEETS (state) {
    state.tweetedIdStr.forEach((idStr) => {
      state.timeline.splice(state.timeline.findIndex(TwitterClient.findItem, idStr), 1)
    })
    state.tweetedIdStr = []
  },
  ADD_MENTIONS (state, tweets) {
    state.mentions = tweets.concat(state.mentions)
  },
  ADD_FAVORITES (state, tweets) {
    state.favorites = tweets.concat(state.favorites)
  },
  ADD_LISTS_STATUSES (state, tweets) {
    state.listsStatuses = tweets.concat(state.listsStatuses)
  },
  UPDATE_FAVORITED (state, {idx, favorited}) {
    state.timeline[idx].favorited = favorited
  },
  UPDATE_RETWEETED (state, {idx, retweeted}) {
    state.timeline[idx].retweeted = retweeted
  }
}

const actions = {
  fetchAccount ({ commit }) {
    TwitterClient.fetchAccount()
      .then((user) => {
        commit('ADD_ME', user)
      })
  },
  fetchLists ({ commit }) {
    TwitterClient.fetchLists()
      .then((lists) => {
        commit('ADD_LISTS', lists)
      })
  },
  fetchTimeline ({ commit }) {
    commit('REMOVE_TWEETS')
    const params = _.cloneDeep(defaultGetParams)
    if (state.timeline.length > 0) {
      params.since_id = state.timeline[0].id_str
    }
    TwitterClient.fetchTweets('statuses/home_timeline', params)
      .then((tweets) => {
        if (tweets.length > 0) {
          commit('ADD_TIMELINE', tweets)
        }
      })
  },
  addTimeline ({ commit }, tweet) {
    commit('ADD_TIMELINE', [TwitterClient.parseTweet(tweet)])
    commit('ADD_TWEETED_ID_STR', tweet.id_str)
  },
  remoteTweets ({ commit }) {
    commit('REMOVE_TWEETS')
  },
  deleteTweet ({ commit }, idStr) {
    commit('DELETE_TWEET', state.timeline.findIndex(TwitterClient.findItem, idStr))
  },
  fetchMentions ({ commit }) {
    const params = _.cloneDeep(defaultGetParams)
    if (state.mentions.length > 0) {
      params.since_id = state.mentions[0].id_str
    }
    TwitterClient.fetchTweets('statuses/mentions_timeline', params)
      .then((tweets) => {
        if (tweets.length > 0) {
          commit('ADD_MENTIONS', tweets)
        }
      })
  },
  fetchFavorites ({ commit }) {
    const params = _.cloneDeep(defaultGetParams)
    if (state.favorites.length > 0) {
      params.since_id = state.favorites[0].id_str
    }
    TwitterClient.fetchTweets('favorites/list', params)
      .then((tweets) => {
        if (tweets.length > 0) {
          commit('ADD_FAVORITES', tweets)
        }
      })
  },
  fetchListsStatuses ({ commit }) {
    const params = _.cloneDeep(defaultGetParams)
    if (state.listsStatuses.length > 0) {
      params.list_id = state.listId
    }
    TwitterClient.fetchTweets('lists/statuses', params)
      .then((tweets) => {
        if (tweets.length > 0) {
          commit('ADD_LISTS_STATUSES', tweets)
        }
      })
  },
  updateFavorited ({ commit }, {idStr, favorited}) {
    commit('UPDATE_FAVORITED', {
      idx: state.timeline.findIndex(TwitterClient.findItem, idStr),
      favorited: favorited
    })
  },
  updateRetweeted ({ commit }, {idStr, retweeted}) {
    commit('UPDATE_RETWEETED', {
      idx: state.timeline.findIndex(TwitterClient.findItem, idStr),
      retweeted: retweeted
    })
  }
}

export default {
  state,
  mutations,
  actions
}
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const exec = require('child_process').exec
const tree = require('strong-npm-ls')
const test = require('tape')
const rimraf = require('rimraf')
const fixtures = fs.readdirSync(path.join(__dirname, 'fixtures'))

test((t) => {
  let count = fixtures.length
  t.plan(count)
  fixtures.forEach(fixture => {
    const modules = path.join(__dirname, 'fixtures', fixture, 'node_modules')
    rimraf(modules, _ => {
      count -= 1
      t.pass()
      if (count === 0) t.end()
    })
  })
})

test((t) => {
  let items = 3
  let count = fixtures.length * items
  t.plan(count)
  fixtures.forEach(fixture => {
    const bin = path.join(__dirname, '..', 'bin', 'dep.js')
    const pkg = path.join(__dirname, 'fixtures', fixture)
    const fix = fs.readFileSync(path.join(pkg, 'tree'), 'utf8')
    exec(`node ${bin} install`, {cwd: pkg}, (err, stdout, stderr) => {
      t.ifError(err)
      tree.read(pkg, (err, out) => {
        count -= items
        const deps = tree.printable(out, Number.MAX_VALUE)
        t.ifError(err)
        t.is(deps, fix)
        if (count === 0) t.end()
      })
    })
  })
})
<commit_msg>fix(test): replace let with var<commit_after>const fs = require('fs')
const path = require('path')
const exec = require('child_process').exec
const tree = require('strong-npm-ls')
const test = require('tape')
const rimraf = require('rimraf')
const fixtures = fs.readdirSync(path.join(__dirname, 'fixtures'))

test((t) => {
  var count = fixtures.length
  t.plan(count)
  fixtures.forEach(fixture => {
    const modules = path.join(__dirname, 'fixtures', fixture, 'node_modules')
    rimraf(modules, _ => {
      count -= 1
      t.pass()
      if (count === 0) t.end()
    })
  })
})

test((t) => {
  var items = 3
  var count = fixtures.length * items
  t.plan(count)
  fixtures.forEach(fixture => {
    const bin = path.join(__dirname, '..', 'bin', 'dep.js')
    const pkg = path.join(__dirname, 'fixtures', fixture)
    const fix = fs.readFileSync(path.join(pkg, 'tree'), 'utf8')
    exec(`node ${bin} install`, {cwd: pkg}, (err, stdout, stderr) => {
      t.ifError(err)
      tree.read(pkg, (err, out) => {
        count -= items
        const deps = tree.printable(out, Number.MAX_VALUE)
        t.ifError(err)
        t.is(deps, fix)
        if (count === 0) t.end()
      })
    })
  })
})
<|endoftext|>


<commit_before>module("Dates");

test("Basic requirements", function() {

    var d = new Date();
    var f = 'MMMM dd, yyyy KK:mm:ss:SSS a';
    var df = $.format.date(d, f);
    equals($.format.date(df, f).getTime(), d.getTime());

    f = 'dd.MM.yyyy';
    df = $.format.date('1.5.2009', f);
    d = new Date(df);
    equals($.format.date(d, f), '01.05.2009');

    $.format.locale({
        date: {
            format: 'EEEE, \'o\'\'clock\' dd\' de \'MMMM\' de \'yyyy H:mm:ss',
            monthsFull: ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'],
            monthsShort: ['ene','feb','mar','abr','may','jun','jul','ago','sep','oct','nov','dic'],
            daysFull: ['domingo','lunes','martes','mi�rcoles','jueves','viernes','s�bado'],
            daysShort: ['dom','lun','mar','mi�','jue','vie','s�b'],
            timeFormat: 'H:mm:ss',
            shortDateFormat: 'dd/MM/yyyy',
            longDateFormat: 'EEEE, dd\' de \'MMMM\' de \'yyyy'
        }
    });

    d = new Date();
    d.setYear(1976);
    d.setMonth(4);
    d.setDate(31);
    d.setHours(3);
    d.setMinutes(20);
    d.setSeconds(43);
    d.setMilliseconds(0);

    equals($.format.date(d), 'lunes, o\'clock 31 de mayo de 1976 3:20:43');

});

module("Number");

test("Basic requirements", function() {

    equals($.format.number(0.123, '#0.0000'), '0.1230');
    equals($.format.number(7456.2, '#,##0.0#'), '7,456.2');
    equals($.format.number(7456.351, '#,##0.#'), '7,456.4');
    equals($.format.number(123.4, '#,##0.00#'), '123.40');
    equals($.format.number(12.32410, '#,##0.0000#'), '12.3241');
    equals($.format.number(0.123213, '#,##0.00###'), '0.12321');
    equals($.format.number(2101.234, '#,###'), '2,101');
    equals($.format.number(101.7, '#,###'), '102');
    equals($.format.number(0.123, '.0000'), '.1230');
    equals($.format.number(5.155, '.0#'), '.16');
    equals($.format.number(540.23, '###'), '540');
    equals($.format.number(540.23, '###.'), '540');
    equals($.format.number(540, '###.##'), '540');
    equals($.format.number(19.03), '19.03');
    equals($.format.number(5.0303, '00.0000'), '05.0303');

    equals($.format.number(23540.23, '#,###.##'), '23,540.23');
    equals($.format.number(23540.23, '#,###'), '23,540');
    equals($.format.number(23540.23, '#####.000'), '23540.230');
    equals($.format.number(3.14, '#00.#'), '03.1');
    equals($.format.number(10.9, '#,##0.0#'), '10.9');

    equals($.format.number(1.02, "#.##"), '1.02');
    equals($.format.number(1.12, "#.##"), '1.12');
    equals($.format.number(1.999, "#.##"), '2');

    equals($.format.number('.1230'), 0.123);
    equals($.format.number('86.02'), 86.02);
    equals($.format.number('03.14'), 3.14);

    $.format.locale({
        number: {
            groupingSeparator: '.',
            decimalSeparator: ','
        }
    });

    equals($.format.number(123.4, '#,##0.000'), '123,400');
    equals($.format.number(12.32410, '#,##0.0000#'), '12,3241');
    equals($.format.number(2123.4, '#,##0.000'), '2.123,400');
    equals($.format.number(1231231212.32410, '#,##0.0000#'), '1.231.231.212,3241');

    equals($.format.number('1.231.231.212,3241'), 1231231212.3241);
    equals($.format.number('18,00.5'), 18.005);

    $.format.locale({
        number: {
            groupingSeparator: '\'',
            decimalSeparator: '.'
        }
    });

    equals($.format.number(123.4, '#,##0.000'), '123.400');
    equals($.format.number(12.32410, '#,##0.0000#'), '12.3241');
    equals($.format.number(2123.4, '#,##0.000'), "2'123.400");
    equals($.format.number(1231231212.32410, '#,##0.0000#'), "1'231'231'212.3241");

    equals($.format.number("1'231'231'212.3241"), 1231231212.3241);
    equals($.format.number("18.00'5"), 18.005);

});<commit_msg>Adds a few more tests.<commit_after>module("Dates");

test("Basic requirements", function() {

    var d = new Date();
    var f = 'MMMM dd, yyyy KK:mm:ss:SSS a';
    var df = $.format.date(d, f);
    equals($.format.date(df, f).getTime(), d.getTime());

    f = 'dd.MM.yyyy';
    df = $.format.date('1.5.2009', f);
    d = new Date(df);
    equals($.format.date(d, f), '01.05.2009');

    $.format.locale({
        date: {
            format: 'EEEE, \'o\'\'clock\' dd\' de \'MMMM\' de \'yyyy H:mm:ss',
            monthsFull: ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'],
            monthsShort: ['ene','feb','mar','abr','may','jun','jul','ago','sep','oct','nov','dic'],
            daysFull: ['domingo','lunes','martes','mi�rcoles','jueves','viernes','s�bado'],
            daysShort: ['dom','lun','mar','mi�','jue','vie','s�b'],
            timeFormat: 'H:mm:ss',
            shortDateFormat: 'dd/MM/yyyy',
            longDateFormat: 'EEEE, dd\' de \'MMMM\' de \'yyyy'
        }
    });

    d = new Date();
    d.setYear(1976);
    d.setMonth(4);
    d.setDate(31);
    d.setHours(3);
    d.setMinutes(20);
    d.setSeconds(43);
    d.setMilliseconds(0);

    equals($.format.date(d), 'lunes, o\'clock 31 de mayo de 1976 3:20:43');

});

module("Number");

test("Basic requirements", function() {

    equals($.format.number(0.123, '#0.0000'), '0.1230');
    equals($.format.number(7456.2, '#,##0.0#'), '7,456.2');
    equals($.format.number(7456.351, '#,##0.#'), '7,456.4');
    equals($.format.number(123.4, '#,##0.00#'), '123.40');
    equals($.format.number(12.32410, '#,##0.0000#'), '12.3241');
    equals($.format.number(0.123213, '#,##0.00###'), '0.12321');
    equals($.format.number(2101.234, '#,###'), '2,101');
    equals($.format.number(101.7, '#,###'), '102');
    equals($.format.number(0.123, '.0000'), '.1230');
    equals($.format.number(5.155, '.0#'), '.16');
    equals($.format.number(540.23, '###'), '540');
    equals($.format.number(540.23, '###.'), '540');
    equals($.format.number(540, '###.##'), '540');
    equals($.format.number(19.03), '19.03');
    equals($.format.number(5.0303, '00.0000'), '05.0303');

    equals($.format.number(23540.23, '#,###.##'), '23,540.23');
    equals($.format.number(23540.23, '#,###'), '23,540');
    equals($.format.number(23540.23, '#####.000'), '23540.230');
    equals($.format.number(3.14, '#00.#'), '03.1');
    equals($.format.number(10.9, '#,##0.0#'), '10.9');

    equals($.format.number(1.02, "#.##"), '1.02');
    equals($.format.number(1.12, "#.##"), '1.12');
    equals($.format.number(1.999, "#.##"), '2');

    equals($.format.number('.1230'), 0.123);
    equals($.format.number('86.02'), 86.02);
    equals($.format.number('03.14'), 3.14);

    $.format.locale({
        number: {
            groupingSeparator: '.',
            decimalSeparator: ','
        }
    });

    equals($.format.number(123.4, '#,##0.000'), '123,400');
    equals($.format.number(12.32410, '#,##0.0000#'), '12,3241');
    equals($.format.number(2123.4, '#,##0.000'), '2.123,400');
    equals($.format.number(1231231212.32410, '#,##0.0000#'), '1.231.231.212,3241');
    equals($.format.number(999, "#,###"), '999');
    equals($.format.number(-999, "#,###"), '-999');

    equals($.format.number('1.231.231.212,3241'), 1231231212.3241);
    equals($.format.number('18,00.5'), 18.005);

    $.format.locale({
        number: {
            groupingSeparator: '\'',
            decimalSeparator: '.'
        }
    });

    equals($.format.number(123.4, '#,##0.000'), '123.400');
    equals($.format.number(12.32410, '#,##0.0000#'), '12.3241');
    equals($.format.number(2123.4, '#,##0.000'), "2'123.400");
    equals($.format.number(1231231212.32410, '#,##0.0000#'), "1'231'231'212.3241");

    equals($.format.number("1'231'231'212.3241"), 1231231212.3241);
    equals($.format.number("18.00'5"), 18.005);

});<|endoftext|>


<commit_before>var test = require('tape')

var levi = require('../')
var similarity = require('../lib/util/similarity')
var H = require('highland')

var lv
test('clean up', function (t) {
  levi.destroy('./test/db', function (err) {
    t.notOk(err, 'destroy')

    lv = levi('./test/db')
    .use(levi.tokenizer())
    .use(levi.stemmer())
    .use(levi.stopword())

    t.end()
  })
})

test('pipeline', function (t) {
  t.plan(8)

  lv.pipeline('including a foo !a!b!c! of instanceof constructor.', function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      'includ', 'foo', 'abc', 'instanceof', 'constructor'
    ], 'stemmer, stopwords, js reserved words')
    lv.pipeline(tokens, function (err, tokens2) {
      t.notOk(err)
      t.deepEqual(tokens, tokens2, 'idempotent')
    })
  })

  lv.pipeline({
    a: 'foo bar',
    c: ['hello'],
    d: { asdf: { ghjk: 'world' } },
    e: 167,
    f: null
  }, function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      'foo', 'bar', 'hello', 'world'
    ], 'text extraction from object')
  })

  var cyclic = { a: 'foo', b: { asdf: 'bar' } }
  cyclic.b.boom = cyclic
  lv.pipeline(cyclic, function (err) {
    t.equal(err.message, 'Cycle detected')
  })

  lv.put('boom', cyclic, function (err) {
    t.equal(err.message, 'Cycle detected')
  })
})

test('similarity', function (t) {
  t.equal(Math.round(similarity(
    {x: 1, y: 3, z: -5, foo: 0},
    {x: 4, y: -2, z: -1}
  ) * 1000) / 1000, 0.111, 'cosine similarity')

  t.equal(similarity(
    {x: 1, y: 3, z: -5},
    {x: 0, y: 0, z: 0}
  ), 0, 'zero magitude vector')

  t.end()
})

test('CRUD', function (t) {
  var aObj = {
    a: 'hello world'
  }

  H('put', lv).pluck('key').take(10).toArray(function (keys) {
    t.deepEqual(keys, [
      'a', 'b',
      'ar', 'c',
      'ar', 'c',
      'ar', 'c',
      'd', 'd'
    ], 'put emitter')
    // must not include error operations
  })

  H('del', lv).pluck('key').take(4).toArray(function (keys) {
    t.deepEqual(keys, [
      'ar', 'c', 'c', 'd'
    ], 'del emitter')
    // must not include error operations
  })

  lv.put('a', aObj, function () {
    lv.get('a', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, aObj, 'put object')
    })
  })

  var bText = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
  lv.put('b', new Buffer(bText), function () {
    lv.get('b', function (err, value) {
      t.notOk(err)
      t.equal(value, bText, 'put buffer')
      t.equal(typeof value, 'string', 'buffer converted to string')
    })
  })

  var ar = ['hello', 'printing', 'a']
  var cText = 'Aldus PageMaker including versions of Lorem Ipsum.'

  lv.batch([
    {type: 'put', key: 'ar', value: ar},
    {type: 'put', key: 'c', value: cText},
    {type: 'del', key: 'ar'},
    {type: 'del', key: 'c'},
    {type: 'put', key: 'ar', value: ar}, // repeated put
    {type: 'put', key: 'c', value: cText},
    {type: 'put', key: 'ar', value: ar},
    {type: 'put', key: 'c', value: cText}
  ], function (err) {
    t.notOk(err, 'batch put')
    lv.get('ar', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, ar, 'put array')
    })
    lv.get('c', function (err, value) {
      t.notOk(err)
      t.equal(value, cText, 'put string')
    })
  })

  for (var i = 0; i < 10; i++) {
    lv.batch([
      {type: 'put', key: 'on99' + i, value: 'on99'},
      {type: 'put', key: 'abc'}, // error
      {type: 'del', key: '168'}
    ], function (err) {
      t.ok(err)
      lv.get('on99' + i, function (err, val) {
        t.notOk(val, 'err not comitted')
        t.ok(err.notFound, 'err not comitted')
      })
    })
  }

  lv.put('d', 'Rick rolling', function (err) {
    t.notOk(err)
    lv.searchStream('rolling and hatin').toArray(function (arr) {
      t.equal(arr.length, 1, 'correct put')
      t.equal(arr[0].key, 'd', 'correct put')
      t.equal(arr[0].value, 'Rick rolling', 'correct put')
      lv.put('d', 'Rick Ashley', function (err) {
        t.notOk(err)
        lv.searchStream('rolling').toArray(function (arr) {
          t.equal(arr.length, 0, 'correct clean up')
          lv.searchStream('ashley').toArray(function (arr) {
            t.equal(arr.length, 1, 'correct upsert')
            t.equal(arr[0].key, 'd', 'correct upsert')
            t.equal(arr[0].value, 'Rick Ashley', 'correct upsert')

            t.end()
          })
        })
      })
    })
  })
})

test('size and tear down', function (t) {
  lv.meta.get('size', function (err, size) {
    t.notOk(err)
    t.equal(size, 5, 'size correct')

    lv.del('c')
    lv.del('d')
    lv.batch([
      {type: 'del', key: 'a'},
      {type: 'del', key: 'ar'},
      {type: 'del', key: 'b'},
      {type: 'del', key: 'a'},
      {type: 'del', key: 'ar'},
      {type: 'del', key: 'b'},
      {type: 'del', key: 'a'}, // repeated delete
      {type: 'del', key: 'ar'},
      {type: 'del', key: 'b'}
    ], function (err) {
      t.notOk(err)
      lv.meta.get('size', function (err, size) {
        t.notOk(err && !err.notFound)
        t.notOk(size, 'empty after delete all')
        t.end()
      })
    })
  })
})

test('Search options', function (t) {
  t.plan(29)

  var live = lv.liveStream('green plant')
  var liveM = lv.liveStream('green plant asdf')
  var liveGt = lv.liveStream('green plant', { gt: 'b' })
  var live2 = lv.searchStream('watering plant', { fields: { title: 1, body: 10 } })
  var live2Lt = lv.liveStream('watering plant', { fields: { title: 1, body: 10 }, lt: 'c' })
  var live3 = lv.searchStream({
    title: 'Professor Plumb loves plant',
    message: 'He has a green plant in his study'
  })

  var list = [{
    id: 'a',
    title: 'Mr. Green kills Colonel Mustard',
    body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. ' +
      'Mr. Green is not a very nice fellow.'
  }, {
    id: 'b',
    title: 'Plumb waters plant',
    body: 'Professor Plumb has a green plant in his study'
  }, {
    id: 'c',
    title: 'Scarlett helps Professor',
    body: 'Miss Scarlett watered Professor Plumbs green plant while he was away ' +
      'from his office last week.'
  }, {
    id: 'd',
    title: 'foo',
    body: 'bar'
  }]

  lv.batch(list.map(function (doc) {
    return {type: 'put', key: doc.id, value: doc}
  }), function () {
    lv.readStream({gt: 'a'}).pluck('value').toArray(function (arr) {
      t.deepEqual(arr, list.slice(1), 'readStream')
    })

    lv.searchStream('green plant').toArray(function (arr) {
      t.equal(arr.length, 3, 'search: correct number of results')
      t.equal(arr[0].key, 'b', 'search: correct score')

      lv.searchStream(['green', 'plant']).toArray(function (arr2) {
        t.deepEqual(arr2, arr, 'tokenized query')
      })

      lv.searchStream('green plant', { values: false }).toArray(function (arr) {
        t.notOk(arr[0].value, 'values: false')
      })

      lv.searchStream('green plant', { offset: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(1), 'query offset')
      })

      lv.searchStream('green plant', { limit: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(0, 1), 'limit')
      })

      live.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })

    liveM.pluck('key').take(3).toArray(function (arr) {
      t.deepEqual(arr, ['a', 'b', 'c'], 'liveStream with missing idf')
    })

    lv.scoreStream('green plant').pluck('key').toArray(function (arr) {
      t.deepEqual(arr, ['a', 'b', 'c'], 'scoreStream')
    })

    lv.searchStream('green plant', { gt: 'b' }).toArray(function (arr) {
      t.equal(arr.length, 1, 'gt correct # of result')
      t.equal(arr[0].key, 'c', 'gt correct first result')
      liveGt.take(1).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[0].score, 'live: last score identical to search gt score')
      })
    })

    lv.searchStream('green', { fields: { title: true } }).toArray(function (arr) {
      t.equal(arr.length, 1, 'fielded: correct number of results')
      t.equal(arr[0].key, 'a', 'fielded: correct result')
    })

    lv.searchStream('watering plant', { fields: { title: 1, body: 10 } }).toArray(function (arr) {
      t.equal(arr.length, 2, 'field boosting: correct number of results')
      t.equal(arr[0].key, 'c', 'field boosting: correct boosted result')

      live2.take(2).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[1].score,
          'live: last score identical to search score')
      })
    })

    lv.searchStream('watering plant', { fields: { title: 1, body: 10 }, lt: 'c' }).toArray(function (arr) {
      t.equal(arr.length, 1, 'upper bound: correct number of results')
      t.equal(arr[0].key, 'b', 'upper bound: correct boosted result')

      live2Lt.take(1).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[0].score,
          'upper bound: last score identical to search score')
      })
    })

    lv.searchStream({
      title: 'Professor Plumb loves plant',
      message: 'He has a green plant in his study'
    }).toArray(function (arr) {
      t.equal(arr.length, 3, 'object search: correct number of results')
      H(arr).pluck('key').toArray(function (arr) {
        t.deepEqual(arr, ['b', 'c', 'a'], 'object search: correct order')
      })
      live3.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })
  })
})
<commit_msg>batch error test clean up<commit_after>var test = require('tape')

var levi = require('../')
var similarity = require('../lib/util/similarity')
var H = require('highland')

var lv
test('clean up', function (t) {
  levi.destroy('./test/db', function (err) {
    t.notOk(err, 'destroy')

    lv = levi('./test/db')
    .use(levi.tokenizer())
    .use(levi.stemmer())
    .use(levi.stopword())

    t.end()
  })
})

test('pipeline', function (t) {
  t.plan(8)

  lv.pipeline('including a foo !a!b!c! of instanceof constructor.', function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      'includ', 'foo', 'abc', 'instanceof', 'constructor'
    ], 'stemmer, stopwords, js reserved words')
    lv.pipeline(tokens, function (err, tokens2) {
      t.notOk(err)
      t.deepEqual(tokens, tokens2, 'idempotent')
    })
  })

  lv.pipeline({
    a: 'foo bar',
    c: ['hello'],
    d: { asdf: { ghjk: 'world' } },
    e: 167,
    f: null
  }, function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      'foo', 'bar', 'hello', 'world'
    ], 'text extraction from object')
  })

  var cyclic = { a: 'foo', b: { asdf: 'bar' } }
  cyclic.b.boom = cyclic
  lv.pipeline(cyclic, function (err) {
    t.equal(err.message, 'Cycle detected')
  })

  lv.put('boom', cyclic, function (err) {
    t.equal(err.message, 'Cycle detected')
  })
})

test('similarity', function (t) {
  t.equal(Math.round(similarity(
    {x: 1, y: 3, z: -5, foo: 0},
    {x: 4, y: -2, z: -1}
  ) * 1000) / 1000, 0.111, 'cosine similarity')

  t.equal(similarity(
    {x: 1, y: 3, z: -5},
    {x: 0, y: 0, z: 0}
  ), 0, 'zero magitude vector')

  t.end()
})

test('CRUD', function (t) {
  var aObj = {
    a: 'hello world'
  }

  H('put', lv).pluck('key').take(10).toArray(function (keys) {
    t.deepEqual(keys, [
      'a', 'b',
      'ar', 'c',
      'ar', 'c',
      'ar', 'c',
      'd', 'd'
    ], 'put emitter')
    // must not include error operations
  })

  H('del', lv).pluck('key').take(4).toArray(function (keys) {
    t.deepEqual(keys, [
      'ar', 'c', 'c', 'd'
    ], 'del emitter')
    // must not include error operations
  })

  lv.put('a', aObj, function () {
    lv.get('a', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, aObj, 'put object')
    })
  })

  var bText = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
  lv.put('b', new Buffer(bText), function () {
    lv.get('b', function (err, value) {
      t.notOk(err)
      t.equal(value, bText, 'put buffer')
      t.equal(typeof value, 'string', 'buffer converted to string')
    })
  })

  for (var i = 0; i < 10; i++) {
    lv.batch([
      {type: 'put', key: 'on99' + i, value: 'on99'},
      {type: 'put', key: 'abc'}, // error
      {type: 'del', key: '167'}
    ], function (err) {
      t.ok(err, 'batch error')
    })
  }

  var ar = ['hello', 'printing', 'a']
  var cText = 'Aldus PageMaker including versions of Lorem Ipsum.'

  lv.batch([
    {type: 'put', key: 'ar', value: ar},
    {type: 'put', key: 'c', value: cText},
    {type: 'del', key: 'ar'},
    {type: 'del', key: 'c'},
    {type: 'put', key: 'ar', value: ar}, // repeated put
    {type: 'put', key: 'c', value: cText},
    {type: 'put', key: 'ar', value: ar},
    {type: 'put', key: 'c', value: cText}
  ], function (err) {
    t.notOk(err, 'batch put')
    lv.get('ar', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, ar, 'put array')
    })
    lv.get('c', function (err, value) {
      t.notOk(err)
      t.equal(value, cText, 'put string')
    })
  })

  lv.put('d', 'Rick rolling', function (err) {
    t.notOk(err)
    lv.searchStream('rolling and hatin').toArray(function (arr) {
      t.equal(arr.length, 1, 'correct put')
      t.equal(arr[0].key, 'd', 'correct put')
      t.equal(arr[0].value, 'Rick rolling', 'correct put')
      lv.put('d', 'Rick Ashley', function (err) {
        t.notOk(err)
        lv.searchStream('rolling').toArray(function (arr) {
          t.equal(arr.length, 0, 'correct clean up')
          lv.searchStream('ashley').toArray(function (arr) {
            t.equal(arr.length, 1, 'correct upsert')
            t.equal(arr[0].key, 'd', 'correct upsert')
            t.equal(arr[0].value, 'Rick Ashley', 'correct upsert')

            t.end()
          })
        })
      })
    })
  })
})

test('size and tear down', function (t) {
  lv.meta.get('size', function (err, size) {
    t.notOk(err)
    t.equal(size, 5, 'size correct')

    lv.del('c')
    lv.del('d')
    lv.batch([
      {type: 'del', key: 'a'},
      {type: 'del', key: 'ar'},
      {type: 'del', key: 'b'},
      {type: 'del', key: 'a'},
      {type: 'del', key: 'ar'},
      {type: 'del', key: 'b'},
      {type: 'del', key: 'a'}, // repeated delete
      {type: 'del', key: 'ar'},
      {type: 'del', key: 'b'}
    ], function (err) {
      t.notOk(err)
      lv.meta.get('size', function (err, size) {
        t.notOk(err && !err.notFound)
        t.notOk(size, 'empty after delete all')
        t.end()
      })
    })
  })
})

test('Search options', function (t) {
  t.plan(29)

  var live = lv.liveStream('green plant')
  var liveM = lv.liveStream('green plant asdf')
  var liveGt = lv.liveStream('green plant', { gt: 'b' })
  var live2 = lv.searchStream('watering plant', { fields: { title: 1, body: 10 } })
  var live2Lt = lv.liveStream('watering plant', { fields: { title: 1, body: 10 }, lt: 'c' })
  var live3 = lv.searchStream({
    title: 'Professor Plumb loves plant',
    message: 'He has a green plant in his study'
  })

  var list = [{
    id: 'a',
    title: 'Mr. Green kills Colonel Mustard',
    body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. ' +
      'Mr. Green is not a very nice fellow.'
  }, {
    id: 'b',
    title: 'Plumb waters plant',
    body: 'Professor Plumb has a green plant in his study'
  }, {
    id: 'c',
    title: 'Scarlett helps Professor',
    body: 'Miss Scarlett watered Professor Plumbs green plant while he was away ' +
      'from his office last week.'
  }, {
    id: 'd',
    title: 'foo',
    body: 'bar'
  }]

  lv.batch(list.map(function (doc) {
    return {type: 'put', key: doc.id, value: doc}
  }), function () {
    lv.readStream({gt: 'a'}).pluck('value').toArray(function (arr) {
      t.deepEqual(arr, list.slice(1), 'readStream')
    })

    lv.searchStream('green plant').toArray(function (arr) {
      t.equal(arr.length, 3, 'search: correct number of results')
      t.equal(arr[0].key, 'b', 'search: correct score')

      lv.searchStream(['green', 'plant']).toArray(function (arr2) {
        t.deepEqual(arr2, arr, 'tokenized query')
      })

      lv.searchStream('green plant', { values: false }).toArray(function (arr) {
        t.notOk(arr[0].value, 'values: false')
      })

      lv.searchStream('green plant', { offset: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(1), 'query offset')
      })

      lv.searchStream('green plant', { limit: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(0, 1), 'limit')
      })

      live.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })

    liveM.pluck('key').take(3).toArray(function (arr) {
      t.deepEqual(arr, ['a', 'b', 'c'], 'liveStream with missing idf')
    })

    lv.scoreStream('green plant').pluck('key').toArray(function (arr) {
      t.deepEqual(arr, ['a', 'b', 'c'], 'scoreStream')
    })

    lv.searchStream('green plant', { gt: 'b' }).toArray(function (arr) {
      t.equal(arr.length, 1, 'gt correct # of result')
      t.equal(arr[0].key, 'c', 'gt correct first result')
      liveGt.take(1).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[0].score, 'live: last score identical to search gt score')
      })
    })

    lv.searchStream('green', { fields: { title: true } }).toArray(function (arr) {
      t.equal(arr.length, 1, 'fielded: correct number of results')
      t.equal(arr[0].key, 'a', 'fielded: correct result')
    })

    lv.searchStream('watering plant', { fields: { title: 1, body: 10 } }).toArray(function (arr) {
      t.equal(arr.length, 2, 'field boosting: correct number of results')
      t.equal(arr[0].key, 'c', 'field boosting: correct boosted result')

      live2.take(2).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[1].score,
          'live: last score identical to search score')
      })
    })

    lv.searchStream('watering plant', { fields: { title: 1, body: 10 }, lt: 'c' }).toArray(function (arr) {
      t.equal(arr.length, 1, 'upper bound: correct number of results')
      t.equal(arr[0].key, 'b', 'upper bound: correct boosted result')

      live2Lt.take(1).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[0].score,
          'upper bound: last score identical to search score')
      })
    })

    lv.searchStream({
      title: 'Professor Plumb loves plant',
      message: 'He has a green plant in his study'
    }).toArray(function (arr) {
      t.equal(arr.length, 3, 'object search: correct number of results')
      H(arr).pluck('key').toArray(function (arr) {
        t.deepEqual(arr, ['b', 'c', 'a'], 'object search: correct order')
      })
      live3.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert'),
    AV = require('../api-validator.js'),
    SV = AV.singleValidator;

describe('singleValidator', function () {
    it('should be passed', function (done) {
        assert.equal(null, SV({
            data: {abc: 'dev'},
            schema: {
                '$schema': 'http://json-schema.org/draft-04/schema#',
                'type': 'object',
                required: ['abc'],
                properties: {
                    abc: {
                        type: 'string'
                    }
                }
            }
        }));
        done();
    });
});
<commit_msg>add error case<commit_after>'use strict';

var assert = require('assert'),
    AV = require('../api-validator.js'),
    SV = AV.singleValidator;

describe('singleValidator', function () {
    it('should be failed as internal error', function (done) {
        assert.deepEqual({"error":[{"type":"internal","message":"No input for singleValidator"}]}, SV());
        done();
    });

    it('should be passed', function (done) {
        assert.equal(null, SV({
            data: {abc: 'dev'},
            schema: {
                '$schema': 'http://json-schema.org/draft-04/schema#',
                'type': 'object',
                required: ['abc'],
                properties: {
                    abc: {
                        type: 'string'
                    }
                }
            }
        }));
        done();
    });
});
<|endoftext|>


<commit_before>'use strict';

var pluginPath = '../index';
var axeCore = require(pluginPath);
var gulp = require('gulp');
var path = require('path');
var should = require('should');
var assert = require('assert');
var sassert = require('stream-assert');
require('mocha');

var fixtures = function(glob) { return path.join(__dirname, './fixtures', glob); }

describe('gulp-axe-core', function() {

	it('should pass the a11y validation', function (done) {
			gulp.src(fixtures('working.html'))
				.pipe(axeCore())
				.pipe(sassert.end(done));
	});

	it('should not pass the a11y validation', function (done) {
			gulp.src(fixtures('broken.html'))
				.pipe(axeCore())
				.pipe(sassert.end(done));
	});

	it('should create JSON file with the results', function (done) {
		var options = {
			saveOutputIn: 'allHtml.json'
		};
		gulp.src(fixtures('broken.html'))
				.pipe(axeCore(options))
				.pipe(sassert.end(function() {
					var expected = fs.readFileSync(path.join(__dirname,'allHtml.json')).toString();
					expected.should.not.be('');
					done();
				}));
	});

});<commit_msg>fix(test.js): add timeout due the async<commit_after>'use strict';

var pluginPath = '../index';
var axeCore = require(pluginPath);
var gulp = require('gulp');
var path = require('path');
var should = require('should');
var assert = require('assert');
var sassert = require('stream-assert');
require('mocha');

var fixtures = function(glob) { return path.join(__dirname, './fixtures', glob); }

describe('gulp-axe-core', function() {

	this.timeout(5000);

	it('should pass the a11y validation', function (done) {
			gulp.src(fixtures('working.html'))
				.pipe(axeCore())
				.pipe(sassert.end(done));
	});

	it('should not pass the a11y validation', function (done) {
			gulp.src(fixtures('broken.html'))
				.pipe(axeCore())
				.pipe(sassert.end(done));
	});

	it('should create JSON file with the results', function (done) {
		var options = {
			saveOutputIn: 'allHtml.json'
		};
		gulp.src(fixtures('broken.html'))
				.pipe(axeCore(options))
				.pipe(sassert.end(function() {
					var expected = fs.readFileSync(path.join(__dirname,'allHtml.json')).toString();
					expected.should.not.be('');
					done();
				}));
	});

});<|endoftext|>


<commit_before>var assert = require('assert');
var pseudoElements = require('..');

describe('pseudo-elements', function() {

  it('should do something awesome', function() {
    assert.equal(pseudoElements(), true);
  });
});
<commit_msg>Add test<commit_after>var assert = require('assert');
var pseudoElements = require('..');

var elements = ['after', 'before', 'first-letter', 'first-line', 'selection'];

describe('pseudo-elements', function() {

  it('should do return a list of pseudo-elements', function() {
    assert.deepEqual(pseudoElements(), elements);
  });
});
<|endoftext|>