<commit_before>/* eslint-env mocha */

const mineflayer = require('../')
const vec3 = require('vec3')
const mc = require('minecraft-protocol')
const assert = require('assert')

const { firstVersion, lastVersion } = require('./common/parallel')
mineflayer.testedVersions.forEach((supportedVersion, i) => {
  if (!(i >= firstVersion && i <= lastVersion)) {
    return
  }
  const mcData = require('minecraft-data')(supportedVersion)
  const version = mcData.version
  const Chunk = require('prismarine-chunk')(supportedVersion)

  describe(`mineflayer_internal ${version.minecraftVersion}`, function () {
    this.timeout(10 * 1000)
    let bot
    let server
    beforeEach((done) => {
      server = mc.createServer({
        'online-mode': false,
        version: supportedVersion,
        // 25565 - local server, 25566 - proxy server
        port: 25567
      })
      server.on('listening', () => {
        bot = mineflayer.createBot({
          username: 'player',
          version: supportedVersion,
          port: 25567
        })
        done()
      })
    })
    afterEach((done) => {
      bot.on('end', done)
      server.close()
    })
    it('chat', (done) => {
      bot.once('chat', (username, message) => {
        assert.strictEqual(username, 'gary')
        assert.strictEqual(message, 'hello')
        bot.chat('hi')
      })
      server.on('login', (client) => {
        const message = JSON.stringify({
          translate: 'chat.type.text',
          with: [{
            text: 'gary'
          },
          'hello'
          ]
        })
        client.write('chat', { message, position: 0 })
        client.on('chat', (packet) => {
          assert.strictEqual(packet.message, 'hi')
          done()
        })
      })
    })
    it('entity effects', (done) => {
      bot.once('entityEffect', (entity, effect) => {
        assert.strictEqual(entity.mobType, 'Creeper')
        assert.strictEqual(effect.id, 10)
        assert.strictEqual(effect.amplifier, 1)
        assert.strictEqual(effect.duration, 11)
        done()
      })
      server.on('login', (client) => {
        client.write('spawn_entity_living', {
          entityId: 8, // random
          entityUUID: '00112233-4455-6677-8899-aabbccddeeff',
          type: 50, // creeper
          x: 10,
          y: 11,
          z: 12,
          yaw: 13,
          pitch: 14,
          headPitch: 14,
          velocityX: 16,
          velocityY: 17,
          velocityZ: 18,
          metadata: []
        })
        client.write('entity_effect', {
          entityId: 8,
          effectId: 10,
          amplifier: 1,
          duration: 11,
          hideParticles: false
        })
      })
    })
    it('blockAt', (done) => {
      const pos = vec3(1, 65, 1)
      const goldId = 41
      bot.on('chunkColumnLoad', (columnPoint) => {
        assert.strictEqual(columnPoint.x, 0)
        assert.strictEqual(columnPoint.z, 0)
        assert.strictEqual(bot.blockAt(pos).type, goldId)
        done()
      })
      server.on('login', (client) => {
        client.write('login', {
          entityId: 0,
          levelType: 'fogetaboutit',
          gameMode: 0,
          dimension: 0,
          difficulty: 0,
          maxPlayers: 20,
          reducedDebugInfo: true
        })
        const chunk = new Chunk()

        chunk.setBlockType(pos, goldId)
        client.write('map_chunk', {
          x: 0,
          z: 0,
          groundUp: true,
          bitMap: 0xffff,
          chunkData: chunk.dump(),
          blockEntities: []
        })
      })
    })
    describe('physics', () => {
      const pos = vec3(1, 65, 1)
      const goldId = 41
      it('gravity + land on solid block + jump', (done) => {
        let y = 80
        const terminal = 10
        let hitTerminal = false
        bot.on('move', () => {
          assert.ok(bot.entity.position.y <= y)
          assert.ok(bot.entity.position.y >= pos.y)
          y = bot.entity.position.y
          if (bot.entity.velocity.y > -terminal) hitTerminal = true
          if (bot.entity.velocity.y === 0) {
            assert.ok(hitTerminal)
            assert.ok(bot.entity.onGround)
            assert.ok(bot.entity.position.y, pos.y)
            done()
          } else {
            assert.strictEqual(bot.entity.onGround, false)
          }
        })
        server.on('login', (client) => {
          client.write('login', {
            entityId: 0,
            levelType: 'fogetaboutit',
            gameMode: 0,
            dimension: 0,
            difficulty: 0,
            maxPlayers: 20,
            reducedDebugInfo: true
          })
          const chunk = new Chunk()

          chunk.setBlockType(pos, goldId)
          client.write('map_chunk', {
            x: 0,
            z: 0,
            groundUp: true,
            bitMap: 0xffff,
            chunkData: chunk.dump(),
            blockEntities: []
          })
          client.write('position', {
            x: 1.5,
            y: 80,
            z: 1.5,
            pitch: 0,
            yaw: 0,
            flags: 0,
            teleportId: 0
          })
        })
      })
    })
    describe('entities', () => {
      it('player displayName', (done) => {
        server.on('login', (client) => {
          bot.on('entitySpawn', (entity) => {
            const player = bot.players[entity.username]
            assert.strictEqual(entity.username, player.displayName.toString())
            client.write('player_info', {
              id: 56,
              state: 'play',
              action: 3,
              length: 1,
              data: [{
                UUID: '1-2-3-4',
                name: 'bot5',
                propertiesLength: 0,
                properties: [],
                gamemode: 0,
                ping: 0,
                hasDisplayName: true,
                displayName: '{"text":"wvffle"}'
              }]
            })
          })

          bot.once('playerUpdated', (player) => {
            assert.strictEqual('wvffle', player.displayName.toString())
            client.write('player_info', {
              id: 56,
              state: 'play',
              action: 3,
              length: 1,
              data: [{
                UUID: '1-2-3-4',
                name: 'bot5',
                propertiesLength: 0,
                properties: [],
                gamemode: 0,
                ping: 0,
                hasDisplayName: false
              }]
            })

            bot.once('playerUpdated', (player) => {
              assert.strictEqual(player.entity.username, player.displayName.toString())
              done()
            })
          })

          client.write('player_info', {
            id: 56,
            state: 'play',
            action: 0,
            length: 1,
            data: [{
              UUID: '1-2-3-4',
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false
            }]
          })

          client.write('named_entity_spawn', {
            entityId: 56,
            playerUUID: '1-2-3-4',
            x: 1,
            y: 2,
            z: 3,
            yaw: 0,
            pitch: 0,
            currentItem: -1,
            metadata: []
          })
        })
      })
      it('sets players[player].entity to null upon despawn', (done) => {
        let serverClient = null
        bot.once('entitySpawn', (entity) => {
          serverClient.write('entity_destroy', {
            entityIds: [8]
          })
        })
        bot.once('entityGone', (entity) => {
          assert.strictEqual(bot.players[entity.username], undefined)
          done()
        })
        server.on('login', (client) => {
          serverClient = client

          client.write('player_info', {
            id: 56,
            state: 'play',
            action: 0,
            length: 1,
            data: [{
              UUID: '1-2-3-4',
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false
            }]
          })

          client.write('named_entity_spawn', {
            entityId: 56,
            playerUUID: '1-2-3-4',
            x: 1,
            y: 2,
            z: 3,
            yaw: 0,
            pitch: 0,
            currentItem: -1,
            metadata: []
          })
        })
      })

      it('metadata', (done) => {
        server.on('login', (client) => {
          bot.on('entitySpawn', (entity) => {
            assert.strictEqual(entity.mobType, 'Creeper')

            const lastMeta = entity.metadata
            bot.on('entityUpdate', (entity) => {
              assert.ok('1' in entity.metadata)
              assert.strictEqual(entity.metadata[0], 1)
              assert.strictEqual(entity.metadata[1], lastMeta[1])
              done()
            })

            client.write('entity_metadata', {
              entityId: 8,
              metadata: [
                { type: 0, key: 0, value: 1 }
              ]
            })
          })

          client.write('spawn_entity_living', {
            entityId: 8, // random
            entityUUID: '00112233-4455-6677-8899-aabbccddeeff',
            type: 50, // creeper
            x: 10,
            y: 11,
            z: 12,
            yaw: 13,
            pitch: 14,
            headPitch: 14,
            velocityX: 16,
            velocityY: 17,
            velocityZ: 18,
            metadata: [
              { type: 0, key: 0, value: 0 },
              { type: 0, key: 1, value: 1 }
            ]
          })
        })
      })
    })

    describe('tablist', () => {
      it('handles newlines in header and footer', (done) => {
        const HEADER = 'asd\ndsa'
        const FOOTER = '\nas\nas\nas\n'

        bot._client.on('playerlist_header', (packet) => {
          setImmediate(() => {
            assert.strictEqual(bot.tablist.header.toString(), HEADER)
            assert.strictEqual(bot.tablist.footer.toString(), FOOTER)
            done()
          })
        })

        server.on('login', (client) => {
          client.write('playerlist_header', {
            header: JSON.stringify({ text: '', extra: [{ text: HEADER, color: 'yellow' }] }),
            footer: JSON.stringify({ text: '', extra: [{ text: FOOTER, color: 'yellow' }] })
          })
        })
      })
    })
  })
})
<commit_msg>fix internal test : use entity id<commit_after>/* eslint-env mocha */

const mineflayer = require('../')
const vec3 = require('vec3')
const mc = require('minecraft-protocol')
const assert = require('assert')

const { firstVersion, lastVersion } = require('./common/parallel')
mineflayer.testedVersions.forEach((supportedVersion, i) => {
  if (!(i >= firstVersion && i <= lastVersion)) {
    return
  }
  const mcData = require('minecraft-data')(supportedVersion)
  const version = mcData.version
  const Chunk = require('prismarine-chunk')(supportedVersion)

  describe(`mineflayer_internal ${version.minecraftVersion}`, function () {
    this.timeout(10 * 1000)
    let bot
    let server
    beforeEach((done) => {
      server = mc.createServer({
        'online-mode': false,
        version: supportedVersion,
        // 25565 - local server, 25566 - proxy server
        port: 25567
      })
      server.on('listening', () => {
        bot = mineflayer.createBot({
          username: 'player',
          version: supportedVersion,
          port: 25567
        })
        done()
      })
    })
    afterEach((done) => {
      bot.on('end', done)
      server.close()
    })
    it('chat', (done) => {
      bot.once('chat', (username, message) => {
        assert.strictEqual(username, 'gary')
        assert.strictEqual(message, 'hello')
        bot.chat('hi')
      })
      server.on('login', (client) => {
        const message = JSON.stringify({
          translate: 'chat.type.text',
          with: [{
            text: 'gary'
          },
          'hello'
          ]
        })
        client.write('chat', { message, position: 0 })
        client.on('chat', (packet) => {
          assert.strictEqual(packet.message, 'hi')
          done()
        })
      })
    })
    it('entity effects', (done) => {
      bot.once('entityEffect', (entity, effect) => {
        assert.strictEqual(entity.id, 8)
        assert.strictEqual(effect.id, 10)
        assert.strictEqual(effect.amplifier, 1)
        assert.strictEqual(effect.duration, 11)
        done()
      })
      server.on('login', (client) => {
        client.write('spawn_entity_living', {
          entityId: 8, // random
          entityUUID: '00112233-4455-6677-8899-aabbccddeeff',
          type: 50, // creeper
          x: 10,
          y: 11,
          z: 12,
          yaw: 13,
          pitch: 14,
          headPitch: 14,
          velocityX: 16,
          velocityY: 17,
          velocityZ: 18,
          metadata: []
        })
        client.write('entity_effect', {
          entityId: 8,
          effectId: 10,
          amplifier: 1,
          duration: 11,
          hideParticles: false
        })
      })
    })
    it('blockAt', (done) => {
      const pos = vec3(1, 65, 1)
      const goldId = 41
      bot.on('chunkColumnLoad', (columnPoint) => {
        assert.strictEqual(columnPoint.x, 0)
        assert.strictEqual(columnPoint.z, 0)
        assert.strictEqual(bot.blockAt(pos).type, goldId)
        done()
      })
      server.on('login', (client) => {
        client.write('login', {
          entityId: 0,
          levelType: 'fogetaboutit',
          gameMode: 0,
          dimension: 0,
          difficulty: 0,
          maxPlayers: 20,
          reducedDebugInfo: true
        })
        const chunk = new Chunk()

        chunk.setBlockType(pos, goldId)
        client.write('map_chunk', {
          x: 0,
          z: 0,
          groundUp: true,
          bitMap: 0xffff,
          chunkData: chunk.dump(),
          blockEntities: []
        })
      })
    })
    describe('physics', () => {
      const pos = vec3(1, 65, 1)
      const goldId = 41
      it('gravity + land on solid block + jump', (done) => {
        let y = 80
        const terminal = 10
        let hitTerminal = false
        bot.on('move', () => {
          assert.ok(bot.entity.position.y <= y)
          assert.ok(bot.entity.position.y >= pos.y)
          y = bot.entity.position.y
          if (bot.entity.velocity.y > -terminal) hitTerminal = true
          if (bot.entity.velocity.y === 0) {
            assert.ok(hitTerminal)
            assert.ok(bot.entity.onGround)
            assert.ok(bot.entity.position.y, pos.y)
            done()
          } else {
            assert.strictEqual(bot.entity.onGround, false)
          }
        })
        server.on('login', (client) => {
          client.write('login', {
            entityId: 0,
            levelType: 'fogetaboutit',
            gameMode: 0,
            dimension: 0,
            difficulty: 0,
            maxPlayers: 20,
            reducedDebugInfo: true
          })
          const chunk = new Chunk()

          chunk.setBlockType(pos, goldId)
          client.write('map_chunk', {
            x: 0,
            z: 0,
            groundUp: true,
            bitMap: 0xffff,
            chunkData: chunk.dump(),
            blockEntities: []
          })
          client.write('position', {
            x: 1.5,
            y: 80,
            z: 1.5,
            pitch: 0,
            yaw: 0,
            flags: 0,
            teleportId: 0
          })
        })
      })
    })
    describe('entities', () => {
      it('player displayName', (done) => {
        server.on('login', (client) => {
          bot.on('entitySpawn', (entity) => {
            const player = bot.players[entity.username]
            assert.strictEqual(entity.username, player.displayName.toString())
            client.write('player_info', {
              id: 56,
              state: 'play',
              action: 3,
              length: 1,
              data: [{
                UUID: '1-2-3-4',
                name: 'bot5',
                propertiesLength: 0,
                properties: [],
                gamemode: 0,
                ping: 0,
                hasDisplayName: true,
                displayName: '{"text":"wvffle"}'
              }]
            })
          })

          bot.once('playerUpdated', (player) => {
            assert.strictEqual('wvffle', player.displayName.toString())
            client.write('player_info', {
              id: 56,
              state: 'play',
              action: 3,
              length: 1,
              data: [{
                UUID: '1-2-3-4',
                name: 'bot5',
                propertiesLength: 0,
                properties: [],
                gamemode: 0,
                ping: 0,
                hasDisplayName: false
              }]
            })

            bot.once('playerUpdated', (player) => {
              assert.strictEqual(player.entity.username, player.displayName.toString())
              done()
            })
          })

          client.write('player_info', {
            id: 56,
            state: 'play',
            action: 0,
            length: 1,
            data: [{
              UUID: '1-2-3-4',
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false
            }]
          })

          client.write('named_entity_spawn', {
            entityId: 56,
            playerUUID: '1-2-3-4',
            x: 1,
            y: 2,
            z: 3,
            yaw: 0,
            pitch: 0,
            currentItem: -1,
            metadata: []
          })
        })
      })
      it('sets players[player].entity to null upon despawn', (done) => {
        let serverClient = null
        bot.once('entitySpawn', (entity) => {
          serverClient.write('entity_destroy', {
            entityIds: [8]
          })
        })
        bot.once('entityGone', (entity) => {
          assert.strictEqual(bot.players[entity.username], undefined)
          done()
        })
        server.on('login', (client) => {
          serverClient = client

          client.write('player_info', {
            id: 56,
            state: 'play',
            action: 0,
            length: 1,
            data: [{
              UUID: '1-2-3-4',
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false
            }]
          })

          client.write('named_entity_spawn', {
            entityId: 56,
            playerUUID: '1-2-3-4',
            x: 1,
            y: 2,
            z: 3,
            yaw: 0,
            pitch: 0,
            currentItem: -1,
            metadata: []
          })
        })
      })

      it('metadata', (done) => {
        server.on('login', (client) => {
          bot.on('entitySpawn', (entity) => {
            assert.strictEqual(entity.mobType, 'Creeper')

            const lastMeta = entity.metadata
            bot.on('entityUpdate', (entity) => {
              assert.ok('1' in entity.metadata)
              assert.strictEqual(entity.metadata[0], 1)
              assert.strictEqual(entity.metadata[1], lastMeta[1])
              done()
            })

            client.write('entity_metadata', {
              entityId: 8,
              metadata: [
                { type: 0, key: 0, value: 1 }
              ]
            })
          })

          client.write('spawn_entity_living', {
            entityId: 8, // random
            entityUUID: '00112233-4455-6677-8899-aabbccddeeff',
            type: 50, // creeper
            x: 10,
            y: 11,
            z: 12,
            yaw: 13,
            pitch: 14,
            headPitch: 14,
            velocityX: 16,
            velocityY: 17,
            velocityZ: 18,
            metadata: [
              { type: 0, key: 0, value: 0 },
              { type: 0, key: 1, value: 1 }
            ]
          })
        })
      })
    })

    describe('tablist', () => {
      it('handles newlines in header and footer', (done) => {
        const HEADER = 'asd\ndsa'
        const FOOTER = '\nas\nas\nas\n'

        bot._client.on('playerlist_header', (packet) => {
          setImmediate(() => {
            assert.strictEqual(bot.tablist.header.toString(), HEADER)
            assert.strictEqual(bot.tablist.footer.toString(), FOOTER)
            done()
          })
        })

        server.on('login', (client) => {
          client.write('playerlist_header', {
            header: JSON.stringify({ text: '', extra: [{ text: HEADER, color: 'yellow' }] }),
            footer: JSON.stringify({ text: '', extra: [{ text: FOOTER, color: 'yellow' }] })
          })
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>var journey = require('../lib/journey'),
       vows = require('../../vows/lib/vows');

var sys = require('sys'),
   http = require('http'),
 assert = require('assert'),
    url = require('url');

var mock = {
    mockRequest: function (method, path, headers) {
        var uri = url.parse(path || '/', true);

        return {
            listeners: [],
            method: method,
            headers: headers || { accept: "application/json", "Content-Type":'application/json' },
            url: uri,
            setBodyEncoding: function (e) { this.bodyEncoding = e },
            addListener: function (event, callback) {
                this.listeners.push({ event: event, callback: callback });
                if (event == 'body') {
                    var body = this.body;
                    this.body = '';
                    callback(body);
                } else { callback() }
            }
        };
    },
    mockResponse: function () {
        return {
            body: null,
            finished: false,
            status: 200,
            headers: [],
            sendHeader: function (status, headers) {
                this.status = status;
                this.headers = headers;
            },
            sendBody: function (body) { this.body = body },
            finish: function () { this.finished = true }
        };
    },

    request: function (method, path, headers, body) {
        return journey.server.handler(this.mockRequest(method, path, headers),
                                      this.mockResponse(), body);
    }
}

// Convenience functions to send mock requests
var get  = function (p, h)    { return mock.request('GET',    p, h) }
var del  = function (p, h)    { return mock.request('DELETE', p, h) }
var post = function (p, h, b) { return mock.request('POST',   p, h, b) }
var put  = function (p, h, b) { return mock.request('PUT',    p, h, b) }

var routes = function (map) {
    map.route('GET', 'picnic/fail').to(map.resources["picnic"].fail);
    map.get('home/room').to(map.resources["home"].room);

    map.route('GET', /^(\w+)$/).
        to(function (res, r) { return map.resource(r).index(res) });
    map.route('GET', /^(\w+)\/([0-9]+)$/).
        to(function (res, r, k) { return map.resources[r].get(res, k) });
    map.route('PUT', /^(\w+)\/([0-9]+)$/, { payload: true }).
        to(function (res, r, k) { return map.resources[r].update(res, k) });
    map.route('POST', /^(\w+)$/, { payload: true }).
        to(function (res, r, doc) { return map.resources[r].create(res, doc) });
    map.route('DELETE', /^(\w+)\/([0-9]+)$/).
        to(function (res, r, k) { return map.resources[r].destroy(res, k) });
    map.route('GET', '/').to(function (res) { return map.resources["home"].index(res) });
};

journey.resources = {
    "home": {
        index: function (res) {
            res.send([200, {"Content-Type":"text/html"}, "honey I'm home!"]);
        },
    },
    "picnic": {
        fail: function () {
            throw "fail!";
        }
    },
                                                                                "kitchen": {},
    "recipies": {}
};

journey.ENV = 'test';

vows.tell('Journey', {
    //
    // SUCCESSFUL (2xx)
    //
    "A valid HTTP request": {
        setup: function () { return get('/', { accept: "application/json" }) },

        "returns a 200": function (res) {
            assert.equal(res.status, 200);
            assert.equal(res.body, "honey I'm home!");
            assert.match(res.body, /honey/);
            assert.ok(res.finished);
        }
    },

    "A request with uri parameters": {
        setup: function () {
            // URI parameters get parsed into a javascript object, and are passed to the
            // function handler like so:
            journey.resources["home"].room = function (res, params) {
                res.send([200, {"Content-Type":"text/html"}, JSON.stringify(params)]);
            };
            return get('/home/room?slippers=on&candles=lit');
        },

        "gets parsed into an object": function (res) {
            var home = JSON.parse(res.body);

            assert.equal(home.slippers, 'on');
            assert.equal(home.candles, 'lit');
            assert.equal(res.status, 200);
        }
    },

    "A POST request": {
        setup: function () {
            // Here, we're sending a POST request; the input is parsed into an object, and passed
            // to the function handler as a parameter.
            // We expect Journey to respond with a 201 'Created', if the request was successful.
            journey.resources["kitchen"].create = function (res, input) {
                res.send(201, "cooking-time: " + (input['chicken'].length + input['fries'].length) + 'min');
            };
            return post('/kitchen', null, {"chicken":"roasted", "fries":"golden"})
        },
        "returns a 201": function (res) {
            assert.equal(res.body, 'cooking-time: 13min');
            assert.equal(res.status, 201);
        }
    },

    //
    // Representational State Transfer (REST)
    //
    //journey.resources["recipies"].index = function (params) {
    //
    //};
    //get('/recipies').addCallback(function (res) {
    //    //var doc = JSON.parse(res.body);

    //    //assert.ok(doc.includes("recipies"));
    //    //assert.ok(doc.recipies.is(Array));
    //});

    //
    // CLIENT ERRORS (4xx)
    //

    // Journey being a JSON only server, asking for text/html returns 'Bad Request'
    "A request for text/html": {
        setup: function () {
            return get('/', { accept: "text/html" });
        },
        "returns a 400": function (res) { assert.equal(res.status, 400) }
    },
    // This request won't match any pattern, because of the '@',
    // it's therefore considered invalid
    "A request for text/html": {
        setup: function () {
            return get('/hello/@');
        },
        "returns a 400": function (res) {
            assert.equal(res.status, 400);
        }
    },
    // Trying to access an unknown resource will result in a 404 'Not Found',
    // as long as the uri format is valid
    "A request for an unknown resource": {
        setup: function () {
            return get('/unknown');
        },
        "returns a 404": function (res) {
            assert.equal(res.status, 404);
        }
    },
    // Here, we're trying to use the DELETE method on /
    // Of course, we haven't allowed this, so Journey responds with a
    // 405 'Method not Allowed', and returns the allowed methods
    "A request with an unsupported method": {
        setup: function () {
            return del('/');
        },
        "returns a 405": function (res) {
            assert.equal(res.status, 405);
            assert.equal(res.headers.allow, 'GET');
        }
    },

    //
    // SERVER ERRORS (5xx)
    //

    // The code in `picnic.fail` throws an exception, so we return a
    // 500 'Internal Server Error'
    "A request to a controller with an error in it": {
        setup: function () {
            return get('/picnic/fail');
        },
        "returns a 500": function (res) {
            assert.equal(res.status, 500);
        }
    }
});

journey.router.draw(routes);

<commit_msg>whitespace<commit_after>var journey = require('../lib/journey'),
       vows = require('../../vows/lib/vows');

var sys = require('sys'),
   http = require('http'),
 assert = require('assert'),
    url = require('url');

var mock = {
    mockRequest: function (method, path, headers) {
        var uri = url.parse(path || '/', true);

        return {
            listeners: [],
            method: method,
            headers: headers || { accept: "application/json", "Content-Type":'application/json' },
            url: uri,
            setBodyEncoding: function (e) { this.bodyEncoding = e },
            addListener: function (event, callback) {
                this.listeners.push({ event: event, callback: callback });
                if (event == 'body') {
                    var body = this.body;
                    this.body = '';
                    callback(body);
                } else { callback() }
            }
        };
    },
    mockResponse: function () {
        return {
            body: null,
            finished: false,
            status: 200,
            headers: [],
            sendHeader: function (status, headers) {
                this.status = status;
                this.headers = headers;
            },
            sendBody: function (body) { this.body = body },
            finish: function () { this.finished = true }
        };
    },

    request: function (method, path, headers, body) {
        return journey.server.handler(this.mockRequest(method, path, headers),
                                      this.mockResponse(), body);
    }
}

// Convenience functions to send mock requests
var get  = function (p, h)    { return mock.request('GET',    p, h) }
var del  = function (p, h)    { return mock.request('DELETE', p, h) }
var post = function (p, h, b) { return mock.request('POST',   p, h, b) }
var put  = function (p, h, b) { return mock.request('PUT',    p, h, b) }

var routes = function (map) {
    map.route('GET', 'picnic/fail').to(map.resources["picnic"].fail);
    map.get('home/room').to(map.resources["home"].room);

    map.route('GET', /^(\w+)$/).
        to(function (res, r) { return map.resource(r).index(res) });
    map.route('GET', /^(\w+)\/([0-9]+)$/).
        to(function (res, r, k) { return map.resources[r].get(res, k) });
    map.route('PUT', /^(\w+)\/([0-9]+)$/, { payload: true }).
        to(function (res, r, k) { return map.resources[r].update(res, k) });
    map.route('POST', /^(\w+)$/, { payload: true }).
        to(function (res, r, doc) { return map.resources[r].create(res, doc) });
    map.route('DELETE', /^(\w+)\/([0-9]+)$/).
        to(function (res, r, k) { return map.resources[r].destroy(res, k) });
    map.route('GET', '/').to(function (res) { return map.resources["home"].index(res) });
};

journey.resources = {
    "home": {
        index: function (res) {
            res.send([200, {"Content-Type":"text/html"}, "honey I'm home!"]);
        },
    },
    "picnic": {
        fail: function () {
            throw "fail!";
        }
    },
    "kitchen": {},
    "recipies": {}
};

journey.ENV = 'test';

vows.tell('Journey', {
    //
    // SUCCESSFUL (2xx)
    //
    "A valid HTTP request": {
        setup: function () { return get('/', { accept: "application/json" }) },

        "returns a 200": function (res) {
            assert.equal(res.status, 200);
            assert.equal(res.body, "honey I'm home!");
            assert.match(res.body, /honey/);
            assert.ok(res.finished);
        }
    },

    "A request with uri parameters": {
        setup: function () {
            // URI parameters get parsed into a javascript object, and are passed to the
            // function handler like so:
            journey.resources["home"].room = function (res, params) {
                res.send([200, {"Content-Type":"text/html"}, JSON.stringify(params)]);
            };
            return get('/home/room?slippers=on&candles=lit');
        },

        "gets parsed into an object": function (res) {
            var home = JSON.parse(res.body);

            assert.equal(home.slippers, 'on');
            assert.equal(home.candles, 'lit');
            assert.equal(res.status, 200);
        }
    },

    "A POST request": {
        setup: function () {
            // Here, we're sending a POST request; the input is parsed into an object, and passed
            // to the function handler as a parameter.
            // We expect Journey to respond with a 201 'Created', if the request was successful.
            journey.resources["kitchen"].create = function (res, input) {
                res.send(201, "cooking-time: " + (input['chicken'].length + input['fries'].length) + 'min');
            };
            return post('/kitchen', null, {"chicken":"roasted", "fries":"golden"})
        },
        "returns a 201": function (res) {
            assert.equal(res.body, 'cooking-time: 13min');
            assert.equal(res.status, 201);
        }
    },

    //
    // Representational State Transfer (REST)
    //
    //journey.resources["recipies"].index = function (params) {
    //
    //};
    //get('/recipies').addCallback(function (res) {
    //    //var doc = JSON.parse(res.body);

    //    //assert.ok(doc.includes("recipies"));
    //    //assert.ok(doc.recipies.is(Array));
    //});

    //
    // CLIENT ERRORS (4xx)
    //

    // Journey being a JSON only server, asking for text/html returns 'Bad Request'
    "A request for text/html": {
        setup: function () {
            return get('/', { accept: "text/html" });
        },
        "returns a 400": function (res) { assert.equal(res.status, 400) }
    },
    // This request won't match any pattern, because of the '@',
    // it's therefore considered invalid
    "A request for text/html": {
        setup: function () {
            return get('/hello/@');
        },
        "returns a 400": function (res) {
            assert.equal(res.status, 400);
        }
    },
    // Trying to access an unknown resource will result in a 404 'Not Found',
    // as long as the uri format is valid
    "A request for an unknown resource": {
        setup: function () {
            return get('/unknown');
        },
        "returns a 404": function (res) {
            assert.equal(res.status, 404);
        }
    },
    // Here, we're trying to use the DELETE method on /
    // Of course, we haven't allowed this, so Journey responds with a
    // 405 'Method not Allowed', and returns the allowed methods
    "A request with an unsupported method": {
        setup: function () {
            return del('/');
        },
        "returns a 405": function (res) {
            assert.equal(res.status, 405);
            assert.equal(res.headers.allow, 'GET');
        }
    },

    //
    // SERVER ERRORS (5xx)
    //

    // The code in `picnic.fail` throws an exception, so we return a
    // 500 'Internal Server Error'
    "A request to a controller with an error in it": {
        setup: function () {
            return get('/picnic/fail');
        },
        "returns a 500": function (res) {
            assert.equal(res.status, 500);
        }
    }
});

journey.router.draw(routes);

<|endoftext|>


<commit_before>
/*!
 * socket.io-node
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Test dependencies.
 */

var sio = require('socket.io')
  , http = require('http')
  , should = require('./common')
  , ports = 15100;

/**
 * Test.
 */

module.exports = {

  'test setting and getting a configuration flag': function (done) {
    done();
  },

  'test enabling and disabling a configuration flag': function (done) {
    var port = ++ports
      , io = sio.listen(http.createServer());

    io.enable('flag');
    io.enabled('flag').should.be.true;
    io.disabled('flag').should.be.false;

    io.disable('flag');
    var port = ++ports
      , io = sio.listen(http.createServer());

    io.configure(function () {
      io.set('a', 'b');
      io.enable('tobi');
    });

    io.get('a').should.eql('b');
    io.enabled('tobi').should.be.true;

    done();
  },

  'test configuration callbacks with envs': function (done) {
    var port = ++ports
      , io = sio.listen(http.createServer());

    process.env.NODE_ENV = 'development';

    io.configure('production', function () {
      io.set('ferret', 'tobi');
    });

    io.configure('development', function () {
      io.set('ferret', 'jane');
    });

    io.get('ferret').should.eql('jane');
    done();
  },

  'test that normal requests are still served': function (done) {
    var server = http.createServer(function (req, res) {
      res.writeHead(200);
      res.end('woot');
    });

    var io = sio.listen(server)
      , port = ++ports
      , cl = client(port);

    server.listen(ports);

    cl.get('/socket.io', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.eql('Welcome to socket.io.');

      cl.get('/woot', function (res, data) {
        cl.end();
        server.close();
        done();
      });
    });
  },

  'test that the client is served': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    cl.get('/socket.io/socket.io.js', function (res, data) {
      res.headers['content-type'].should.eql('application/javascript');
      res.headers['content-length'].should.be.match(/([0-9]+)/);
      res.headers.etag.should.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/);

      data.should.match(/XMLHttpRequest/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test that the cached client is served': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    cl.get('/socket.io/socket.io.js', function (res, data) {
      res.headers['content-type'].should.eql('application/javascript');
      res.headers['content-length'].should.be.match(/([0-9]+)/);
      res.headers.etag.should.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/);

      data.should.match(/XMLHttpRequest/);
      io.client.should.match(/XMLHttpRequest/);

      cl.get('/socket.io/socket.io.js', function (res, data) {
        res.headers['content-type'].should.eql('application/javascript');
        res.headers['content-length'].should.be.match(/([0-9]+)/);
        res.headers.etag.should.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/);

        data.should.match(/XMLHttpRequest/);

        cl.end();
        io.server.close();
        done();
      });
    });
  },

  'test that you can serve custom clients': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('browser client', 'custom_client');
      io.set('browser client etag', '1.0');
    });

    cl.get('/socket.io/socket.io.js', function (res, data) {
      res.headers['content-type'].should.eql('application/javascript');
      res.headers['content-length'].should.eql(13);
      res.headers.etag.should.eql('1.0');

      data.should.eql('custom_client');

      cl.end();
      io.server.close();
      done();
    });
  },

  'test handshake': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+):([0-9]+)?:([0-9]+)?:(.+)/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test handshake with unsupported protocol version': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    cl.get('/socket.io/-1/', function (res, data) {
      res.statusCode.should.eql(500);
      data.should.match(/Protocol version not supported/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test authorization failure in handshake': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      function auth (data, fn) {
        fn(null, false);
      };

      io.set('authorization', auth);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(403);
      data.should.match(/handshake unauthorized/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test a handshake error': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      function auth (data, fn) {
        fn(new Error);
      };

      io.set('authorization', auth);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(500);
      data.should.match(/handshake error/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test limiting the supported transports for a manager': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('transports', ['tobi', 'jane']);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+):([0-9]+)?:([0-9]+)?:tobi,jane/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test setting a custom close timeout': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('close timeout', 66);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+):([0-9]+)?:66?:(.*)/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test setting a custom heartbeat timeout': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('heartbeat timeout', 33);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+):33:([0-9]+)?:(.*)/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test disabling timeouts': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('heartbeat timeout', null);
      io.set('close timeout', '');
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+)::?:(.*)/);

      cl.end();
      io.server.close();
      done();
    });
  }

};
<commit_msg>Added Manager#configure callbacks scope test.<commit_after>
/*!
 * socket.io-node
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Test dependencies.
 */

var sio = require('socket.io')
  , http = require('http')
  , should = require('./common')
  , ports = 15100;

/**
 * Test.
 */

module.exports = {

  'test setting and getting a configuration flag': function (done) {
    done();
  },

  'test enabling and disabling a configuration flag': function (done) {
    var port = ++ports
      , io = sio.listen(http.createServer());

    io.enable('flag');
    io.enabled('flag').should.be.true;
    io.disabled('flag').should.be.false;

    io.disable('flag');
    var port = ++ports
      , io = sio.listen(http.createServer());

    io.configure(function () {
      io.set('a', 'b');
      io.enable('tobi');
    });

    io.get('a').should.eql('b');
    io.enabled('tobi').should.be.true;

    done();
  },

  'test configuration callbacks with envs': function (done) {
    var port = ++ports
      , io = sio.listen(http.createServer());

    process.env.NODE_ENV = 'development';

    io.configure('production', function () {
      io.set('ferret', 'tobi');
    });

    io.configure('development', function () {
      io.set('ferret', 'jane');
    });

    io.get('ferret').should.eql('jane');
    done();
  },

  'test configuration callbacks conserve scope': function (done) {
    var port = ++ports
      , io = sio.listen(http.createServer())
      , calls = 0;

    process.env.NODE_ENV = 'development';

    io.configure(function () {
      this.should.eql(io);
      calls++;
    });

    io.configure('development', function () {
      this.should.eql(io);
      calls++;
    });

    calls.should.eql(2);
    done();
  },

  'test that normal requests are still served': function (done) {
    var server = http.createServer(function (req, res) {
      res.writeHead(200);
      res.end('woot');
    });

    var io = sio.listen(server)
      , port = ++ports
      , cl = client(port);

    server.listen(ports);

    cl.get('/socket.io', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.eql('Welcome to socket.io.');

      cl.get('/woot', function (res, data) {
        cl.end();
        server.close();
        done();
      });
    });
  },

  'test that the client is served': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    cl.get('/socket.io/socket.io.js', function (res, data) {
      res.headers['content-type'].should.eql('application/javascript');
      res.headers['content-length'].should.be.match(/([0-9]+)/);
      res.headers.etag.should.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/);

      data.should.match(/XMLHttpRequest/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test that the cached client is served': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    cl.get('/socket.io/socket.io.js', function (res, data) {
      res.headers['content-type'].should.eql('application/javascript');
      res.headers['content-length'].should.be.match(/([0-9]+)/);
      res.headers.etag.should.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/);

      data.should.match(/XMLHttpRequest/);
      io.client.should.match(/XMLHttpRequest/);

      cl.get('/socket.io/socket.io.js', function (res, data) {
        res.headers['content-type'].should.eql('application/javascript');
        res.headers['content-length'].should.be.match(/([0-9]+)/);
        res.headers.etag.should.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/);

        data.should.match(/XMLHttpRequest/);

        cl.end();
        io.server.close();
        done();
      });
    });
  },

  'test that you can serve custom clients': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('browser client', 'custom_client');
      io.set('browser client etag', '1.0');
    });

    cl.get('/socket.io/socket.io.js', function (res, data) {
      res.headers['content-type'].should.eql('application/javascript');
      res.headers['content-length'].should.eql(13);
      res.headers.etag.should.eql('1.0');

      data.should.eql('custom_client');

      cl.end();
      io.server.close();
      done();
    });
  },

  'test handshake': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+):([0-9]+)?:([0-9]+)?:(.+)/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test handshake with unsupported protocol version': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    cl.get('/socket.io/-1/', function (res, data) {
      res.statusCode.should.eql(500);
      data.should.match(/Protocol version not supported/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test authorization failure in handshake': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      function auth (data, fn) {
        fn(null, false);
      };

      io.set('authorization', auth);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(403);
      data.should.match(/handshake unauthorized/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test a handshake error': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      function auth (data, fn) {
        fn(new Error);
      };

      io.set('authorization', auth);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(500);
      data.should.match(/handshake error/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test limiting the supported transports for a manager': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('transports', ['tobi', 'jane']);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+):([0-9]+)?:([0-9]+)?:tobi,jane/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test setting a custom close timeout': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('close timeout', 66);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+):([0-9]+)?:66?:(.*)/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test setting a custom heartbeat timeout': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('heartbeat timeout', 33);
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+):33:([0-9]+)?:(.*)/);

      cl.end();
      io.server.close();
      done();
    });
  },

  'test disabling timeouts': function (done) {
    var port = ++ports
      , io = sio.listen(port)
      , cl = client(port);

    io.configure(function () {
      io.set('heartbeat timeout', null);
      io.set('close timeout', '');
    });

    cl.get('/socket.io/{protocol}/', function (res, data) {
      res.statusCode.should.eql(200);
      data.should.match(/([^:]+)::?:(.*)/);

      cl.end();
      io.server.close();
      done();
    });
  }

};
<|endoftext|>


<commit_before>var opbeat = require('../');
var utils = require('../lib/utils');

describe('utils', function () {
  describe('.validStack()', function () {
    it('should return true if the stack is valid', function () {
      var err = new Error();
      err.stack; // Error.prepareStackTrace is only called when stack is accessed, so access it
      utils.validStack(err.structuredStackTrace).should.equal(true);
    });

    it('should return false if the stack isn\'t valid', function () {
      utils.validStack([]).should.equal(false);
    });
  });
});
<commit_msg>Add test of utils.parseStack()<commit_after>var opbeat = require('../');
var utils = require('../lib/utils');

describe('utils', function () {
  describe('.validStack()', function () {
    it('should return true if the stack is valid', function () {
      var err = new Error();
      err.stack; // Error.prepareStackTrace is only called when stack is accessed, so access it
      utils.validStack(err.structuredStackTrace).should.equal(true);
    });

    it('should return false if the stack isn\'t valid', function () {
      utils.validStack([]).should.equal(false);
    });
  });

  describe('.parseStack()', function () {
    it('should call the callback with an array of stack frames', function (done) {
      var err = new Error();
      err.stack; // Error.prepareStackTrace is only called when stack is accessed, so access it
      utils.parseStack(err.structuredStackTrace, function (frames) {
        frames.should.be.an.instanceOf(Array);
        frames.length.should.not.equal(0);
        frames[0].should.have.ownProperty('filename');
        frames[0].should.have.ownProperty('function');
        frames[0].should.have.ownProperty('lineno');
        frames[0].should.have.ownProperty('in_app');
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>describe('Pagelet', function () {
  'use strict';

  var Pagelet = require('../').extend({ name: 'test' })
    , Temper = require('temper')
    , Pipe = require('bigpipe')
    , assume = require('assume')
    , React = require('react')
    , server = require('http').createServer()
    , pagelet, P;

  //
  // A lazy mans temper, we just want ignore all temper actions sometimes
  // because our pagelet is not exported using `.on(module)`
  //
  var temper = new Temper
    , pipe = new Pipe(server);

  beforeEach(function () {
    P = Pagelet.extend({
      directory: __dirname,
      view: 'fixtures/view.html',
      css: 'fixtures/style.css',
      js: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min.js',
      dependencies: [
        'http://code.jquery.com/jquery-2.0.0.js',
        'fixtures/custom.js'
      ]
    });

    pagelet = new P({ temper: temper });
  });

  afterEach(function each() {
    pagelet = null;
  });

  it('rendering is asynchronous', function (done) {
    pagelet.get(pagelet.emits('called'));

    // Listening only till after the event is potentially emitted, will ensure
    // callbacks are called asynchronously by pagelet.render.
    pagelet.on('called', done);
  });

  it('can have reference to temper', function () {
    pagelet = new P({ temper: temper });
    var property = Object.getOwnPropertyDescriptor(pagelet, '_temper');

    assume(pagelet._temper).to.be.an('object');
    assume(property.writable).to.equal(true);
    assume(property.enumerable).to.equal(true);
    assume(property.configurable).to.equal(true);
  });

  it('can have reference to pipe instance', function () {
    pagelet = new P({ pipe: pipe });
    var property = Object.getOwnPropertyDescriptor(pagelet, '_pipe');

    assume(pagelet._pipe).to.be.an('object');
    assume(pagelet._pipe).to.be.instanceof(Pipe);
    assume(property.writable).to.equal(true);
    assume(property.enumerable).to.equal(true);
    assume(property.configurable).to.equal(true);
  });

  describe('.on', function () {
    it('sets the pathname', function () {
      var pagelet = Pagelet.extend({});
      assume(pagelet.prototype.directory).to.equal('');

      pagelet.prototype.directory = 'foo';
      assume(pagelet.prototype.directory).to.equal('foo');

      pagelet.on(module);

      assume(pagelet.prototype.directory).to.be.a('string');
      assume(pagelet.prototype.directory).to.equal(__dirname);
    });

    it('resolves the view', function () {
      assume(P.prototype.view).to.equal('fixtures/view.html');

      P.on(module);
      assume(P.prototype.view).to.equal(__dirname +'/fixtures/view.html');
    });

    it('resolves the `error` view');
  });

  describe('.discover', function () {
    it('emits discover and returns immediatly if the parent pagelet has no children', function (done) {
      pagelet.once('discover', done);
      pagelet.discover();
    });

    /* Disabled for now, might return before 1.0.0
    it('initializes pagelets by allocating from the Pagelet.freelist', function (done) {
      var Hero = require(__dirname + '/fixtures/pagelets/hero').optimize(app.temper)
        , Faq = require(__dirname + '/fixtures/pages/faq').extend({ pagelets: [ Hero ] })
        , pageletFreelist = sinon.spy(Hero.freelist, 'alloc')
        , faq = new Faq(app);

      faq.once('discover', function () {
        assume(pageletFreelist).to.be.calledOnce;
        done();
      });

      faq.discover();
    });*/
  });

  describe('.length', function () {
    it('is a getter that returns the childrens length', function () {
      pagelet._children = [ 1, 2, 3 ];
      assume(pagelet.length).to.equal(3);
    });
  });

  describe('.template', function () {
    it('is a function', function () {
      assume(Pagelet.prototype.template).to.be.a('function');
      assume(P.prototype.template).to.be.a('function');
      assume(Pagelet.prototype.template).to.equal(P.prototype.template);
      assume(pagelet.template).to.equal(P.prototype.template);
    });

    it('returns compiled server template from Temper by path', function () {
      var result = pagelet.template(__dirname + '/fixtures/view.html', {
        test: 'data'
      });

      assume(result).to.be.a('string');
      assume(result).to.equal('
Some data fixture
');
    });

    it('returns compiled server React template for jsx templates', function () {
      var result = pagelet.template(__dirname + '/fixtures/view.jsx', {
        Component: React.createClass({
          render: function () {
            return (
              React.createElement('span', null, 'some text')
            )
          }
        }),
        test: 'data'
      });

      assume(result).to.be.a('object');
      assume(React.isValidElement(result)).is.true();
    });

    it('defaults to the pagelets view if no path is provided', function() {
      var result = new (P.extend().on(module))({ temper: temper }).template({
        test: 'data'
      });

      assume(result).to.be.a('string');
      assume(result).to.equal('
Some data fixture
');
    });
  });

  describe('.children', function () {
    it('is a function', function () {
      assume(Pagelet.children).to.be.a('function');
      assume(P.children).to.be.a('function');
      assume(Pagelet.children).to.equal(P.children);
    });

    it('returns an array', function () {
      var one = P.children()
        , recur = P.extend({
            pagelets: {
              child: P.extend({ name: 'child' })
            }
          }).children('this one');

      assume(one).to.be.an('array');
      assume(one.length).to.equal(0);

      assume(recur).to.be.an('array');
      assume(recur.length).to.equal(1);
    });

    it('will only return children of the pagelet', function () {
      var single = P.children();

      assume(single).to.be.an('array');
      assume(single.length).to.equal(0);
    });

    it('does recursive pagelet discovery', function () {
      var recur = P.extend({
        pagelets: {
          child: P.extend({
            name: 'child' ,
            pagelets: {
              another: P.extend({ name: 'another' })
            }
          }),
        }
      }).children('multiple');

      assume(recur).is.an('array');
      assume(recur.length).to.equal(2);
      assume(recur[0].prototype.name).to.equal('child');
      assume(recur[1].prototype.name).to.equal('another');
    });

    it('sets the pagelets parent name on `_parent`', function () {
      var recur = P.extend({
        pagelets: {
          child: P.extend({
            name: 'child'
          })
        }
      }).children('parental');

      assume(recur[0].prototype._parent).to.equal('parental');
    });
  });

  describe('.optimize', function () {
    it('should prepare an async call stack');
    it('should provide optimizer with Pagelet reference if no transform:before event');
  });
});
<commit_msg>[test] Restore tests<commit_after>describe('Pagelet', function () {
  'use strict';

  var Pagelet = require('../').extend({ name: 'test' })
    , Temper = require('temper')
    , Pipe = require('bigpipe')
    , assume = require('assume')
    , React = require('react')
    , server = require('http').createServer()
    , pagelet, P;

  //
  // A lazy mans temper, we just want ignore all temper actions sometimes
  // because our pagelet is not exported using `.on(module)`
  //
  var temper = new Temper
    , pipe = new Pipe(server);

  beforeEach(function () {
    P = Pagelet.extend({
      directory: __dirname,
      view: 'fixtures/view.html',
      css: 'fixtures/style.css',
      js: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min.js',
      dependencies: [
        'http://code.jquery.com/jquery-2.0.0.js',
        'fixtures/custom.js'
      ]
    });

    pagelet = new P({ temper: temper });
  });

  afterEach(function each() {
    pagelet = null;
  });

  it('rendering is asynchronous', function (done) {
    pagelet.get(pagelet.emits('called'));

    // Listening only till after the event is potentially emitted, will ensure
    // callbacks are called asynchronously by pagelet.render.
    pagelet.on('called', done);
  });

  it('can have reference to temper', function () {
    pagelet = new P({ temper: temper });
    var property = Object.getOwnPropertyDescriptor(pagelet, '_temper');

    assume(pagelet._temper).to.be.an('object');
    assume(property.writable).to.equal(true);
    assume(property.enumerable).to.equal(false);
    assume(property.configurable).to.equal(true);
  });

  it('can have reference to pipe instance', function () {
    pagelet = new P({ pipe: pipe });
    var property = Object.getOwnPropertyDescriptor(pagelet, '_bigpipe');

    assume(pagelet._bigpipe).to.be.an('object');
    assume(pagelet._bigpipe).to.be.instanceof(Pipe);
    assume(property.writable).to.equal(true);
    assume(property.enumerable).to.equal(false);
    assume(property.configurable).to.equal(true);
  });

  describe('.on', function () {
    it('sets the pathname', function () {
      var pagelet = Pagelet.extend({});
      assume(pagelet.prototype.directory).to.equal('');

      pagelet.prototype.directory = 'foo';
      assume(pagelet.prototype.directory).to.equal('foo');

      pagelet.on(module);

      assume(pagelet.prototype.directory).to.be.a('string');
      assume(pagelet.prototype.directory).to.equal(__dirname);
    });

    it('resolves the view', function () {
      assume(P.prototype.view).to.equal('fixtures/view.html');

      P.on(module);
      assume(P.prototype.view).to.equal(__dirname +'/fixtures/view.html');
    });

    it('resolves the `error` view');
  });

  describe('.discover', function () {
    it('emits discover and returns immediatly if the parent pagelet has no children', function (done) {
      pagelet.once('discover', done);
      pagelet.discover();
    });

    /* Disabled for now, might return before 1.0.0
    it('initializes pagelets by allocating from the Pagelet.freelist', function (done) {
      var Hero = require(__dirname + '/fixtures/pagelets/hero').optimize(app.temper)
        , Faq = require(__dirname + '/fixtures/pages/faq').extend({ pagelets: [ Hero ] })
        , pageletFreelist = sinon.spy(Hero.freelist, 'alloc')
        , faq = new Faq(app);

      faq.once('discover', function () {
        assume(pageletFreelist).to.be.calledOnce;
        done();
      });

      faq.discover();
    });*/
  });

  describe('.length', function () {
    it('is a getter that returns the childrens length', function () {
      pagelet._children = [ 1, 2, 3 ];
      assume(pagelet.length).to.equal(3);
    });
  });

  describe('.template', function () {
    it('is a function', function () {
      assume(Pagelet.prototype.template).to.be.a('function');
      assume(P.prototype.template).to.be.a('function');
      assume(Pagelet.prototype.template).to.equal(P.prototype.template);
      assume(pagelet.template).to.equal(P.prototype.template);
    });

    it('returns compiled server template from Temper by path', function () {
      var result = pagelet.template(__dirname + '/fixtures/view.html', {
        test: 'data'
      });

      assume(result).to.be.a('string');
      assume(result).to.equal('
Some data fixture
');
    });

    it('returns compiled server React template for jsx templates', function () {
      var result = pagelet.template(__dirname + '/fixtures/view.jsx', {
        Component: React.createClass({
          render: function () {
            return (
              React.createElement('span', null, 'some text')
            )
          }
        }),
        test: 'data'
      });

      assume(result).to.be.a('object');
      assume(React.isValidElement(result)).is.true();
    });

    it('defaults to the pagelets view if no path is provided', function() {
      var result = new (P.extend().on(module))({ temper: temper }).template({
        test: 'data'
      });

      assume(result).to.be.a('string');
      assume(result).to.equal('
Some data fixture
');
    });
  });

  describe('.children', function () {
    it('is a function', function () {
      assume(Pagelet.children).to.be.a('function');
      assume(P.children).to.be.a('function');
      assume(Pagelet.children).to.equal(P.children);
    });

    it('returns an array', function () {
      var one = P.children()
        , recur = P.extend({
            pagelets: {
              child: P.extend({ name: 'child' })
            }
          }).children('this one');

      assume(one).to.be.an('array');
      assume(one.length).to.equal(0);

      assume(recur).to.be.an('array');
      assume(recur.length).to.equal(1);
    });

    it('will only return children of the pagelet', function () {
      var single = P.children();

      assume(single).to.be.an('array');
      assume(single.length).to.equal(0);
    });

    it('does recursive pagelet discovery', function () {
      var recur = P.extend({
        pagelets: {
          child: P.extend({
            name: 'child' ,
            pagelets: {
              another: P.extend({ name: 'another' })
            }
          }),
        }
      }).children('multiple');

      assume(recur).is.an('array');
      assume(recur.length).to.equal(2);
      assume(recur[0].prototype.name).to.equal('child');
      assume(recur[1].prototype.name).to.equal('another');
    });

    it('sets the pagelets parent name on `_parent`', function () {
      var recur = P.extend({
        pagelets: {
          child: P.extend({
            name: 'child'
          })
        }
      }).children('parental');

      assume(recur[0].prototype._parent).to.equal('parental');
    });
  });

  describe('.optimize', function () {
    it('should prepare an async call stack');
    it('should provide optimizer with Pagelet reference if no transform:before event');
  });
});
<|endoftext|>


<commit_before>// jscs:disable maximumLineLength
'use strict';

const assert = require('chai').assert;
const sinon = require('sinon');
const robotto = require('../src/robotto');
const fake = require('./fake');

let sandbox = sinon.sandbox.create();
let coolUrl = 'http://my-cool-domain.com/blog-post/1';
let coolRobot = 'http://my-cool-domain.com/robots.txt';

describe('robotto', () => {
    afterEach(() => {
        sandbox.restore();
    });

    describe('_getRobotsUrl', () => {
        it('returns robots.txt url for given host', () => {
            let robotsUrl = robotto._getRobotsUrl(coolUrl);
            assert.deepEqual(robotsUrl, coolRobot);
        });
    });

    describe('fetch', () => {
        beforeEach(() => {
            sandbox.spy(robotto, '_getRobotsUrl');
            sandbox.stub(robotto, '_request')
                .callsArgWith(1, null, fake.response(), fake.robots());
        });

        it('should not break if no callback is passed', () => {
            assert.doesNotThrow(() => {
                robotto.fetch(coolUrl);
            }, 'callback is not a function');
        });

        it('should call _getRobotsUrl', (done) => {
            robotto.fetch(coolUrl, () => {
                sinon.assert.calledWith(robotto._getRobotsUrl, coolUrl);
                done();
            });
        });

        it('should call _request', (done) => {
            robotto.fetch(coolUrl, () => {
                sinon.assert.calledWith(robotto._request, coolRobot);
                done();
            });
        });

        it('should callback with an error if request fails', (done) => {
            robotto._request.restore();
            sandbox.stub(robotto, '_request')
                .callsArgWith(1, new Error('fake request error'));

            robotto.fetch(coolUrl, (err) => {
                assert.deepEqual(err.message, 'fake request error');
                done();
            });
        });

        it('should callback with an error if status code is not 200', (done) => {
            robotto._request.restore();
            sandbox.stub(robotto, '_request')
                .callsArgWith(1, null, {statusCode: 404});

            robotto.fetch(coolUrl, (err) => {
                assert.deepEqual(err.message, `Could not fetch robots.txt from ${coolUrl}. Server response code: 404`);
                done();
            });
        });

        it('should callback with robots.txt content', (done) => {
            robotto.fetch(coolUrl, (err, robots) => {
                assert.notOk(err);
                assert.deepEqual(robots, fake.robots());
                done();
            });
        });
    });

    describe('parse', () => {
        it('should undertand comments', () => {
            let robotsFile = [
                '# comment 1',
                'User-agent: 007 # comment 2'
            ].join('\n');
            let comments = ['comment 1', 'comment 2'];

            assert.deepEqual(robotto.parse(robotsFile).comments, comments);
        });

        it('should index by User-agent', () => {
            let robotsFile = [
                '# comment 1',
                'User-agent: 007 # comment 2',
                'Allow: /kill/',
                'User-agent: Agent 47',
                'Disallow: /nothing/'
            ].join('\n');

            assert.property(robotto.parse(robotsFile), '007');
            assert.property(robotto.parse(robotsFile), 'Agent 47');
        });

        it('should put allow entries in their respective User-agents', () => {
            let robotsFile = [
                '# comment 1',
                'User-agent: 007 # comment 2',
                'Allow: /kill/',
                'User-agent: Agent 47',
                'Allow: /everything/'
            ].join('\n');
            let rules = robotto.parse(robotsFile);

            assert.deepEqual(rules['007'].allow, ['/kill/']);
            assert.deepEqual(rules['Agent 47'].allow, ['/everything/']);
        });

        it('should put disallow entries in their respective User-agents', () => {
            let robotsFile = [
                '# comment 1',
                'User-agent: 007 # comment 2',
                'Disallow: /betrayal/',
                'User-agent: Agent 47',
                'Disallow: /nothing/'
            ].join('\n');
            let rules = robotto.parse(robotsFile);

            assert.deepEqual(rules['007'].disallow, ['/betrayal/']);
            assert.deepEqual(rules['Agent 47'].disallow, ['/nothing/']);
        });

        it('should actually parse a robots.txt file', () => {
            assert.deepEqual(robotto.parse(fake.robots()), fake.rules());
        });
    });
});
<commit_msg>Fixing typo on tests file<commit_after>// jscs:disable maximumLineLength
'use strict';

const assert = require('chai').assert;
const sinon = require('sinon');
const robotto = require('../src/robotto');
const fake = require('./fake');

let sandbox = sinon.sandbox.create();
let coolUrl = 'http://my-cool-domain.com/blog-post/1';
let coolRobot = 'http://my-cool-domain.com/robots.txt';

describe('robotto', () => {
    afterEach(() => {
        sandbox.restore();
    });

    describe('_getRobotsUrl', () => {
        it('returns robots.txt url for given host', () => {
            let robotsUrl = robotto._getRobotsUrl(coolUrl);
            assert.deepEqual(robotsUrl, coolRobot);
        });
    });

    describe('fetch', () => {
        beforeEach(() => {
            sandbox.spy(robotto, '_getRobotsUrl');
            sandbox.stub(robotto, '_request')
                .callsArgWith(1, null, fake.response(), fake.robots());
        });

        it('should not break if no callback is passed', () => {
            assert.doesNotThrow(() => {
                robotto.fetch(coolUrl);
            }, 'callback is not a function');
        });

        it('should call _getRobotsUrl', (done) => {
            robotto.fetch(coolUrl, () => {
                sinon.assert.calledWith(robotto._getRobotsUrl, coolUrl);
                done();
            });
        });

        it('should call _request', (done) => {
            robotto.fetch(coolUrl, () => {
                sinon.assert.calledWith(robotto._request, coolRobot);
                done();
            });
        });

        it('should callback with an error if request fails', (done) => {
            robotto._request.restore();
            sandbox.stub(robotto, '_request')
                .callsArgWith(1, new Error('fake request error'));

            robotto.fetch(coolUrl, (err) => {
                assert.deepEqual(err.message, 'fake request error');
                done();
            });
        });

        it('should callback with an error if status code is not 200', (done) => {
            robotto._request.restore();
            sandbox.stub(robotto, '_request')
                .callsArgWith(1, null, {statusCode: 404});

            robotto.fetch(coolUrl, (err) => {
                assert.deepEqual(err.message, `Could not fetch robots.txt from ${coolUrl}. Server response code: 404`);
                done();
            });
        });

        it('should callback with robots.txt content', (done) => {
            robotto.fetch(coolUrl, (err, robots) => {
                assert.notOk(err);
                assert.deepEqual(robots, fake.robots());
                done();
            });
        });
    });

    describe('parse', () => {
        it('should understand comments', () => {
            let robotsFile = [
                '# comment 1',
                'User-agent: 007 # comment 2'
            ].join('\n');
            let comments = ['comment 1', 'comment 2'];

            assert.deepEqual(robotto.parse(robotsFile).comments, comments);
        });

        it('should index by User-agent', () => {
            let robotsFile = [
                '# comment 1',
                'User-agent: 007 # comment 2',
                'Allow: /kill/',
                'User-agent: Agent 47',
                'Disallow: /nothing/'
            ].join('\n');

            assert.property(robotto.parse(robotsFile), '007');
            assert.property(robotto.parse(robotsFile), 'Agent 47');
        });

        it('should put allow entries in their respective User-agents', () => {
            let robotsFile = [
                '# comment 1',
                'User-agent: 007 # comment 2',
                'Allow: /kill/',
                'User-agent: Agent 47',
                'Allow: /everything/'
            ].join('\n');
            let rules = robotto.parse(robotsFile);

            assert.deepEqual(rules['007'].allow, ['/kill/']);
            assert.deepEqual(rules['Agent 47'].allow, ['/everything/']);
        });

        it('should put disallow entries in their respective User-agents', () => {
            let robotsFile = [
                '# comment 1',
                'User-agent: 007 # comment 2',
                'Disallow: /betrayal/',
                'User-agent: Agent 47',
                'Disallow: /nothing/'
            ].join('\n');
            let rules = robotto.parse(robotsFile);

            assert.deepEqual(rules['007'].disallow, ['/betrayal/']);
            assert.deepEqual(rules['Agent 47'].disallow, ['/nothing/']);
        });

        it('should actually parse a robots.txt file', () => {
            assert.deepEqual(robotto.parse(fake.robots()), fake.rules());
        });
    });
});
<|endoftext|>


<commit_before>module("zart.js - RDFa Service");

test("Test simple RDFa parsing", function() {
    var z = new Zart();
    z.use(new z.RdfaService);

    var html = jQuery('
Albert Einstein1879-03-14
Federal Republic of Germany
');

    stop();
    z.load({element: html}).from('rdfa').execute().done(function(entities) {
        ok(entities);
        equal(entities.length, 2);

        equal(entities[1].id, '<http://dbpedia.org/resource/Albert_Einstein>');
        equal(entities[1].get('foaf:name'), 'Albert Einstein');
        equal(entities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany');

        equal(z.entities.get('<http://dbpedia.org/resource/Germany>'), entities[0]);

        start();
    });
});

test("Test updating RDFa views", function() {
    var z = new Zart();
    z.use(new z.RdfaService);

    var html = jQuery('
Albert Einstein1879-03-14
Federal Republic of Germany
');

    stop();
    z.load({element: html}).from('rdfa').execute().done(function(entities) {
        ok(entities);
        equal(entities.length, 2);

        equal(entities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany');

        entities[0].set({'dbp:conventionalLongName': 'Switzerland'});
        equal(entities[0].get('dbp:conventionalLongName'), 'Switzerland');

        jQuery('[property="dbp:conventionalLongName"]', html).each(function() {
            equal(jQuery(this).html(), 'Switzerland');
        });

        start();
    });
});

/**
 * This test doesn't work with QUnit
test("Test global entity with a base URL", function() {
    var z = new Zart();
    z.use(new z.RdfaService);

    var html = jQuery('<base href="http://www.example.org/jo/blog" /><title>Jo\'s Friends and Family Blog</title><link rel="foaf:primaryTopic" href="#bbq" /><meta property="dc:creator" content="Jo" />...');

    z.load({element: html}).from('rdfa').execute().done(function(entities) {
        ok(entities);
        equal(entities.length, 1);
        equal(entities[0].get('dc:creator'), 'Jo');
        equal(entities[0].id, '<http://www.example.org/jo/blog>');

        start();
    });
    stop();
});
*/
<commit_msg>Port more RDFa tests<commit_after>module("zart.js - RDFa Service");

test("Test simple RDFa parsing", function() {
    var z = new Zart();
    z.use(new z.RdfaService);

    var html = jQuery('
Albert Einstein1879-03-14
Federal Republic of Germany
');

    stop();
    z.load({element: html}).from('rdfa').execute().done(function(entities) {
        ok(entities);
        equal(entities.length, 2);

        equal(entities[1].id, '<http://dbpedia.org/resource/Albert_Einstein>');
        equal(entities[1].get('foaf:name'), 'Albert Einstein');
        equal(entities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany');

        equal(z.entities.get('<http://dbpedia.org/resource/Germany>'), entities[0]);

        start();
    });
});

test("Test updating RDFa views", function() {
    var z = new Zart();
    z.use(new z.RdfaService);

    var html = jQuery('
Albert Einstein1879-03-14
Federal Republic of Germany
');

    stop();
    z.load({element: html}).from('rdfa').execute().done(function(entities) {
        ok(entities);
        equal(entities.length, 2);

        equal(entities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany');

        entities[0].set({'dbp:conventionalLongName': 'Switzerland'});
        equal(entities[0].get('dbp:conventionalLongName'), 'Switzerland');

        jQuery('[property="dbp:conventionalLongName"]', html).each(function() {
            equal(jQuery(this).html(), 'Switzerland');
        });

        start();
    });
});

test("Test simple RDFa nested tags", function() {
    var z = new Zart();
    z.use(new z.RdfaService);

    var html = jQuery('

News item title

');

    stop();
    z.load({element: html}).from('rdfa').execute().done(function(entities) {
        equal(entities.length, 1);
        equal(entities[0].get('dcterms:title'), 'News item title');
        start();
    });
});

test("Test RDFa property content", function() {
    var z = new Zart();
    z.use(new z.RdfaService);

    var html = jQuery('
Henri Bergius
');

    stop();
    z.load({element: html}).from('rdfa').execute().done(function(entities) {
        equal(entities.length, 1);
        equal(entities[0].get('iks:online'), 0);

        entities[0].set({'iks:online': 1});
        equal(entities[0].get('iks:online'), 1);
        equal(jQuery('[property="iks:online"]', html).attr('content'), 1);
        equal(jQuery('[property="iks:online"]', html).text(), '');

        start();
    });
});

test("Test RDFa example from Wikipedia", function() {
    var z = new Zart();
    z.use(new z.RdfaService);

    var html = jQuery('
In his latest book Wikinomics, Don Tapscott explains deep changes in technology, demographics and business. The book is due to be published in October 2006.
');

    stop();
    z.load({element: html}).from('rdfa').execute().done(function(entities) {
        var objectInstance = z.entities.get('<http://www.example.com/books/wikinomics>');
        equal(objectInstance.get('dc:title'), 'Wikinomics');
        equal(objectInstance.get('dc:creator'), 'Don Tapscott');
        start();
    });
});

/**
 * This test doesn't work with QUnit
test("Test global entity with a base URL", function() {
    var z = new Zart();
    z.use(new z.RdfaService);

    var html = jQuery('<base href="http://www.example.org/jo/blog" /><title>Jo\'s Friends and Family Blog</title><link rel="foaf:primaryTopic" href="#bbq" /><meta property="dc:creator" content="Jo" />...');

    z.load({element: html}).from('rdfa').execute().done(function(entities) {
        ok(entities);
        equal(entities.length, 1);
        equal(entities[0].get('dc:creator'), 'Jo');
        equal(entities[0].id, '<http://www.example.org/jo/blog>');

        start();
    });
    stop();
});
*/
<|endoftext|>


<commit_before>var assert = require('assert'),
    termops = require('../lib/util/termops');

describe('termops', function() {
    describe('tokenize', function() {
        describe('examples', function() {
            it('tokenizes basic strings', function() {
                assert.deepEqual(termops.tokenize('foo'), ['foo']);
                assert.deepEqual(termops.tokenize('foo bar'), ['foo', 'bar']);
                assert.deepEqual(termops.tokenize('foo-bar'), ['foo', 'bar']);
            });
        });
        describe('edge cases', function() {
            it('empty string', function() {
                assert.deepEqual(termops.tokenize(''), []);
            });
        });
    });
    describe('terms', function() {
        it('tokenizes and hashes values', function() {
            assert.deepEqual(termops.terms('foo bar'), [2851307220,1991736600]);
        });
    });
    describe('termsMap', function() {
        it('tokenizes and hashes values', function() {
            assert.deepEqual(termops.termsMap('foo bar'), {
                2851307220: 'foo',
                1991736600: 'bar'
            });
        });
    });
    describe('degens', function() {
        it('generates degenerates', function() {
            var degens = termops.degens('foobarbaz');
            assert.deepEqual(degens, {
                967483784: 1617781335,
                1062237932: 1617781335,
                1617781332: 1617781332,
                2851307220: 1617781335,
                2921073340: 1617781334,
                3214735720: 1617781335,
                4112850188: 1617781333
            });
            for (var k in degens) {
                // Encodes ID for 'foobarbaz'.
                assert.equal(degens[k] >>> 2 << 2 >>> 0, termops.terms('foobarbaz')[0]);
                // Encodes degen distance (max: 3) from foobarbaz.
                assert.ok(degens[k] % 4 <= 3);
            }
        });
    });
    describe('phrase', function() {
        it('generates a name id', function() {
            assert.deepEqual(termops.phrase('foo'), 2851307223);
            assert.deepEqual(termops.phrase('foo street'), 1742114519);
            assert.deepEqual(termops.phrase('foo lane'), 3289808599);
            // Clusters phrase IDs based on initial term.
            assert.deepEqual(termops.phrase('foo') % 4096, 3799);
            assert.deepEqual(termops.phrase('foo street') % 4096, 3799);
            assert.deepEqual(termops.phrase('foo lane') % 4096, 3799);
        });
    });
});
<commit_msg>Add more tokenization tests (failing).<commit_after>var assert = require('assert'),
    termops = require('../lib/util/termops');

describe('termops', function() {
    describe('tokenize', function() {
        describe('examples', function() {
            it('tokenizes basic strings', function() {
                assert.deepEqual(termops.tokenize('foo'), ['foo']);
                assert.deepEqual(termops.tokenize('foo bar'), ['foo', 'bar']);
                assert.deepEqual(termops.tokenize('foo-bar'), ['foo', 'bar']);
                assert.deepEqual(termops.tokenize('San José'), ['san', 'jose']);
                assert.deepEqual(termops.tokenize('San José'), ['san', 'jose']);
                assert.deepEqual(termops.tokenize('Chamonix-Mont-Blanc'), ['chamonix','mont','blanc']);
                assert.deepEqual(termops.tokenize('Москва'), ['moskva']);
                assert.deepEqual(termops.tokenize('京都市'), ['jing','du','shi']);
            });
        });
        describe('edge cases', function() {
            it('empty string', function() {
                assert.deepEqual(termops.tokenize(''), []);
            });
        });
    });
    describe('terms', function() {
        it('tokenizes and hashes values', function() {
            assert.deepEqual(termops.terms('foo bar'), [2851307220,1991736600]);
        });
    });
    describe('termsMap', function() {
        it('tokenizes and hashes values', function() {
            assert.deepEqual(termops.termsMap('foo bar'), {
                2851307220: 'foo',
                1991736600: 'bar'
            });
        });
    });
    describe('degens', function() {
        it('generates degenerates', function() {
            var degens = termops.degens('foobarbaz');
            assert.deepEqual(degens, {
                967483784: 1617781335,
                1062237932: 1617781335,
                1617781332: 1617781332,
                2851307220: 1617781335,
                2921073340: 1617781334,
                3214735720: 1617781335,
                4112850188: 1617781333
            });
            for (var k in degens) {
                // Encodes ID for 'foobarbaz'.
                assert.equal(degens[k] >>> 2 << 2 >>> 0, termops.terms('foobarbaz')[0]);
                // Encodes degen distance (max: 3) from foobarbaz.
                assert.ok(degens[k] % 4 <= 3);
            }
        });
    });
    describe('phrase', function() {
        it('generates a name id', function() {
            assert.deepEqual(termops.phrase('foo'), 2851307223);
            assert.deepEqual(termops.phrase('foo street'), 1742114519);
            assert.deepEqual(termops.phrase('foo lane'), 3289808599);
            // Clusters phrase IDs based on initial term.
            assert.deepEqual(termops.phrase('foo') % 4096, 3799);
            assert.deepEqual(termops.phrase('foo street') % 4096, 3799);
            assert.deepEqual(termops.phrase('foo lane') % 4096, 3799);
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('chai').assert,
    testlib = require('../lib/test'),
    context = require('../lib/context.js');

describe('context', function () {
    it('.query should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().query));
        done();
    });

    it('.param should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().param));
        done();
    });

    it('.cookie should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().cookie));
        done();
    });

    it('.data should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().data));
        done();
    });

    it('.data("getProdcut") should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().data('getProduct')));
        done();
    });

    it('.module should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().module));
        done();
    });

    it('.module("header") should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().module('header')));
        done();
    });

    it('.module("not_found") should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().module('not_found')));
        done();
    });

    it('.page should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().page));
        done();
    });

    it('.react should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().react));
        done();
    });

    it('.dreact should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().dreact));
        done();
    });

    it('.task should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().task));
        done();
    });

    it('.input should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().input));
        done();
    });

    it('.input("getSomeParams") should be a subtask', function (done) {
        assert.equal(true, testlib.isSubtask(testlib.getMockContext().input('getSomeParams')));
        done();
    });

    it('.reactBindStr() should return null when no react modules', function (done) {
        assert.equal(null, testlib.getMockContext().reactBindStr());
        done();
    });

    it('.reactBindStr() should return js code for client to bind react modules', function (done) {
        var CX = testlib.getMockContext();
        CX.taskPool.react = {Rid: {jsx: 'Test', props: [1, 2]}};
        assert.equal('var React=require("react"),Test=require("./react/Test.jsx");React.renderComponent(Test.apply(Test,[1,2]), document.getElementById("Rid"))', CX.reactBindStr());
        done();
    });
});

describe('context tasks', function () {
    it('module("header")() should be a success task', function (done) {
        testlib.getMockContext().module('header')().execute(function (D) {
            assert.equal(true, D !== undefined);
            done();
        });
    });

    it('page("sample")() should be a success task', function (done) {
        testlib.getMockContext().page('sample')().execute(function (D) {
            assert.equal(true, D !== undefined);
            done();
        });
    });

    it('react("path")(productData) should be a success task', function (done) {
        testlib.getMockContext().react('Path')({
            path: [
                {id: 1, title: 'root'},
                {id: 3, title: 'second'},
                {id: 321, title: 'final'}
            ]
        }).execute(function (D) {
            assert.equal('

root

second

final

', D);
            done();
        });
    });

    it('react("path")(badData) should be a failed task', function (done) {
        var CX = testlib.getMockContext(),
            T = CX.react('Path')({});

        T.execute(function (D) {
            assert.equal(undefined, D);
            assert.equal(1, CX.taskPool.errors.length);
            done();
        });
    });
});
<commit_msg>test more<commit_after>'use strict';

var assert = require('chai').assert,
    testlib = require('../lib/test'),
    context = require('../lib/context.js');

describe('context', function () {
    it('.query should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().query));
        done();
    });

    it('.param should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().param));
        done();
    });

    it('.cookie should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().cookie));
        done();
    });

    it('.data should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().data));
        done();
    });

    it('.data("getProdcut") should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().data('getProduct')));
        done();
    });

    it('.module should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().module));
        done();
    });

    it('.module("header") should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().module('header')));
        done();
    });

    it('.module("not_found") should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().module('not_found')));
        done();
    });

    it('.page should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().page));
        done();
    });

    it('.react should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().react));
        done();
    });

    it('.dreact should be a subtask creator locator', function (done) {
        assert.equal(true, testlib.isSubtaskCreatorFinder(testlib.getMockContext().dreact));
        done();
    });

    it('.task should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().task));
        done();
    });

    it('.input should be a subtask creator', function (done) {
        assert.equal(true, testlib.isSubtaskCreator(testlib.getMockContext().input));
        done();
    });

    it('.input("getSomeParams") should be a subtask', function (done) {
        assert.equal(true, testlib.isSubtask(testlib.getMockContext().input('getSomeParams')));
        done();
    });

    it('.reactBindStr() should return null when no react modules', function (done) {
        assert.equal(null, testlib.getMockContext().reactBindStr());
        done();
    });

    it('.reactBindStr() should return js code for client to bind react modules', function (done) {
        var CX = testlib.getMockContext();
        CX.taskPool.react = {Rid: {jsx: 'Test', props: [1, 2]}};
        assert.equal('var React=require("react"),Test=require("./react/Test.jsx");React.renderComponent(Test.apply(Test,[1,2]), document.getElementById("Rid"))', CX.reactBindStr());
        done();
    });
});

describe('context tasks', function () {
    it('data("getProduct")(id) should be a success task', function (done) {
        testlib.getMockContext().data('getProduct')(123).execute(function (D) {
            assert.equal(true, D !== undefined);
            assert.equal('this is sample product title (id=123)', D.title);
            done();
        });
    });
    it('module("header")() should be a success task', function (done) {
        testlib.getMockContext().module('header')().execute(function (D) {
            assert.equal(true, D !== undefined);
            done();
        });
    });

    it('page("sample")() should be a success task', function (done) {
        testlib.getMockContext().page('sample')().execute(function (D) {
            assert.equal(true, D !== undefined);
            done();
        });
    });

    it('react("path")(productData) should be a success task', function (done) {
        testlib.getMockContext().react('Path')({
            path: [
                {id: 1, title: 'root'},
                {id: 3, title: 'second'},
                {id: 321, title: 'final'}
            ]
        }).execute(function (D) {
            assert.equal('

root

second

final

', D);
            done();
        });
    });

    it('react("path")(badData) should be a failed task', function (done) {
        var CX = testlib.getMockContext(),
            T = CX.react('Path')({});

        T.execute(function (D) {
            assert.equal(undefined, D);
            assert.equal(1, CX.taskPool.errors.length);
            done();
        });
    });
});
<|endoftext|>