<commit_before>var CachedRequest = require("../")
,   request = require("request")
,   nock = require("nock")
,   temp = require('temp').track()
,   Readable = require("stream").Readable
,   util = require("util")
,   zlib = require("zlib");

util.inherits(MockedResponseStream, Readable);

function MockedResponseStream (options, response) {
  Readable.call(this, options);
  this.response = response;
}

MockedResponseStream.prototype._read = function (size) {
  this.push(this.response);
  this.push(null);
};

describe("CachedRequest", function () {
  var cacheDir;

  function mock (method, times, response, headers) {
    method = method.toLowerCase();
    times = times || 1;
    nock("http://ping.com")
      .filteringPath(/.+/, "/")
      [method]("/")
      .times(times)
      .reply(200, response, headers);
  };

  before(function () {
    nock.disableNetConnect();
  });

  beforeEach(function () {
    cacheDir = temp.mkdirSync("cache");
    this.cachedRequest = CachedRequest(request);
    this.cachedRequest.setCacheDirectory(cacheDir);
  });

  describe("caching", function () {
    it("makes the request when the response isn't cached", function (done) {
      mock("GET", 1, function () {
        return new MockedResponseStream({}, "pong");
      });
      this.cachedRequest({uri: "http://ping.com/", ttl: 0}, function (error, response, body) {
        if (error) return done(error);
        expect(response.statusCode).to.equal(200);
        expect(response.headers["x-from-cache"]).to.not.exist;
        expect(body).to.equal("pong");
        done();
      });
    });

    it("responds from the cache", function (done) {
      var self = this;
      var responseBody = {"a": 1, "b": {"c": 2}};
      var options = {
        uri: "http://ping.com/",
        method: "POST",
        json: {
          a: 1
        },
        ttl: 5000
      };

      mock(options.method, 1, function () {
        return new MockedResponseStream({}, JSON.stringify(responseBody));
      });

      this.cachedRequest(options, function (error, response, body) {
        if (error) return done(error);
        expect(response.statusCode).to.equal(200);
        expect(response.headers["x-from-cache"]).to.not.exist;
        expect(body).to.deep.equal(responseBody);

        self.cachedRequest(options, function (error, response, body) {
          if (error) return done(error);
          expect(response.statusCode).to.equal(200);
          expect(response.headers["x-from-cache"]).to.equal(1);
          expect(body).to.deep.equal(responseBody);
          done();
        });
      });
    });

    it("responds the same from the cache if gzipped", function (done) {
      var self = this;
      var responseBody = 'foo';
      var options = {
        url: "http://ping.com/",
        ttl: 5000,
        encoding: null // avoids messing with gzip responses so we can handle them
      };

      //Return gzip compressed response with valid content encoding header
      mock("GET", 1, function () {
        return new MockedResponseStream({}, responseBody).pipe(zlib.createGzip());
      },
      {
        "Content-Encoding": "gzip"
      });

      this.cachedRequest(options, function (error, response, body) {
        if (error) return done(error);
        expect(response.statusCode).to.equal(200);
        expect(response.headers["x-from-cache"]).to.not.exist;

        zlib.gunzip(body, function (error, buffer) {
          if (error) return done(error);
          expect(buffer.toString()).to.deep.equal(responseBody);

          self.cachedRequest(options, function (error, response, body) {
            if (error) return done(error);
            expect(response.statusCode).to.equal(200);
            expect(response.headers["x-from-cache"]).to.equal(1);
            zlib.gunzip(body, function (error, buffer) {
              if (error) done(error);
              expect(buffer.toString()).to.deep.equal(responseBody);
              done();
            });
          });
        });
      });
    });
  });

  describe("streaming", function () {
    it("allows to use request as a stream", function (done) {
      var self = this;
      var responseBody = "";

      for (var i = 0; i < 1000; i++) {
        responseBody += "this is a long response body";
      };

      mock("GET", 1, function () {
        return new MockedResponseStream({}, responseBody);
      });

      var options = {url: "http://ping.com/", ttl: 5000};
      var body = "";

      //Make fresh request
      this.cachedRequest(options)
      .on("data", function (data) {
          body += data;
      })
      .on("end", function () {
        expect(body).to.equal(responseBody);
        body = "";
        //Make cached request
        self.cachedRequest(options)
        .on("response", function (response) {
          expect(response.statusCode).to.equal(200);
          expect(response.headers["x-from-cache"]).to.equal(1);
          response.on("data", function (data) {
            body += data;
          })
          .on("end", function () {
            expect(body).to.equal(responseBody);
            done();
          });
        });
      });
    });

    it("handles gzip response", function (done) {

      var self = this;
      var responseBody = "";

      for (var i = 0; i < 1000; i++) {
        responseBody += "this is a long response body";
      };

      //Return gzip compressed response with valid content encoding header
      mock("GET", 1, function () {
        return new MockedResponseStream({}, responseBody).pipe(zlib.createGzip());
      },
      {
        "Content-Encoding": "gzip"
      });

      var options = {url: "http://ping.com/", ttl: 5000};
      var body = "";

      //Make fresh request
      this.cachedRequest(options)
        .on("data", function (data) {
          //Ignore first reply
        })
        .on("end", function () {
          body = "";
          //Make cached request
          self.cachedRequest(options)
            .on("response", function (response) {
              expect(response.statusCode).to.equal(200);
              expect(response.headers["x-from-cache"]).to.equal(1);
              expect(response.headers["content-encoding"]).to.equal("gzip");

              var gunzip = zlib.createGunzip();
              gunzip.on("data", function (data) {
                body += data.toString();
              });

              gunzip.on("end", function () {
                expect(body).to.equal(responseBody);
                done();
              });

              gunzip.on('error', function (error) {
                done(error);
              });

              response.pipe(gunzip);
            });

        });
    });
  });

  after(function () {
    temp.cleanupSync();
  });
});<commit_msg>testing config<commit_after>var CachedRequest = require("../")
,   request = require("request")
,   nock = require("nock")
,   temp = require('temp').track()
,   Readable = require("stream").Readable
,   util = require("util")
,   zlib = require("zlib");

util.inherits(MockedResponseStream, Readable);

function MockedResponseStream (options, response) {
  Readable.call(this, options);
  this.response = response;
}

MockedResponseStream.prototype._read = function (size) {
  this.push(this.response);
  this.push(null);
};

describe("CachedRequest", function () {
  var cacheDir;

  function mock (method, times, response, headers) {
    method = method.toLowerCase();
    times = times || 1;
    nock("http://ping.com")
      .filteringPath(/.+/, "/")
      [method]("/")
      .times(times)
      .reply(200, response, headers);
  };

  before(function () {
    nock.disableNetConnect();
  });

  beforeEach(function () {
    cacheDir = temp.mkdirSync("cache");
    this.cachedRequest = CachedRequest(request);
    this.cachedRequest.setCacheDirectory(cacheDir);
  });

  describe("caching", function () {
    it("makes the request when the response isn't cached", function (done) {
      mock("GET", 1, function () {
        return new MockedResponseStream({}, "pong");
      });
      this.cachedRequest({uri: "http://ping.com/", ttl: 0}, function (error, response, body) {
        if (error) return done(error);
        expect(response.statusCode).to.equal(200);
        expect(response.headers["x-from-cache"]).to.not.exist;
        expect(body).to.equal("pong");
        done();
      });
    });

    it("responds from the cache", function (done) {
      var self = this;
      var responseBody = {"a": 1, "b": {"c": 2}};
      var options = {
        uri: "http://ping.com/",
        method: "POST",
        json: {
          a: 1
        },
        ttl: 5000
      };

      mock(options.method, 1, function () {
        return new MockedResponseStream({}, JSON.stringify(responseBody));
      });

      this.cachedRequest(options, function (error, response, body) {
        if (error) return done(error);
        expect(response.statusCode).to.equal(200);
        expect(response.headers["x-from-cache"]).to.not.exist;
        expect(body).to.deep.equal(responseBody);

        self.cachedRequest(options, function (error, response, body) {
          if (error) return done(error);
          expect(response.statusCode).to.equal(200);
          expect(response.headers["x-from-cache"]).to.equal(1);
          expect(body).to.deep.equal(responseBody);
          done();
        });
      });
    });

    it("responds the same from the cache if gzipped", function (done) {
      var self = this;
      var responseBody = 'foo';
      var options = {
        url: "http://ping.com/",
        ttl: 5000,
        encoding: null // avoids messing with gzip responses so we can handle them
      };

      //Return gzip compressed response with valid content encoding header
      mock("GET", 1, function () {
        return new MockedResponseStream({}, responseBody).pipe(zlib.createGzip());
      },
      {
        "Content-Encoding": "gzip"
      });

      this.cachedRequest(options, function (error, response, body) {
        if (error) return done(error);
        expect(response.statusCode).to.equal(200);
        expect(response.headers["x-from-cache"]).to.not.exist;

        zlib.gunzip(body, function (error, buffer) {
          if (error) return done(error);
          expect(buffer.toString()).to.deep.equal(responseBody);

          self.cachedRequest(options, function (error, response, body) {
            if (error) return done(error);
            expect(response.statusCode).to.equal(200);
            expect(response.headers["x-from-cache"]).to.equal(1);
            zlib.gunzip(body, function (error, buffer) {
              if (error) done(error);
              expect(buffer.toString()).to.deep.equal(responseBody);
              done();
            });
          });
        });
      });
    });
  });

  describe("streaming", function () {
    it("allows to use request as a stream", function (done) {
      var self = this;
      var responseBody = "";

      for (var i = 0; i < 1000; i++) {
        responseBody += "this is a long response body";
      };

      mock("GET", 1, function () {
        return new MockedResponseStream({}, responseBody);
      });

      var options = {url: "http://ping.com/", ttl: 5000};
      var body = "";

      //Make fresh request
      this.cachedRequest(options)
      .on("data", function (data) {
          body += data;
      })
      .on("end", function () {
        expect(body).to.equal(responseBody);
        body = "";
        //Make cached request
        self.cachedRequest(options)
        .on("response", function (response) {
          expect(response.statusCode).to.equal(200);
          expect(response.headers["x-from-cache"]).to.equal(1);
          response.on("data", function (data) {
            body += data;
          })
          .on("end", function () {
            expect(body).to.equal(responseBody);
            done();
          });
        });
      });
    });

    it("handles gzip response", function (done) {
      var self = this;
      var responseBody = "";

      for (var i = 0; i < 1000; i++) {
        responseBody += "this is a long response body";
      };

      //Return gzip compressed response with valid content encoding header
      mock("GET", 1, function () {
        return new MockedResponseStream({}, responseBody).pipe(zlib.createGzip());
      },
      {
        "Content-Encoding": "gzip"
      });

      var options = {url: "http://ping.com/", ttl: 5000};
      var body = "";

      //Make fresh request
      this.cachedRequest(options)
        .on("data", function (data) {
          //Ignore first reply
        })
        .on("end", function () {
          body = "";
          //Make cached request
          self.cachedRequest(options)
            .on("response", function (response) {
              expect(response.statusCode).to.equal(200);
              expect(response.headers["x-from-cache"]).to.equal(1);
              expect(response.headers["content-encoding"]).to.equal("gzip");

              var gunzip = zlib.createGunzip();
              gunzip.on("data", function (data) {
                body += data.toString();
              });

              gunzip.on("end", function () {
                expect(body).to.equal(responseBody);
                done();
              });

              gunzip.on('error', function (error) {
                done(error);
              });

              response.pipe(gunzip);
            });

        });
    });
  });

  after(function () {
    temp.cleanupSync();
  });
});<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */
var modRewrite = require('../')
  , sinon = require('sinon')
  , chai = require('chai')
  , expect = require('chai').expect;

/**
 * Plugins.
 */

var sinonChai = require('sinon-chai');
chai.should();
chai.use(sinonChai);

/**
 * Specs.
 */

describe('Connect-modrewrite', function() {
  describe('last flag', function() {
    it('should not go to next rewrite rule', function() {
      var middleware = modRewrite(['/a /b [L]', '/a /c']);
      var req = {
        connection : { encrypted : false },
        header : function() {},
        headers : { host : 'test.com' },
        url : '/a'
      };
      var res = {
        writeHead : sinon.spy(),
        end : sinon.spy()
      };
      var next = sinon.spy();
      middleware(req, res, next);
      expect(req.url).to.equal('/b');
    });
  });
});
<commit_msg>Changed spec<commit_after>
/**
 * Module dependencies.
 */
var modRewrite = require('../')
  , sinon = require('sinon')
  , chai = require('chai')
  , expect = require('chai').expect;

/**
 * Plugins.
 */

var sinonChai = require('sinon-chai');
chai.should();
chai.use(sinonChai);

/**
 * Specs.
 */

describe('Connect-modrewrite', function() {
  describe('last flag', function() {
    it('should not go to next rewrite rule if the current matches', function() {
      var middleware = modRewrite(['/a /b [L]', '/a /c']);
      var req = {
        connection : { encrypted : false },
        header : function() {},
        headers : { host : 'test.com' },
        url : '/a'
      };
      var res = {
        writeHead : sinon.spy(),
        end : sinon.spy()
      };
      var next = sinon.spy();
      middleware(req, res, next);
      expect(req.url).to.equal('/b');
    });
  });
});
<|endoftext|>


<commit_before>var assert = require("assert")

describe('Running zondajs tests', function(){
  describe('Router tests', function(){
    it('zondajs.__router must be defined', function(){

    });

    it('zondajs.__router.list must be defined', function(){

    });

    it('zondajs.__router.config must be defined', function(){

    });

    it('zondajs.__router.config.namedRegex must be defined', function(){

    });

    it('zondajs.__router.add must be defined', function(){

    });

    it('zondajs.__router.add is adding routes properly', function(){

    });

    it('zondajs.__router.add creates route object successfully', function(){

    });

    it('zondajs.__router.get must be defined', function(){

    });

    it('zondajs.__router.get is getting the route if exists', function(){

    });

    it('zondajs.__router.get returns false if there is no matching route', function(){

    });

    it('zondajs.__router.get returns an object with method and params properties', function(){

    });

  });

  describe('Dependency Injection tests', function(){

    it('zondajs.__di must be defined', function(){

    });

    it('zondajs.__di.map must be defined', function(){

    });

    it('zondajs.__di.get must be defined', function(){

    });

    it('zondajs.__di.get returns the candidate if exists', function(){

    });

    it('zondajs.__di.get returns undefined if the candidate does not exists', function(){

    });

    it('zondajs.__di.identifyParams must be defined', function(){

    });

    it('zondajs.__di.identifyParams returns an array with the parameters names', function(){

    });

    it('zondajs.__di.identifyParams ignores request and response params', function(){

    });

    it('zondajs.__di.getDependencies must be defined', function(){

    });

    it('zondajs.__di.getDependencies return an array', function(){

    });

    it('zondajs.__di.getDependencies return an object array', function(){

    });

    it('zondajs.__di.invoke must be defined', function(){

    });

    it('zondajs.__di.invoke injects recursively', function(){

    });

    it('zondajs.__di.invoke ignores injection of the hooks array params', function(){

    });

    it('zondajs.__di.invoke calling without hooks param', function(){

    });

  });

  describe('Properties tests', function(){

    it('zondajs.properties must be defined', function(){

    });
    it('zondajs.properties.map must be defined', function(){

    });

    it('zondajs.properties.set must be defined', function(){

    });

    it('zondajs.properties.set adds a key-value object to the map', function(){

    });

    it('zondajs.properties.get must be defined', function(){

    });

    it('zondajs.properties.get returns the property value if the property exists', function(){

    });

    it('zondajs.properties.get returns undefined if the property does not exits', function(){

    });

  });

  describe('Components tests', function(){

    it('zondajs.component must be defined', function(){

    });
    it('zondajs.component is adding the component to the DI map', function(){

    });

  });

  describe('Controllers tests', function(){

    it('zondajs.controllers must be defined', function(){

    });

    it('zondajs.controllers.get must be defined', function(){

    });

    it('zondajs.controllers.get is adding a HTTP GET route', function(){

    });

    it('zondajs.controllers.post must be defined', function(){

    });

    it('zondajs.controllers.post is adding a HTTP POST route', function(){

    });

    it('zondajs.controllers.put must be defined', function(){

    });

    it('zondajs.controllers.put is adding HTTP PUT route', function(){

    });

    it('zondajs.controllers.del must be defined', function(){

    });

    it('zondajs.controllers.del is adding a HTTP DELETE route', function(){

    });

  });

  describe('Middleware tests', function(){

    it('zondajs.middleware must be defined', function(){

    });

    it('zondajs.middleware.list must be defined', function(){

    });

    it('zondajs.middleware.use must be defined', function(){

    });

    it('zondajs.middleware.use is adding the passed param to the middleware list', function(){

    });

  });

  describe('Loader tests', function(){

    it('zondajs.load must be defined', function(){

    });

    it('zondajs.load is requiring each file for the given folder', function(){

    });

    it('zondajs.load callback is called for each file found', function(){

    });

    it('zondajs.load index.js is ignored', function(){

    });

    it('zondajs.load only *.js files are required', function(){

    });

  });

  describe('Enhancements tests', function(){

    it('zondajs.enhancements must be defined', function(){

    });

    it('zondajs.enhancements.response must be defined', function(){

    });

    it('zondajs.enhancements.response.render must be defined', function(){

    });

    it('zondajs.enhancements.response.render is rendering properly', function(){

    });

    it('zondajs.enhancements.response.redirect must be defined', function(){

    });

    it('zondajs.enhancements.response.redirect actually redirects', function(){

    });

    it('zondajs.enhancements.response.sendFile must be defined', function(){

    });

    it('zondajs.enhancements.response.sendFile is answering with the file', function(){

    });

    it('zondajs.enhancements.response.sendFile is only sending files located at the static folder', function(){

    });

    it('zondajs.enhancements.response.sendFile is setting the appropieate mime content-type', function(){

    });

    it('zondajs.enhancements.response.sendJSON must be defined', function(){

    });

    it('zondajs.enhancements.response.sendJSON is converting the provided object to string', function(){

    });

    it('zondajs.enhancements.response.sendJSON is setting content-type application/json', function(){

    });

    it('zondajs.enhancements.response.sendError must be defined', function(){

    });

    it('zondajs.enhancements.response.sendError is rendering the appropiate error file', function(){

    });

    it('zondajs.enhancements.response.sendError is setting the appropiate status header', function(){

    });

    it('zondajs.enhancements.run must be defined', function(){

    });

    it('zondajs.enhancements.run is loading the methods into the request/response', function(){

    });

  });

  describe('Dispatcher tests', function(){

    it('zondajs.dispatcher must be defined', function(){

    });

    it('zondajs.dispatcher.run must be defined', function(){

    });

    it('zondajs.dispatcher.run start the callback calling process', function(){

    });

    it('zondajs.dispatcher.runNext must be defined', function(){

    });

    it('zondajs.dispatcher.runNext calls the next item in the execution queue', function(){

    });

    it('zondajs.dispatcher.dispatch must be defined', function(){

    });

    it('zondajs.dispatcher.dispatch initializes the execution queue if the controller is found', function(){

    });

    it('zondajs.dispatcher.dispatch sends a 404 if the controller is not defined', function(){

    });

  });

  describe('App starter tests', function(){

    it('zondajs.startApp must be defined', function(){

    });

    it('zondajs.startApp creates a server on the given port', function(){

    });

  });
});
<commit_msg>added must be defined test cases<commit_after>var assert = require("assert");
var zondajs = require('../zondajs');

describe('Running zondajs tests', function(){
  describe('Router tests', function(){
    it('zondajs.__routes must be defined', function(){
      assert(zondajs.__routes);
    });

    it('zondajs.__routes.list must be defined', function(){
       assert(zondajs.__routes.list);
    });

    it('zondajs.__routes.config must be defined', function(){
       assert(zondajs.__routes.config);
    });

    it('zondajs.__routes.config.namedRegex must be defined', function(){
       assert(zondajs.__routes.config.namedRegex);
    });

    it('zondajs.__routes.add must be defined', function(){
       assert(zondajs.__routes.add);
    });

    it('zondajs.__routes.add is adding routes properly', function(){
       assert(false);
    });

    it('zondajs.__routes.add creates route object successfully', function(){
       assert(false);
    });

    it('zondajs.__routes.get must be defined', function(){
       assert(zondajs.__routes.get);
    });

    it('zondajs.__routes.get is getting the route if exists', function(){
       assert(false);
    });

    it('zondajs.__routes.get returns false if there is no matching route', function(){
       assert(false);
    });

    it('zondajs.__routes.get returns an object with method and params properties', function(){
       assert(false);
    });

  });

  describe('Dependency Injection tests', function(){

    it('zondajs.__di must be defined', function(){
       assert(zondajs.__di);
    });

    it('zondajs.__di.map must be defined', function(){
       assert(zondajs.__di.map);
    });

    it('zondajs.__di.get must be defined', function(){
       assert(zondajs.__di.get);
    });

    it('zondajs.__di.get returns the candidate if exists', function(){
       assert(false);
    });

    it('zondajs.__di.get returns undefined if the candidate does not exists', function(){
       assert(false);
    });

    it('zondajs.__di.identifyParams must be defined', function(){
       assert(zondajs.__di.identifyParams);
    });

    it('zondajs.__di.identifyParams returns an array with the parameters names', function(){
       assert(false);
    });

    it('zondajs.__di.identifyParams ignores request and response params', function(){
       assert(false);
    });

    it('zondajs.__di.getDependencies must be defined', function(){
       assert(zondajs.__di.getDependencies);
    });

    it('zondajs.__di.getDependencies return an array', function(){
       assert(false);
    });

    it('zondajs.__di.getDependencies return an object array', function(){
       assert(false);
    });

    it('zondajs.__di.invoke must be defined', function(){
       assert(zondajs.__di.invoke);
    });

    it('zondajs.__di.invoke injects recursively', function(){
       assert(false);
    });

    it('zondajs.__di.invoke ignores injection of the hooks array params', function(){
       assert(false);
    });

    it('zondajs.__di.invoke calling without hooks param', function(){
       assert(false);
    });

  });

  describe('Properties tests', function(){

    it('zondajs.properties must be defined', function(){
       assert(zondajs.properties);
    });

    it('zondajs.properties.map must be defined', function(){
       assert(zondajs.properties.map);
    });

    it('zondajs.properties.set must be defined', function(){
       assert(zondajs.properties.set);
    });

    it('zondajs.properties.set adds a key-value object to the map', function(){
       assert(false);
    });

    it('zondajs.properties.get must be defined', function(){
       assert(zondajs.properties.get);
    });

    it('zondajs.properties.get returns the property value if the property exists', function(){
       assert(false);
    });

    it('zondajs.properties.get returns undefined if the property does not exits', function(){
       assert(false);

    });

  });

  describe('Components tests', function(){

    it('zondajs.component must be defined', function(){
       assert(zondajs.component);
    });

    it('zondajs.component is adding the component to the DI map', function(){
       assert(false);
    });

  });

  describe('Controllers tests', function(){

    it('zondajs.controller must be defined', function(){
       assert(zondajs.controller);
    });

    it('zondajs.controller.get must be defined', function(){
       assert(zondajs.controller.get);
    });

    it('zondajs.controller.get is adding a HTTP GET route', function(){
       assert(false);
    });

    it('zondajs.controller.post must be defined', function(){
       assert(zondajs.controller.post);
    });

    it('zondajs.controller.post is adding a HTTP POST route', function(){
       assert(false);
    });

    it('zondajs.controller.put must be defined', function(){
       assert(zondajs.controller.put);
    });

    it('zondajs.controller.put is adding HTTP PUT route', function(){
       assert(false);
    });

    it('zondajs.controller.del must be defined', function(){
       assert(zondajs.controller.del);
    });

    it('zondajs.controller.del is adding a HTTP DELETE route', function(){
       assert(false);
    });

  });

  describe('Middleware tests', function(){

    it('zondajs.middleware must be defined', function(){
       assert(zondajs.middleware);
    });

    it('zondajs.middleware.list must be defined', function(){
       assert(zondajs.middleware.list);
    });

    it('zondajs.middleware.use must be defined', function(){
       assert(zondajs.middleware.use);
    });

    it('zondajs.middleware.use is adding the passed param to the middleware list', function(){
       assert(false);
    });

  });

  describe('Loader tests', function(){

    it('zondajs.load must be defined', function(){
       assert(zondajs.load);
    });

    it('zondajs.load is requiring each file for the given folder', function(){
       assert(false);
    });

    it('zondajs.load callback is called for each file found', function(){
       assert(false);
    });

    it('zondajs.load index.js is ignored', function(){
       assert(false);
    });

    it('zondajs.load only *.js files are required', function(){
       assert(false);
    });

  });

  describe('Enhancements tests', function(){

    it('zondajs.enhancements must be defined', function(){
       assert(zondajs.enhancements);
    });

    it('zondajs.enhancements.response must be defined', function(){
       assert(zondajs.enhancements.response);
    });

    it('zondajs.enhancements.response.render must be defined', function(){
       assert(zondajs.enhancements.response.render);
    });

    it('zondajs.enhancements.response.render is rendering properly', function(){
       assert(false);
    });

    it('zondajs.enhancements.response.redirect must be defined', function(){
       assert(zondajs.enhancements.response.redirect);
    });

    it('zondajs.enhancements.response.redirect actually redirects', function(){
       assert(false);
    });

    it('zondajs.enhancements.response.sendFile must be defined', function(){
       assert(zondajs.enhancements.response.sendFile);
    });

    it('zondajs.enhancements.response.sendFile is answering with the file', function(){
       assert(false);
    });

    it('zondajs.enhancements.response.sendFile is only sending files located at the static folder', function(){
       assert(false);
    });

    it('zondajs.enhancements.response.sendFile is setting the appropieate mime content-type', function(){
       assert(false);
    });

    it('zondajs.enhancements.response.sendJSON must be defined', function(){
       assert(zondajs.enhancements.response.sendJSON);
    });

    it('zondajs.enhancements.response.sendJSON is converting the provided object to string', function(){
       assert(false);
    });

    it('zondajs.enhancements.response.sendJSON is setting content-type application/json', function(){
       assert(false);
    });

    it('zondajs.enhancements.response.sendError must be defined', function(){
       assert(zondajs.enhancements.response.sendError);
    });

    it('zondajs.enhancements.response.sendError is rendering the appropiate error file', function(){
        assert(false);
    });

    it('zondajs.enhancements.response.sendError is setting the appropiate status header', function(){
        assert(false);
    });

    it('zondajs.enhancements.run must be defined', function(){
        assert(zondajs.enhancements.run);
    });

    it('zondajs.enhancements.run is loading the methods into the request/response', function(){
        assert(false);
    });

  });

  describe('Dispatcher tests', function(){

    it('zondajs.dispatcher must be defined', function(){
        assert(zondajs.dispatcher);
    });

    it('zondajs.dispatcher.run must be defined', function(){
        assert(zondajs.dispatcher.run);
    });

    it('zondajs.dispatcher.run start the callback calling process', function(){
        assert(false);
    });

    it('zondajs.dispatcher.runNext must be defined', function(){
        assert(zondajs.dispatcher.runNext);
    });

    it('zondajs.dispatcher.runNext calls the next item in the execution queue', function(){
        assert(false);
    });

    it('zondajs.dispatcher.dispatch must be defined', function(){
        assert(zondajs.dispatcher.dispatch);
    });

    it('zondajs.dispatcher.dispatch initializes the execution queue if the controller is found', function(){
        assert(false);
    });

    it('zondajs.dispatcher.dispatch sends a 404 if the controller is not defined', function(){
        assert(false);
    });

  });

  describe('App starter tests', function(){

    it('zondajs.startApp must be defined', function(){
        assert(zondajs.startApp);
    });

    it('zondajs.startApp creates a server on the given port', function(){
        assert(false);
    });

  });
});
<|endoftext|>


<commit_before>'use strict';
// This is a basic test file for use with testling.
// The test script language comes from tape.
/* jshint node: true */
/* global Promise */
var test = require('tape');

// adapter.js is not supposed to spill console.log
// when used as a module. This temporarily overloads
// console.log so we can assert this.
var logCount = 0;
var saveConsole = console.log.bind(console);
console.log = function() {
  logCount++;
  saveConsole.apply(saveConsole, arguments);
};
var m = require('../adapter.js');
console.log = saveConsole;

test('log suppression', function(t) {
  t.ok(logCount === 0, 'adapter.js does not use console.log');
  t.end();
});

test('Browser identified', function(t) {
  t.plan(3);
  t.ok(m.webrtcDetectedBrowser, 'Browser detected:' + m.webrtcDetectedBrowser);
  t.ok(m.webrtcDetectedVersion,
       'Browser version detected:' + m.webrtcDetectedVersion);
  t.ok(m.webrtcMinimumVersion, 'Minimum Browser version detected');
});

test('Browser supported by adapter.js', function(t) {
  t.plan(1);
  t.ok(m.webrtcDetectedVersion >= m.webrtcMinimumVersion,
      'Browser version supported by adapter.js');
});

test('getUserMedia shim', function(t) {
  t.ok(typeof navigator.getUserMedia !== 'undefined',
       'navigator.getUserMedia is defined');
  t.ok(navigator.mediaDevices &&
       typeof navigator.mediaDevices.getUserMedia !== 'undefined',
       'navigator.mediaDevices.getUserMedia is defined');
  t.end();
});

test('RTCPeerConnection shim', function(t) {
  t.ok(typeof window.RTCPeerConnection !== 'undefined',
       'RTCPeerConnection is defined');
  t.ok(typeof window.RTCSessionDescription !== 'undefined',
       'RTCSessionDescription is defined');
  t.ok(typeof window.RTCIceCandidate !== 'undefined',
       'RTCIceCandidate is defined');
  t.end();
});

test('create RTCPeerConnection', function(t) {
  t.plan(1);
  t.ok(typeof(new RTCPeerConnection()) === 'object',
      'RTCPeerConnection constructor');
});

test('attachMediaStream', function(t) {
  var video = document.createElement('video');
  // if attachMediaStream works, we should get a video
  // at some point. This will trigger onloadedmetadata.
  video.onloadedmetadata = function() {
    t.pass('got stream with w=' + video.videoWidth +
           ',h=' + video.videoHeight);
    t.end();
  };

  var constraints = {video: true, fake: true};
  navigator.mediaDevices.getUserMedia(constraints)
  .then(function(stream) {
    t.pass('got stream.');
    m.attachMediaStream(video, stream);
    t.pass('attachMediaStream worked');
  })
  .catch(function(err) {
    t.fail(err.toString());
  });
});

test('call getUserMedia with constraints', function(t) {
  t.plan(1);
  var impossibleConstraints = {
    video: {
      width: 1280,
      height: {min: 200, ideal: 720, max: 1080},
      frameRate: {exact: 0} // to fail
    },
  };
  if (m.webrtcDetectedBrowser === 'firefox') {
    if (m.webrtcDetectedVersion < 42) {
      t.skip('getUserMedia(impossibleConstraints) must fail (firefox <42 can't turn off fake devices)');
      return;
    }
    impossibleConstraints.fake = false; // override
  }
  new Promise(function(resolve, reject) {
    navigator.getUserMedia(impossibleConstraints, resolve, reject);
  })
  .then(function() {
    t.fail('getUserMedia(impossibleConstraints) must fail');
  })
  .catch(function(err) {
    t.ok(err.name.indexOf('Error') >= 0, 'getUserMedia(impossibleConstraints) must fail');
  });
});

test('basic connection establishment', function(t) {
  var pc1 = new RTCPeerConnection(null);
  var pc2 = new RTCPeerConnection(null);
  var ended = false;

  pc1.createDataChannel('somechannel');
  pc1.oniceconnectionstatechange = function() {
    if (pc1.iceConnectionState === 'connected' ||
        pc1.iceConnectionState === 'completed') {
      t.pass('P2P connection established');
      if (!ended) {
        ended = true;
        t.end();
      }
    }
  };

  var addCandidate = function(pc, event) {
    if (event.candidate) {
      var cand = new RTCIceCandidate(event.candidate);
      pc.addIceCandidate(cand,
        function() {
          t.pass('addIceCandidate');
        },
        function(err) {
          t.fail('addIceCandidate ' + err.toString());
        }
      );
    }
  };
  pc1.onicecandidate = function(event) {
    addCandidate(pc2, event);
  };
  pc2.onicecandidate = function(event) {
    addCandidate(pc1, event);
  };

  pc1.createOffer(
    function(offer) {
      t.pass('pc1.createOffer');
      pc1.setLocalDescription(offer,
        function() {
          t.pass('pc1.setLocalDescription');

          offer = new RTCSessionDescription(offer);
          t.pass('created RTCSessionDescription from offer');
          pc2.setRemoteDescription(offer,
            function() {
              t.pass('pc2.setRemoteDescription');
              pc2.createAnswer(
                function(answer) {
                  t.pass('pc2.createAnswer');
                  pc2.setLocalDescription(answer,
                    function() {
                      t.pass('pc2.setLocalDescription');
                      answer = new RTCSessionDescription(answer);
                      t.pass('created RTCSessionDescription from answer');
                      pc1.setRemoteDescription(answer,
                        function() {
                          t.pass('pc1.setRemoteDescription');
                        },
                        function(err) {
                          t.fail('pc1.setRemoteDescription ' + err.toString());
                        }
                      );
                    },
                    function(err) {
                      t.fail('pc2.setLocalDescription ' + err.toString());
                    }
                  );
                },
                function(err) {
                  t.fail('pc2.createAnswer ' + err.toString());
                }
              );
            },
            function(err) {
              t.fail('pc2.setRemoteDescription ' + err.toString());
            }
          );
        },
        function(err) {
          t.fail('pc1.setLocalDescription ' + err.toString());
        }
      );
    },
    function(err) {
      t.fail('pc1 failed to create offer ' + err.toString());
    }
  );
});

test('basic connection establishment with promise', function(t) {
  var pc1 = new RTCPeerConnection(null);
  var pc2 = new RTCPeerConnection(null);
  var ended = false;

  pc1.createDataChannel('somechannel');
  pc1.oniceconnectionstatechange = function() {
    if (pc1.iceConnectionState === 'connected' ||
        pc1.iceConnectionState === 'completed') {
      t.pass('P2P connection established');
      if (!ended) {
        ended = true;
        t.end();
      }
    }
  };

  var addCandidate = function(pc, event) {
    if (event.candidate) {
      var cand = new RTCIceCandidate(event.candidate);
      pc.addIceCandidate(cand).catch(function(err) {
        t.fail('addIceCandidate ' + err.toString());
      });
    }
  };
  pc1.onicecandidate = function(event) {
    addCandidate(pc2, event);
  };
  pc2.onicecandidate = function(event) {
    addCandidate(pc1, event);
  };

  pc1.createOffer().then(function(offer) {
    t.pass('pc1.createOffer');
    return pc1.setLocalDescription(offer);
  }).then(function() {
    t.pass('pc1.setLocalDescription');
    return pc2.setRemoteDescription(pc1.localDescription);
  }).then(function() {
    t.pass('pc2.setRemoteDescription');
    return pc2.createAnswer();
  }).then(function(answer) {
    t.pass('pc2.createAnswer');
    return pc2.setLocalDescription(answer);
  }).then(function() {
    t.pass('pc2.setLocalDescription');
    return pc1.setRemoteDescription(pc2.localDescription);
  }).then(function() {
    t.pass('pc1.setRemoteDescription');
  }).catch(function(err) {
    t.fail(err.toString());
  });
});

test('call enumerateDevices', function(t) {
  var step = 'enumerateDevices() must succeed';
  navigator.mediaDevices.enumerateDevices()
  .then(function(devices) {
    t.pass(step);
    step = 'valid enumerateDevices output: ' + JSON.stringify(devices);
    t.ok(typeof devices.length === 'number', 'Produced a devices array');
    devices.forEach(function(d) {
      t.ok(d.kind === 'videoinput' ||
           d.kind === 'audioinput' ||
           d.kind === 'audiooutput', 'Known device kind');
      t.ok(d.deviceId.length !== undefined, 'device id present');
      t.ok(d.label.length !== undefined, 'device label present');
    });
    t.pass(step);
    t.end();
  })
  .catch(function(err) {
    t.fail(step + ' - ' + err.toString());
    t.end();
  });
});

// Test that adding and removing an eventlistener on navigator.mediaDevices
// is possible. The usecase for this is the devicechanged event.
// This does not test whether devicechanged is actually called.
test('navigator.mediaDevices eventlisteners', function(t) {
  t.plan(2);
  t.ok(typeof(navigator.mediaDevices.addEventListener) === 'function',
      'navigator.mediaDevices.addEventListener is a function');
  t.ok(typeof(navigator.mediaDevices.removeEventListener) === 'function',
      'navigator.mediaDevices.removeEventListener is a function');
});

// Test that getUserMedia is shimmed properly.
test('navigator.mediaDevices.getUserMedia', function(t) {
  navigator.mediaDevices.getUserMedia({video: true, fake: true})
  .then(function(stream) {
    t.ok(stream.getVideoTracks().length > 0, 'Got stream with video tracks.');
    t.end();
  })
  .catch(function(err) {
    t.fail('getUserMedia failed with error: ' + err.toString());
    t.end();
  });
});

// Test Chrome polyfill for getStats.
test('getStats', function(t) {
  var pc1 = new RTCPeerConnection(null);

  // Test expected new behavior.
  new Promise(function(resolve, reject) {
    pc1.getStats(null, resolve, reject);
  })
  .then(function(report) {
    t.equal(typeof(report), 'object', 'report is an object.');
    for (var key in report) {
      // This avoids problems with Firefox
      if (typeof(report[key]) === 'function') {
        continue;
      }
      t.equal(report[key].id, key, 'report key matches stats id.');
    }
    t.end();
  })
  .catch(function(err) {
    t.fail('getStats() should never fail with error: ' + err.toString());
    t.end();
  });
});

// Test that polyfill for Chrome getStats falls back to builtin functionality
// when the old getStats function signature is used; when the callback is passed
// as the first argument.
test('originalChromeGetStats', function(t) {
  var pc1 = new RTCPeerConnection(null);

  if (m.webrtcDetectedBrowser === 'chrome') {
    new Promise(function(resolve, reject) {  // jshint ignore: line
      pc1.getStats(resolve, null);
    })
    .then(function(response) {
      var reports = response.result();
      reports.forEach(function(report) {
        t.equal(typeof(report), 'object');
        t.equal(typeof(report.id), 'string');
        t.equal(typeof(report.type), 'string');
        t.equal(typeof(report.timestamp), 'object');
        report.names().forEach(function(name) {
          t.notEqual(report.stat(name), null,
              'stat ' +
              name + ' not equal to null');
        });
      });
      t.end();
    })
    .catch(function(err) {
      t.fail('getStats() should never fail with error: ' + err.toString());
      t.end();
    });
  } else {
    // All other browsers.
    t.end();
  }
});

test('getStats promise', function(t) {
  t.plan(2);
  var pc1 = new m.RTCPeerConnection(null);

  var p = pc1.getStats();
  t.ok(typeof p === 'object', 'getStats with no arguments returns a Promise');

  var q = pc1.getStats(null);
  t.ok(typeof q === 'object', 'getStats with a selector returns a Promise');
});
<commit_msg>Fix mess-up.<commit_after>'use strict';
// This is a basic test file for use with testling.
// The test script language comes from tape.
/* jshint node: true */
/* global Promise */
var test = require('tape');

// adapter.js is not supposed to spill console.log
// when used as a module. This temporarily overloads
// console.log so we can assert this.
var logCount = 0;
var saveConsole = console.log.bind(console);
console.log = function() {
  logCount++;
  saveConsole.apply(saveConsole, arguments);
};
var m = require('../adapter.js');
console.log = saveConsole;

test('log suppression', function(t) {
  t.ok(logCount === 0, 'adapter.js does not use console.log');
  t.end();
});

test('Browser identified', function(t) {
  t.plan(3);
  t.ok(m.webrtcDetectedBrowser, 'Browser detected:' + m.webrtcDetectedBrowser);
  t.ok(m.webrtcDetectedVersion,
       'Browser version detected:' + m.webrtcDetectedVersion);
  t.ok(m.webrtcMinimumVersion, 'Minimum Browser version detected');
});

test('Browser supported by adapter.js', function(t) {
  t.plan(1);
  t.ok(m.webrtcDetectedVersion >= m.webrtcMinimumVersion,
      'Browser version supported by adapter.js');
});

test('getUserMedia shim', function(t) {
  t.ok(typeof navigator.getUserMedia !== 'undefined',
       'navigator.getUserMedia is defined');
  t.ok(navigator.mediaDevices &&
       typeof navigator.mediaDevices.getUserMedia !== 'undefined',
       'navigator.mediaDevices.getUserMedia is defined');
  t.end();
});

test('RTCPeerConnection shim', function(t) {
  t.ok(typeof window.RTCPeerConnection !== 'undefined',
       'RTCPeerConnection is defined');
  t.ok(typeof window.RTCSessionDescription !== 'undefined',
       'RTCSessionDescription is defined');
  t.ok(typeof window.RTCIceCandidate !== 'undefined',
       'RTCIceCandidate is defined');
  t.end();
});

test('create RTCPeerConnection', function(t) {
  t.plan(1);
  t.ok(typeof(new RTCPeerConnection()) === 'object',
      'RTCPeerConnection constructor');
});

test('attachMediaStream', function(t) {
  var video = document.createElement('video');
  // if attachMediaStream works, we should get a video
  // at some point. This will trigger onloadedmetadata.
  video.onloadedmetadata = function() {
    t.pass('got stream with w=' + video.videoWidth +
           ',h=' + video.videoHeight);
    t.end();
  };

  var constraints = {video: true, fake: true};
  navigator.mediaDevices.getUserMedia(constraints)
  .then(function(stream) {
    t.pass('got stream.');
    m.attachMediaStream(video, stream);
    t.pass('attachMediaStream worked');
  })
  .catch(function(err) {
    t.fail(err.toString());
  });
});

test('call getUserMedia with constraints', function(t) {
  t.plan(1);
  var impossibleConstraints = {
    video: {
      width: 1280,
      height: {min: 200, ideal: 720, max: 1080},
      frameRate: {exact: 0} // to fail
    },
  };
  if (m.webrtcDetectedBrowser === 'firefox') {
    if (m.webrtcDetectedVersion < 42) {
      t.skip('getUserMedia(impossibleConstraints) must fail (firefox <42 cannot turn off fake devices)');
      return;
    }
    impossibleConstraints.fake = false; // override
  }
  new Promise(function(resolve, reject) {
    navigator.getUserMedia(impossibleConstraints, resolve, reject);
  })
  .then(function() {
    t.fail('getUserMedia(impossibleConstraints) must fail');
  })
  .catch(function(err) {
    t.ok(err.name.indexOf('Error') >= 0, 'getUserMedia(impossibleConstraints) must fail');
  });
});

test('basic connection establishment', function(t) {
  var pc1 = new RTCPeerConnection(null);
  var pc2 = new RTCPeerConnection(null);
  var ended = false;

  pc1.createDataChannel('somechannel');
  pc1.oniceconnectionstatechange = function() {
    if (pc1.iceConnectionState === 'connected' ||
        pc1.iceConnectionState === 'completed') {
      t.pass('P2P connection established');
      if (!ended) {
        ended = true;
        t.end();
      }
    }
  };

  var addCandidate = function(pc, event) {
    if (event.candidate) {
      var cand = new RTCIceCandidate(event.candidate);
      pc.addIceCandidate(cand,
        function() {
          t.pass('addIceCandidate');
        },
        function(err) {
          t.fail('addIceCandidate ' + err.toString());
        }
      );
    }
  };
  pc1.onicecandidate = function(event) {
    addCandidate(pc2, event);
  };
  pc2.onicecandidate = function(event) {
    addCandidate(pc1, event);
  };

  pc1.createOffer(
    function(offer) {
      t.pass('pc1.createOffer');
      pc1.setLocalDescription(offer,
        function() {
          t.pass('pc1.setLocalDescription');

          offer = new RTCSessionDescription(offer);
          t.pass('created RTCSessionDescription from offer');
          pc2.setRemoteDescription(offer,
            function() {
              t.pass('pc2.setRemoteDescription');
              pc2.createAnswer(
                function(answer) {
                  t.pass('pc2.createAnswer');
                  pc2.setLocalDescription(answer,
                    function() {
                      t.pass('pc2.setLocalDescription');
                      answer = new RTCSessionDescription(answer);
                      t.pass('created RTCSessionDescription from answer');
                      pc1.setRemoteDescription(answer,
                        function() {
                          t.pass('pc1.setRemoteDescription');
                        },
                        function(err) {
                          t.fail('pc1.setRemoteDescription ' + err.toString());
                        }
                      );
                    },
                    function(err) {
                      t.fail('pc2.setLocalDescription ' + err.toString());
                    }
                  );
                },
                function(err) {
                  t.fail('pc2.createAnswer ' + err.toString());
                }
              );
            },
            function(err) {
              t.fail('pc2.setRemoteDescription ' + err.toString());
            }
          );
        },
        function(err) {
          t.fail('pc1.setLocalDescription ' + err.toString());
        }
      );
    },
    function(err) {
      t.fail('pc1 failed to create offer ' + err.toString());
    }
  );
});

test('basic connection establishment with promise', function(t) {
  var pc1 = new RTCPeerConnection(null);
  var pc2 = new RTCPeerConnection(null);
  var ended = false;

  pc1.createDataChannel('somechannel');
  pc1.oniceconnectionstatechange = function() {
    if (pc1.iceConnectionState === 'connected' ||
        pc1.iceConnectionState === 'completed') {
      t.pass('P2P connection established');
      if (!ended) {
        ended = true;
        t.end();
      }
    }
  };

  var addCandidate = function(pc, event) {
    if (event.candidate) {
      var cand = new RTCIceCandidate(event.candidate);
      pc.addIceCandidate(cand).catch(function(err) {
        t.fail('addIceCandidate ' + err.toString());
      });
    }
  };
  pc1.onicecandidate = function(event) {
    addCandidate(pc2, event);
  };
  pc2.onicecandidate = function(event) {
    addCandidate(pc1, event);
  };

  pc1.createOffer().then(function(offer) {
    t.pass('pc1.createOffer');
    return pc1.setLocalDescription(offer);
  }).then(function() {
    t.pass('pc1.setLocalDescription');
    return pc2.setRemoteDescription(pc1.localDescription);
  }).then(function() {
    t.pass('pc2.setRemoteDescription');
    return pc2.createAnswer();
  }).then(function(answer) {
    t.pass('pc2.createAnswer');
    return pc2.setLocalDescription(answer);
  }).then(function() {
    t.pass('pc2.setLocalDescription');
    return pc1.setRemoteDescription(pc2.localDescription);
  }).then(function() {
    t.pass('pc1.setRemoteDescription');
  }).catch(function(err) {
    t.fail(err.toString());
  });
});

test('call enumerateDevices', function(t) {
  var step = 'enumerateDevices() must succeed';
  navigator.mediaDevices.enumerateDevices()
  .then(function(devices) {
    t.pass(step);
    step = 'valid enumerateDevices output: ' + JSON.stringify(devices);
    t.ok(typeof devices.length === 'number', 'Produced a devices array');
    devices.forEach(function(d) {
      t.ok(d.kind === 'videoinput' ||
           d.kind === 'audioinput' ||
           d.kind === 'audiooutput', 'Known device kind');
      t.ok(d.deviceId.length !== undefined, 'device id present');
      t.ok(d.label.length !== undefined, 'device label present');
    });
    t.pass(step);
    t.end();
  })
  .catch(function(err) {
    t.fail(step + ' - ' + err.toString());
    t.end();
  });
});

// Test that adding and removing an eventlistener on navigator.mediaDevices
// is possible. The usecase for this is the devicechanged event.
// This does not test whether devicechanged is actually called.
test('navigator.mediaDevices eventlisteners', function(t) {
  t.plan(2);
  t.ok(typeof(navigator.mediaDevices.addEventListener) === 'function',
      'navigator.mediaDevices.addEventListener is a function');
  t.ok(typeof(navigator.mediaDevices.removeEventListener) === 'function',
      'navigator.mediaDevices.removeEventListener is a function');
});

// Test that getUserMedia is shimmed properly.
test('navigator.mediaDevices.getUserMedia', function(t) {
  navigator.mediaDevices.getUserMedia({video: true, fake: true})
  .then(function(stream) {
    t.ok(stream.getVideoTracks().length > 0, 'Got stream with video tracks.');
    t.end();
  })
  .catch(function(err) {
    t.fail('getUserMedia failed with error: ' + err.toString());
    t.end();
  });
});

// Test Chrome polyfill for getStats.
test('getStats', function(t) {
  var pc1 = new RTCPeerConnection(null);

  // Test expected new behavior.
  new Promise(function(resolve, reject) {
    pc1.getStats(null, resolve, reject);
  })
  .then(function(report) {
    t.equal(typeof(report), 'object', 'report is an object.');
    for (var key in report) {
      // This avoids problems with Firefox
      if (typeof(report[key]) === 'function') {
        continue;
      }
      t.equal(report[key].id, key, 'report key matches stats id.');
    }
    t.end();
  })
  .catch(function(err) {
    t.fail('getStats() should never fail with error: ' + err.toString());
    t.end();
  });
});

// Test that polyfill for Chrome getStats falls back to builtin functionality
// when the old getStats function signature is used; when the callback is passed
// as the first argument.
test('originalChromeGetStats', function(t) {
  var pc1 = new RTCPeerConnection(null);

  if (m.webrtcDetectedBrowser === 'chrome') {
    new Promise(function(resolve, reject) {  // jshint ignore: line
      pc1.getStats(resolve, null);
    })
    .then(function(response) {
      var reports = response.result();
      reports.forEach(function(report) {
        t.equal(typeof(report), 'object');
        t.equal(typeof(report.id), 'string');
        t.equal(typeof(report.type), 'string');
        t.equal(typeof(report.timestamp), 'object');
        report.names().forEach(function(name) {
          t.notEqual(report.stat(name), null,
              'stat ' +
              name + ' not equal to null');
        });
      });
      t.end();
    })
    .catch(function(err) {
      t.fail('getStats() should never fail with error: ' + err.toString());
      t.end();
    });
  } else {
    // All other browsers.
    t.end();
  }
});

test('getStats promise', function(t) {
  t.plan(2);
  var pc1 = new m.RTCPeerConnection(null);

  var p = pc1.getStats();
  t.ok(typeof p === 'object', 'getStats with no arguments returns a Promise');

  var q = pc1.getStats(null);
  t.ok(typeof q === 'object', 'getStats with a selector returns a Promise');
});
<|endoftext|>


<commit_before>"use strict";

const assert = require('chai').assert;
const Sequelize = require('sequelize');
const winston = require('winston');
const WinstonTransportSequelize = require('../index');

let sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'sqlite',
  storage: ':memory:',
  logging: false
});

let logger = new winston.Logger({
  transports: [
    new WinstonTransportSequelize({
      level: 'info',
      sequelize: sequelize
    })
  ]
});

let transport = logger.transports.sequelize;

describe('WinstonTransportSequelize:', function () {
  let message = 'message';
  let meta = { meta: 'meta' };

  before(function() {
    return sequelize.sync({ force: true });
  });

  function transportCallback(loggedFn, errorFn) {
    function onLogged() {
      transport.removeListener('logged',  onLogged);
      loggedFn && loggedFn();
    }

    function onError() {
      transport.removeListener('error', onError);
      errorFn && errorFn();
    }

    transport.on('logged', onLogged).on('error', onError);
  }

  it('#log()', function (done) {
    function onLogged() {
      transport.model.findOne({ where: { message: 'message' } }).then((res) => {
        res = res.get();
        assert.equal(res.level, 'info', 'different level');
        assert.equal(JSON.stringify(res.meta), JSON.stringify(res.meta), 'different meta objects');
        done();
      });
    }

    transportCallback(onLogged, () => { throw new Error('Error in the log function') });

    logger.info(message, meta);
  });

  it('#clear()', function () {
    return transport.clear(2).then(() => {
      return transport.model.count().then((count) => {
        assert.equal(count, 1);
      });
    }).then(() => {
      return transport.clear().then(() => {
        return transport.model.count().then((count) => {
          assert.equal(count, 0);
        });
      });
    });
  });
});

<commit_msg>add modelOptions<commit_after>"use strict";

const assert = require('chai').assert;
const Sequelize = require('sequelize');
const winston = require('winston');
const WinstonTransportSequelize = require('../index');

const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'sqlite',
  storage: ':memory:',
  logging: false
});

const logger = new winston.Logger({
  transports: [
    new WinstonTransportSequelize({
      level: 'info',
      sequelize: sequelize
    })
  ]
});

let transport = logger.transports.sequelize;

describe('WinstonTransportSequelize:', function () {
  let message = 'message';
  let meta = { meta: 'meta' };

  before(function() {
    return sequelize.sync({ force: true });
  });

  function transportCallback(loggedFn, errorFn) {
    function onLogged() {
      transport.removeListener('logged',  onLogged);
      loggedFn && loggedFn();
    }

    function onError() {
      transport.removeListener('error', onError);
      errorFn && errorFn();
    }

    transport.on('logged', onLogged).on('error', onError);
  }

  it('#log()', function (done) {
    function onLogged() {
      transport.model.findOne({ where: { message: 'message' } }).then((res) => {
        res = res.get();
        assert.equal(res.level, 'info', 'different level');
        assert.equal(JSON.stringify(res.meta), JSON.stringify(res.meta), 'different meta objects');
        done();
      });
    }

    transportCallback(onLogged, () => { throw new Error('Error in the log function') });

    logger.info(message, meta);
  });

  it('#clear()', function () {
    return transport.clear(2).then(() => {
      return transport.model.count().then((count) => {
        assert.equal(count, 1);
      });
    }).then(() => {
      return transport.clear().then(() => {
        return transport.model.count().then((count) => {
          assert.equal(count, 0);
        });
      });
    });
  });
});

<|endoftext|>


<commit_before>// requires mocha (npm install mocha -g)
var assert = require('assert'),
	fs = require('fs'),
	fn = 'test/testfile',
	fsw = require('../index.js')

function makeFileGrow (txt, cb) {
	fs.appendFile(fn, txt, function(err) {
		cb(err);
	});
}

function makeFileShrink (txt, cb) {
	fs.truncate(fn, 1, function(err) {
		cb(err);
	});
}

function listenForSizeChange (watcher, cb) {
	var notDone = true,
		currSize = watcher.info().size;
	watcher.once('sizeChange', function(newSize){
		notDone = false;
		cb(newSize-currSize);
	});
	watcher.once('error',function(e) {
		if (notDone) throw(e);
	});
	setTimeout(function tooSlow() {
		if(notDone)	throw("test timed out");
	}, 2000);
}

function ignoreSizeChange (watcher, cb) {
	var notDone = true;
	watcher.once('sizeChange', function(){
		if (notDone) throw("test failed.. to time out");
	});
	watcher.once('error',function(e) {
		if (notDone) throw(e);
	});
	setTimeout(function tooSlow() {
		notDone = false;
		cb();
	}, 500);
}

function emoteSuccess (testDesc) {
	console.log("Test Passed.");
}

// First just create a file to test with
before(function(done){
	console.log("Creating a test file");
	makeFileGrow("Creating a file\n", function() {
		watcher = fsw.watch(fn, 100);
		done();
	});
});

// Test to see if watcher detects file growth.
describe('watcher',function(){
	describe('#changes', function(){
		var desc1 = "Test 1: File grows, watcher detects this.";
		it(desc1, function(done) {
			console.log(desc1);
			listenForSizeChange(watcher, function(sizeChange) {
				assert((sizeChange>0),"File size is positive");
				emoteSuccess(desc1);
				done();
			});

			makeFileGrow("testing...\n", function afterGrow(err) {
				if (err) {
					done(err);
				}
			});
		});

		var desc2 = "Test 2: File grows, watcher detects this.";
		it(desc2, function(done) {
			console.log(desc2);
			listenForSizeChange(watcher, function(sizeChange) {
				assert((sizeChange>0),"File size is positive");
				emoteSuccess(desc2);
				done();
			});

			makeFileGrow("testing... 2\n", function afterGrow(err) {
				if (err) {
					done(err);
				}
			});
		});

		var desc3 = "Test 3: File shrinks, watcher detects this.";
		it(desc3, function(done) {
			console.log(desc3);
			listenForSizeChange(watcher, function(sizeChange) {
				assert((sizeChange<0),"File size is negative");
				emoteSuccess(desc3);
				done();
			});

			makeFileShrink("testing... 3\n", function afterAfterShrink(err) {
				if (err) {
					done(err);
				}
			});
		});
	});

	describe("controlling",function(){

		var desc4 = "Test 4: stop watcher"
		it(desc4,function(done) {
			console.log(desc4);
			watcher.stop();
			ignoreSizeChange(watcher, function() {
				emoteSuccess(desc4);
				done();
			});

			makeFileGrow("testing... 4\n", function afterGrow(err) {
				if (err) {
					done(err);
				}
			});
		});

		var desc5 = "Test 5: resume watcher"
		it(desc5,function(done) {
			console.log(desc5);
			watcher.go();
			listenForSizeChange(watcher, function(sizeChange) {
				assert((sizeChange>0),"File size is positive");
				emoteSuccess(desc5);
				done();
			});

			makeFileGrow("testing... 5\n", function afterAfterShrink(err) {
				if (err) {
					done(err);
				}
			});
		});
	});

	describe('other stuff',function() {
		var desc6 = "Testing info()";
		it(desc6, function() {
			console.log(desc6);
			console.log("Size of file is: " + watcher.info().size + " bytes");
			assert(watcher.info().size>0,"Watcher.info reports positive size");
		});

		// Delete file then test to make sure watcher emits an error event
		var desc7 ='Testing error event emission';
		it(desc7, function(done) {
			console.log(desc7);
			watcher.on('error',function(e) {
				console.log("watcher correctly saw error: " + e);
				assert(e.toString()!=="","Testing error msg existence");
				done();
			});
			console.log("Removing test file...");
			fs.unlink(fn, function(e) {
				if(e) throw(e);
			});
		});
	});
});

<commit_msg>Added test for running on nonexistent file<commit_after>// requires mocha (npm install mocha -g)
var assert = require('assert'),
	fs = require('fs'),
	fn = 'test/testfile',
	fsw = require('../index.js'),
	watcher;

function makeFileGrow (txt, cb) {
	fs.appendFile(fn, txt, function(err) {
		cb(err);
	});
}

function makeFileShrink (txt, cb) {
	fs.truncate(fn, 1, function(err) {
		cb(err);
	});
}

function listenForSizeChange (watcher, cb) {
	var notDone = true,
		currSize = watcher.info().size;
	watcher.once('sizeChange', function(newSize){
		notDone = false;
		cb(newSize-currSize);
	});
	watcher.once('error',function(e) {
		if (notDone) throw(e);
	});
	setTimeout(function tooSlow() {
		if(notDone)	throw("test timed out");
	}, 2000);
}

function ignoreSizeChange (watcher, cb) {
	var notDone = true;
	watcher.once('sizeChange', function(){
		if (notDone) throw("test failed.. to time out");
	});
	watcher.once('error',function(e) {
		if (notDone) throw(e);
	});
	setTimeout(function tooSlow() {
		notDone = false;
		cb();
	}, 500);
}

function emoteSuccess (testDesc) {
	console.log("Test Passed.");
}

// First just create a file to test with
before(function(done){
	console.log("Creating a test file");
	makeFileGrow("Creating a file\n", function() {
		watcher = fsw.watch(fn, 100);
		done();
	});
});

// Test to see if watcher detects file growth.
describe('watcher',function(){
	describe('#changes', function(){
		var desc1 = "Test 1: File grows, watcher detects this.";
		it(desc1, function(done) {
			console.log(desc1);
			listenForSizeChange(watcher, function(sizeChange) {
				assert((sizeChange>0),"File size is positive");
				emoteSuccess(desc1);
				done();
			});

			makeFileGrow("testing...\n", function afterGrow(err) {
				if (err) {
					done(err);
				}
			});
		});

		var desc2 = "Test 2: File grows, watcher detects this.";
		it(desc2, function(done) {
			console.log(desc2);
			listenForSizeChange(watcher, function(sizeChange) {
				assert((sizeChange>0),"File size is positive");
				emoteSuccess(desc2);
				done();
			});

			makeFileGrow("testing... 2\n", function afterGrow(err) {
				if (err) {
					done(err);
				}
			});
		});

		var desc3 = "Test 3: File shrinks, watcher detects this.";
		it(desc3, function(done) {
			console.log(desc3);
			listenForSizeChange(watcher, function(sizeChange) {
				assert((sizeChange<0),"File size is negative");
				emoteSuccess(desc3);
				done();
			});

			makeFileShrink("testing... 3\n", function afterAfterShrink(err) {
				if (err) {
					done(err);
				}
			});
		});
	});

	describe("controlling",function(){

		var desc4 = "Test 4: stop watcher"
		it(desc4,function(done) {
			console.log(desc4);
			watcher.stop();
			ignoreSizeChange(watcher, function() {
				emoteSuccess(desc4);
				done();
			});

			makeFileGrow("testing... 4\n", function afterGrow(err) {
				if (err) {
					done(err);
				}
			});
		});

		var desc5 = "Test 5: resume watcher"
		it(desc5,function(done) {
			console.log(desc5);
			watcher.go();
			listenForSizeChange(watcher, function(sizeChange) {
				assert((sizeChange>0),"File size is positive");
				emoteSuccess(desc5);
				done();
			});

			makeFileGrow("testing... 5\n", function afterAfterShrink(err) {
				if (err) {
					done(err);
				}
			});
		});
	});

	describe('other stuff',function() {
		var desc6 = "Testing info()";
		it(desc6, function() {
			console.log(desc6);
			console.log("Size of file is: " + watcher.info().size + " bytes");
			assert(watcher.info().size>0,"Watcher.info reports positive size");
			emoteSuccess(desc6);
		});

		// Delete file then test to make sure watcher emits an error event
		var desc7 ='Testing error event emission';
		it(desc7, function(done) {
			console.log(desc7);
			watcher.on('error',function(e) {
				console.log("watcher correctly saw error: " + e);
				assert(e.toString()!=="","Testing error msg existence");
				done();
				emoteSuccess(desc7);
				watcher.stop();
				watcher.removeAllListeners();
			});
			console.log("Removing test file...");
			fs.unlink(fn, function(e) {
				if(e) throw(e);
			});
		});

		var desc8 ='Try running on nonexistent file';
		it(desc8, function(done) {
			console.log(desc8);
			var newWatcher = fsw.watch('doesNotExist.log',100);
			newWatcher.on('error',function(e) {});
			setTimeout(function() {
				emoteSuccess(desc8);
				done();
			}, 200);
		});
	});
});

<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var webpack = require('webpack')
var jsdom = require('jsdom')
var expect = require('chai').expect
var rimraf = require('rimraf')
var hash = require('hash-sum')
var SourceMapConsumer = require('source-map').SourceMapConsumer
var ExtractTextPlugin = require("extract-text-webpack-plugin")

describe('vue-loader', function () {

  var testHTML = '<!DOCTYPE html>'
  var outputDir = path.resolve(__dirname, './output')
  var loaderPath = path.resolve(__dirname, '../')
  var globalConfig = {
    output: {
      path: outputDir,
      filename: 'test.build.js'
    },
    module: {
      loaders: [
        {
          test: /\.vue$/,
          loader: loaderPath
        }
      ]
    }
  }

  beforeEach(function (done) {
    rimraf(outputDir, done)
  })

  function getFile (file, cb) {
    fs.readFile(path.resolve(outputDir, file), 'utf-8', function (err, data) {
      expect(err).to.be.not.exist
      cb(data)
    })
  }

  function test (options, assert) {
    var config = Object.assign({}, globalConfig, options)
    webpack(config, function (err) {
      if (err) throw err
      getFile('test.build.js', function (data) {
        jsdom.env({
          html: testHTML,
          src: [data],
          done: function (err, window) {
            if (err) {
              console.log(err[0].data.error.stack)
              expect(err).to.be.null
            }
            assert(window)
          }
        })
      })
    })
  }

  it('basic', function (done) {
    test({
      entry: './test/fixtures/basic.js'
    }, function (window) {
      var module = window.testModule
      expect(module.template).to.contain('
{{msg}}
')
      expect(module.data().msg).to.contain('Hello from Component A!')
      var style = window.document.querySelector('style').textContent
      expect(style).to.contain('comp-a h2 {\n  color: #f00;\n}')
      done()
    })
  })

  it('pre-processors', function (done) {
    test({
      entry: './test/fixtures/pre.js'
    }, function (window) {
      var module = window.testModule
      expect(module.template).to.contain(
        '
This is the app
' +
        '<comp-a></comp-a>' +
        '<comp-b></comp-b>'
      )
      expect(module.data().msg).to.contain('Hello from coffee!')
      var style = window.document.querySelector('style').textContent
      expect(style).to.contain('body {\n  font: 100% Helvetica, sans-serif;\n  color: #999;\n}')
      done()
    })
  })

  it('scoped style', function (done) {
    test({
      entry: './test/fixtures/scoped-css.js'
    }, function (window) {
      var module = window.testModule
      var id = '_v-' + hash(require.resolve('./fixtures/scoped-css.vue'))
      expect(module.template).to.contain(
        '

hi

\n' +
        '
hi
'
      )
      var style = window.document.querySelector('style').textContent
      expect(style).to.contain('.test[' + id + '] {\n  color: yellow;\n}')
      expect(style).to.contain('.test[' + id + ']:after {\n  content: \'bye!\';\n}')
      expect(style).to.contain('h1[' + id + '] {\n  color: green;\n}')
      done()
    })
  })

  it('style import', function (done) {
    test({
      entry: './test/fixtures/style-import.vue'
    }, function (window) {
      var styles = window.document.querySelectorAll('style')
      expect(styles[0].textContent).to.contain('h1 { color: red; }')
      // import with scoped
      var id = '_v-' + hash(require.resolve('./fixtures/style-import.vue'))
      expect(styles[1].textContent).to.contain('h1[' + id + '] { color: green; }')
      done()
    })
  })

  it('template import', function (done) {
    test({
      entry: './test/fixtures/template-import.js'
    }, function (window) {
      var module = window.testModule
      expect(module.template).to.contain('

hello

')
      done()
    })
  })

  it('script import', function (done) {
    test({
      entry: './test/fixtures/script-import-entry.js'
    }, function (window) {
      var module = window.testModule
      expect(module.data().msg).to.contain('Hello from Component A!')
      done()
    })
  })

  it('source map', function (done) {
    var config = Object.assign({}, globalConfig, {
      entry: './test/fixtures/basic.js',
      devtool: 'source-map'
    })
    webpack(config, function (err) {
      expect(err).to.be.null
      getFile('test.build.js.map', function (map) {
        var smc = new SourceMapConsumer(JSON.parse(map))
        getFile('test.build.js', function (code) {
          var line
          var col
          var lines = code.split(/\r?\n/g)
          var targetRE = /^\s+msg: 'Hello from Component A!'/
          lines.some(function (l, i) {
            if (targetRE.test(l)) {
              line = i
              col = lines[i - 1].length
              return true
            }
          })
          var pos = smc.originalPositionFor({
            line: line,
            column: col
          })
          expect(pos.source.indexOf('basic.vue') > -1)
          expect(pos.line).to.equal(15)
          done()
        })
      })
    })
  })

  it('autoprefix', function (done) {
    test({
      entry: './test/fixtures/autoprefix.js'
    }, function (window) {
      var style = window.document.querySelector('style').textContent
      expect(style).to.contain('body {\n  -webkit-transform: scale(1);\n          transform: scale(1);\n}')
      done()
    })
  })

  it('media-query', function (done) {
    test({
      entry: './test/fixtures/media-query.js'
    }, function (window) {
      var style = window.document.querySelector('style').textContent
      var id = '_v-' + hash(require.resolve('./fixtures/media-query.vue'))
      expect(style).to.contain('@media print {\n  .foo[' + id + '] {\n    color: #000;\n  }\n}')
      done()
    })
  })

  it('extract CSS', function (done) {
    webpack(Object.assign({}, globalConfig, {
      entry: './test/fixtures/extract-css.js',
      vue: {
        loaders: {
          css: ExtractTextPlugin.extract('css'),
          stylus: ExtractTextPlugin.extract('css?sourceMap!stylus')
        }
      },
      plugins: [
        new ExtractTextPlugin('test.output.css')
      ]
    }), function (err) {
      expect(err).to.be.null
      getFile('test.output.css', function (data) {
        expect(data).to.contain('h1 {\n  color: #f00;\n}\n\nh2 {\n  color: green;\n}')
        done()
      })
    })
  })

  it('dependency injection', function () {
    test({
      entry: './test/fixtures/inject.js'
    }, function (window) {
      var module = window.injector({
        '../service': {
          msg: 'Hello from mocked service!'
        }
      })
      expect(module.template).to.contain('
{{ msg }}
')
      expect(module.data().msg).to.contain('Hello from mocked service!')
      done()
    })
  })

})
<commit_msg>fix source map test<commit_after>var fs = require('fs')
var path = require('path')
var webpack = require('webpack')
var jsdom = require('jsdom')
var expect = require('chai').expect
var rimraf = require('rimraf')
var hash = require('hash-sum')
var SourceMapConsumer = require('source-map').SourceMapConsumer
var ExtractTextPlugin = require("extract-text-webpack-plugin")

describe('vue-loader', function () {

  var testHTML = '<!DOCTYPE html>'
  var outputDir = path.resolve(__dirname, './output')
  var loaderPath = path.resolve(__dirname, '../')
  var globalConfig = {
    output: {
      path: outputDir,
      filename: 'test.build.js'
    },
    module: {
      loaders: [
        {
          test: /\.vue$/,
          loader: loaderPath
        }
      ]
    }
  }

  beforeEach(function (done) {
    rimraf(outputDir, done)
  })

  function getFile (file, cb) {
    fs.readFile(path.resolve(outputDir, file), 'utf-8', function (err, data) {
      expect(err).to.be.not.exist
      cb(data)
    })
  }

  function test (options, assert) {
    var config = Object.assign({}, globalConfig, options)
    webpack(config, function (err) {
      if (err) throw err
      getFile('test.build.js', function (data) {
        jsdom.env({
          html: testHTML,
          src: [data],
          done: function (err, window) {
            if (err) {
              console.log(err[0].data.error.stack)
              expect(err).to.be.null
            }
            assert(window)
          }
        })
      })
    })
  }

  it('basic', function (done) {
    test({
      entry: './test/fixtures/basic.js'
    }, function (window) {
      var module = window.testModule
      expect(module.template).to.contain('
{{msg}}
')
      expect(module.data().msg).to.contain('Hello from Component A!')
      var style = window.document.querySelector('style').textContent
      expect(style).to.contain('comp-a h2 {\n  color: #f00;\n}')
      done()
    })
  })

  it('pre-processors', function (done) {
    test({
      entry: './test/fixtures/pre.js'
    }, function (window) {
      var module = window.testModule
      expect(module.template).to.contain(
        '
This is the app
' +
        '<comp-a></comp-a>' +
        '<comp-b></comp-b>'
      )
      expect(module.data().msg).to.contain('Hello from coffee!')
      var style = window.document.querySelector('style').textContent
      expect(style).to.contain('body {\n  font: 100% Helvetica, sans-serif;\n  color: #999;\n}')
      done()
    })
  })

  it('scoped style', function (done) {
    test({
      entry: './test/fixtures/scoped-css.js'
    }, function (window) {
      var module = window.testModule
      var id = '_v-' + hash(require.resolve('./fixtures/scoped-css.vue'))
      expect(module.template).to.contain(
        '

hi

\n' +
        '
hi
'
      )
      var style = window.document.querySelector('style').textContent
      expect(style).to.contain('.test[' + id + '] {\n  color: yellow;\n}')
      expect(style).to.contain('.test[' + id + ']:after {\n  content: \'bye!\';\n}')
      expect(style).to.contain('h1[' + id + '] {\n  color: green;\n}')
      done()
    })
  })

  it('style import', function (done) {
    test({
      entry: './test/fixtures/style-import.vue'
    }, function (window) {
      var styles = window.document.querySelectorAll('style')
      expect(styles[0].textContent).to.contain('h1 { color: red; }')
      // import with scoped
      var id = '_v-' + hash(require.resolve('./fixtures/style-import.vue'))
      expect(styles[1].textContent).to.contain('h1[' + id + '] { color: green; }')
      done()
    })
  })

  it('template import', function (done) {
    test({
      entry: './test/fixtures/template-import.js'
    }, function (window) {
      var module = window.testModule
      expect(module.template).to.contain('

hello

')
      done()
    })
  })

  it('script import', function (done) {
    test({
      entry: './test/fixtures/script-import-entry.js'
    }, function (window) {
      var module = window.testModule
      expect(module.data().msg).to.contain('Hello from Component A!')
      done()
    })
  })

  it('source map', function (done) {
    var config = Object.assign({}, globalConfig, {
      entry: './test/fixtures/basic.js',
      devtool: 'source-map'
    })
    webpack(config, function (err) {
      expect(err).to.be.null
      getFile('test.build.js.map', function (map) {
        var smc = new SourceMapConsumer(JSON.parse(map))
        getFile('test.build.js', function (code) {
          var line
          var col
          var targetRE = /^\s+msg: 'Hello from Component A!'/
          code.split(/\r?\n/g).some(function (l, i) {
            if (targetRE.test(l)) {
              line = i + 1
              col = l.length
              return true
            }
          })
          var pos = smc.originalPositionFor({
            line: line,
            column: col
          })
          expect(pos.source.indexOf('basic.vue') > -1)
          expect(pos.line).to.equal(15)
          done()
        })
      })
    })
  })

  it('autoprefix', function (done) {
    test({
      entry: './test/fixtures/autoprefix.js'
    }, function (window) {
      var style = window.document.querySelector('style').textContent
      expect(style).to.contain('body {\n  -webkit-transform: scale(1);\n          transform: scale(1);\n}')
      done()
    })
  })

  it('media-query', function (done) {
    test({
      entry: './test/fixtures/media-query.js'
    }, function (window) {
      var style = window.document.querySelector('style').textContent
      var id = '_v-' + hash(require.resolve('./fixtures/media-query.vue'))
      expect(style).to.contain('@media print {\n  .foo[' + id + '] {\n    color: #000;\n  }\n}')
      done()
    })
  })

  it('extract CSS', function (done) {
    webpack(Object.assign({}, globalConfig, {
      entry: './test/fixtures/extract-css.js',
      vue: {
        loaders: {
          css: ExtractTextPlugin.extract('css'),
          stylus: ExtractTextPlugin.extract('css?sourceMap!stylus')
        }
      },
      plugins: [
        new ExtractTextPlugin('test.output.css')
      ]
    }), function (err) {
      expect(err).to.be.null
      getFile('test.output.css', function (data) {
        expect(data).to.contain('h1 {\n  color: #f00;\n}\n\nh2 {\n  color: green;\n}')
        done()
      })
    })
  })

  it('dependency injection', function () {
    test({
      entry: './test/fixtures/inject.js'
    }, function (window) {
      var module = window.injector({
        '../service': {
          msg: 'Hello from mocked service!'
        }
      })
      expect(module.template).to.contain('
{{ msg }}
')
      expect(module.data().msg).to.contain('Hello from mocked service!')
      done()
    })
  })

})
<|endoftext|>


<commit_before>// Mann-Whitney U test
// Luke Mitchell, April 2016
// https://github.com/lukem512/mann-whitney-utest

var mwu = require('../src/mann-whitney');

var tests = [
	{
		name: 'Simple U test #1',
		expected: [19.5, 44.5],
		rejected: false,
		samples: [
			[30, 14, 6, 11, 88, 1, 3, 7],
			[12, 15, 16, 42, 9, 9, 30, 28]
		]
	},

	{
		name: 'Simple U test #2',
		expected: [48.5, 23.5],
		rejected: false,
		samples: [
			[1, 4, 9, 6, 4, 3, 5, 6, 4],
			[1, 5, 3, 2, 5, 4, 1, 5]
		]
	},

	{
		name: 'Sample count > 2',
		rejected: true,
		samples: [
			[30, 14, 6, 11, 88, 1, 3, 7],
			[12, 15, 16, 42, 9, 9, 30, 28],
			[1, 2, 3, 4, 5, 6, 7, 8]
		]
	},

	{
		name: 'Empty sample array',
		rejected: true,
		samples: []
	},

	{
		name: 'Empty samples',
		rejected: true,
		samples: [[],[]]
	},

	{
		name: 'Non-array sample (string)',
		rejected: true,
		samples: 'hello'
	},

	{
		name: 'Non-array sample (numeric)',
		rejected: true,
		samples: 30
	},

	{
		name: 'Non-array sample (boolean)',
		rejected: true,
		samples: true
	},

	{
		name: 'Non-array sample (object)',
		rejected: true,
		samples: { some: 'json' }
	},

	{
		name: 'Non-array sample (function)',
		rejected: true,
		samples: function() { return []; }
	},

	{
		name: 'Non-array sample (null)',
		rejected: true,
		samples: null
	}
];

var passed = true;

tests.forEach(function(t) {
	try {
		var u = mwu.test(t.samples);
		if (!mwu.check(u, t.samples)) throw Error('Check failed');
		if (!t.expected) throw Error('Unexpected results');

		u.forEach(function(o, index) {
			if (t.expected[index] !== o)
				throw Error('Returned results did not match expected results');
		})
	} catch (err) {
		if (!t.rejected) {
			console.error(t.name, err);
			passed = false;
		}
	}
});

if (passed) console.log('Tests succeeded');
else console.log('Tests failed');

return passed;
<commit_msg>Correct test format<commit_after>// Mann-Whitney U test
// Luke Mitchell, April 2016
// https://github.com/lukem512/mann-whitney-utest

var mwu = require('../src/mann-whitney');

var tests = [
	{
		name: 'Simple U test #1',
		expected: [19.5, 44.5],
		rejected: false,
		samples: [
			[30, 14, 6, 11, 88, 1, 3, 7],
			[12, 15, 16, 42, 9, 9, 30, 28]
		]
	},

	{
		name: 'Simple U test #2',
		expected: [48.5, 23.5],
		rejected: false,
		samples: [
			[1, 4, 9, 6, 4, 3, 5, 6, 4],
			[1, 5, 3, 2, 5, 4, 1, 5]
		]
	},

	{
		name: 'Sample count > 2',
		rejected: true,
		samples: [
			[30, 14, 6, 11, 88, 1, 3, 7],
			[12, 15, 16, 42, 9, 9, 30, 28],
			[1, 2, 3, 4, 5, 6, 7, 8]
		]
	},

	{
		name: 'Empty sample array',
		rejected: true,
		samples: []
	},

	{
		name: 'Empty samples',
		rejected: true,
		samples: [[],[]]
	},

	{
		name: 'Non-array sample (string)',
		rejected: true,
		samples: 'hello'
	},

	{
		name: 'Non-array sample (numeric)',
		rejected: true,
		samples: 30
	},

	{
		name: 'Non-array sample (boolean)',
		rejected: true,
		samples: true
	},

	{
		name: 'Non-array sample (object)',
		rejected: true,
		samples: { some: 'json' }
	},

	{
		name: 'Non-array sample (function)',
		rejected: true,
		samples: function() { return []; }
	},

	{
		name: 'Non-array sample (null)',
		rejected: true,
		samples: null
	}
];

var returnCode = 0;

tests.forEach(function(t) {
	try {
		var u = mwu.test(t.samples);
		if (!mwu.check(u, t.samples)) throw Error('Check failed');
		if (!t.expected) throw Error('Unexpected results');

		u.forEach(function(o, index) {
			if (t.expected[index] !== o)
				throw Error('Returned results did not match expected results');
		})
	} catch (err) {
		if (!t.rejected) {
			console.error(t.name, err);
			passed = 1;
		}
	}
});

process.exit(returnCode);
<|endoftext|>


<commit_before>var Fx23StringReader = require('../lib/main').stringReader;
var assert = require('assert');

describe('suite 1', function() {
  it("spec 1", function() {
    var str = '   abcdef\r\na b c\nMgen123abc';

    // initialize the reader
    var reader = new Fx23StringReader(str);
    // counts lineIndex and columnIndex during each read operation
    reader.collectLineInfo = true;

    reader.moveToContent();
    assert.equal(reader.peek(), 'a');
    assert.equal(reader.lineIndex, 0);
    assert.equal(reader.columnIndex, 3);
    assert.equal(reader.visibleIndex, 3);
    assert.equal(reader.index, 3);

    assert.equal(reader.collectWhile(function (c) {
        return c != 'e';
    }), 'abcd');
    assert.equal(reader.peek(), 'e');
    assert.equal(reader.lineIndex, 0);
    assert.equal(reader.columnIndex, 7);
    assert.equal(reader.visibleIndex, 7);
    assert.equal(reader.index, 7);

    assert.equal(reader.collectLine(), 'ef');
    assert.equal(reader.peek(), 'a');
    assert.equal(reader.lineIndex, 1);
    assert.equal(reader.columnIndex, 0);
    assert.equal(reader.visibleIndex, 9);
    assert.equal(reader.index, 11);

    reader.skipLine();
    assert.equal(reader.peek(), 'M');
    assert.equal(reader.lineIndex, 2);
    assert.equal(reader.columnIndex, 0);
    assert.equal(reader.visibleIndex, 14);
    assert.equal(reader.index, 17);

    reader.skipWhile(function (c) {
        return isNaN(c);
    });
    assert.equal(reader.peek(), '1');
    assert.equal(reader.lineIndex, 2);
    assert.equal(reader.columnIndex, 4);
    assert.equal(reader.visibleIndex, 18);
    assert.equal(reader.index, 21);

    assert.equal(reader.collectWhile(function (c) {
        return !isNaN(c);
    }), '123');
    assert.equal(reader.peek(), 'a');
    assert.equal(reader.lineIndex, 2);
    assert.equal(reader.columnIndex, 7);
    assert.equal(reader.visibleIndex, 21);
    assert.equal(reader.index, 24);

    reader.mark();
    while (reader.hasNext()) {
        reader.next();
    }
    assert.equal(reader.collect(), 'abc');
    assert.equal(reader.hasNext(), false);
  });
});
<commit_msg>Fix ESLint warnings<commit_after>var Fx23StringReader = require('../lib/main').stringReader;
var assert = require('assert');

describe('suite 1', function() {
    it('spec 1', function() {
        var str = '   abcdef\r\na b c\nMgen123abc';

        // initialize the reader
        var reader = new Fx23StringReader(str);
        // counts lineIndex and columnIndex during each read operation
        reader.collectLineInfo = true;

        reader.moveToContent();
        assert.equal(reader.peek(), 'a');
        assert.equal(reader.lineIndex, 0);
        assert.equal(reader.columnIndex, 3);
        assert.equal(reader.visibleIndex, 3);
        assert.equal(reader.index, 3);

        assert.equal(reader.collectWhile(function (c) {
            return c != 'e';
        }), 'abcd');
        assert.equal(reader.peek(), 'e');
        assert.equal(reader.lineIndex, 0);
        assert.equal(reader.columnIndex, 7);
        assert.equal(reader.visibleIndex, 7);
        assert.equal(reader.index, 7);

        assert.equal(reader.collectLine(), 'ef');
        assert.equal(reader.peek(), 'a');
        assert.equal(reader.lineIndex, 1);
        assert.equal(reader.columnIndex, 0);
        assert.equal(reader.visibleIndex, 9);
        assert.equal(reader.index, 11);

        reader.skipLine();
        assert.equal(reader.peek(), 'M');
        assert.equal(reader.lineIndex, 2);
        assert.equal(reader.columnIndex, 0);
        assert.equal(reader.visibleIndex, 14);
        assert.equal(reader.index, 17);

        reader.skipWhile(function (c) {
            return isNaN(c);
        });
        assert.equal(reader.peek(), '1');
        assert.equal(reader.lineIndex, 2);
        assert.equal(reader.columnIndex, 4);
        assert.equal(reader.visibleIndex, 18);
        assert.equal(reader.index, 21);

        assert.equal(reader.collectWhile(function (c) {
            return !isNaN(c);
        }), '123');
        assert.equal(reader.peek(), 'a');
        assert.equal(reader.lineIndex, 2);
        assert.equal(reader.columnIndex, 7);
        assert.equal(reader.visibleIndex, 21);
        assert.equal(reader.index, 24);

        reader.mark();
        while (reader.hasNext()) {
            reader.next();
        }
        assert.equal(reader.collect(), 'abc');
        assert.equal(reader.hasNext(), false);
    });
});
<|endoftext|>