<commit_before>var assert = require('chai').assert;
var nodemock = require('nodemock');
var Deferred = require('jsdeferred').Deferred;
var express = require('express');

var utils = require('./test-utils');

var socketIoAdaptor = require('../lib/frontend/socket.io-adaptor');
var model = require('../lib/model');
var scoketIoCommands = require('../lib/frontend/default-commands/socket.io');
var Connection = require('../lib/backend/connection').Connection;

suite('Socket.IO API', function() {
  var connection;
  var server;
  var clientSockets;
  var backend;

  var testPlugin = {
    'reqrep': new model.SocketRequestResponse(),
    'reqrep-mod-event': new model.SocketRequestResponse({
      toBackend: function(event, data) { return [event + '.mod', data]; },
      toClient: function(event, data) { return [event + '.mod', data]; }
    }),
    'reqrep-mod-body': new model.SocketRequestResponse({
      toBackend: function(event, data) { return [event, 'modified request']; },
      toClient: function(event, data) { return [event, 'modified response']; }
    }),
    'pubsub': new model.SocketPublishSubscribe(),
    'pubsub-mod-event': new model.SocketPublishSubscribe({
      toBackend: function(event, data) { return [event + '.mod', data]; },
      toClient: function(event, data) { return [event + '.mod', data]; }
    }),
    'pubsub-mod-body': new model.SocketPublishSubscribe({
      toBackend: function(event, data) { return [event, 'modified request']; },
      toClient: function(event, data) { return [event, 'modified response']; }
    })
  };

  setup(function() {
    clientSockets = [];
  });

  teardown(function() {
    if (clientSockets.length) {
      clientSockets.forEach(function(clientSocket) {
        clientSocket.disconnect();
      });
    }
    utils.teardownApplication({ backend:    backend,
                                server:     server,
                                conncetion: connection });
  });

  test('registeration of plugin commands', function(done) {
    var basePlugin = {
      getCommand: new model.SocketRequestResponse(),
      putCommand: new model.SocketRequestResponse(),
      postCommand: new model.SocketRequestResponse(),
      deleteCommand: new model.SocketRequestResponse(),
      ignored: new model.REST()
    };
    var overridingPlugin = {
      postCommand: new model.SocketRequestResponse(),
      deleteCommand: new model.SocketRequestResponse()
    };

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;

        var registeredCommands = socketIoAdaptor.register(application, server, {
          connection: utils.createStubbedBackendConnection(),
          plugins: [
            basePlugin,
            overridingPlugin
          ]
        });

        registeredCommands = registeredCommands.map(function(command) {
          return {
            name:       command.name,
            definition: command.definition
          };
        });
        assert.deepEqual(registeredCommands,
                         [{ name:       'search',
                            definition: scoketIoCommands.search },
                          { name:       'getCommand',
                            definition: basePlugin.getCommand },
                          { name:       'putCommand',
                            definition: basePlugin.putCommand },
                          { name:       'postCommand',
                            definition: overridingPlugin.postCommand },
                          { name:       'deleteCommand',
                            definition: overridingPlugin.deleteCommand }]);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('initialization', function(done) {
    var mockedListener = nodemock
      .mock('connected');

    var application = express();
    application.on('connection', function(socket) {
      mockedListener.connected();
    });

    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: utils.createStubbedBackendConnection(),
          plugins: [testPlugin]
        });

        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSockets.push(newClientSocket);
      })
      .wait(0.01)
      .next(function() {
        mockedListener.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  suite('request-response', function() {
    function testReqRep(description, params) {
      test(description, function(done) {
        var mockedReceiver;
        utils.setupApplication()
          .next(function(result) {
            server     = result.server;
            connection = result.connection;
            backend    = result.backend;
            socketIoAdaptor.register(result.application, server, {
              tag:      'test',
              connection: connection,
              plugins: [testPlugin]
            });
          })
          .createClientSocket()
          .next(function(newClientSocket) {
            clientSockets.push(newClientSocket);
            clientSockets[0].emit(params.clientCommand, params.clientBody);
          })
          .wait(0.01)
          .next(function() {
            assert.deepEqual(backend.getMessages().map(function(message) {
                               return { type: message.type,
                                        body: message.body };
                             }),
                             [{ type: params.expectedClientCommand,
                                body: params.expectedClientBody }]);

            mockedReceiver = nodemock
              .mock('receive')
                .takes(params.expectedBackendBody);
            clientSockets[0].on(params.expectedBackendCommand, function(data) {
              mockedReceiver.receive(data);
            });

            var request = backend.getMessages()[0];
            var response = utils.createReplyEnvelope(request,
                                                     params.backendCommand,
                                                     params.backendBody);
            return utils.sendPacketTo(utils.createPacket(response),
                                      utils.testReceivePort)
          })
          .wait(0.01)
          .next(function() {
            mockedReceiver.assertThrows();
            done();
          })
          .error(function(error) {
            done(error);
          });
      });
    }

    testReqRep('basic', {
      clientCommand:          'reqrep',
      clientBody:             'raw request',
      expectedClientCommand:  'reqrep',
      expectedClientBody:     'raw request',
      backendCommand:         'reqrep.response',
      backendBody:            'raw response',
      expectedBackendCommand: 'reqrep.response',
      expectedBackendBody:    'raw response'
    });

    testReqRep('modified event type', {
      clientCommand:          'reqrep-mod-event',
      clientBody:             'raw request',
      expectedClientCommand:  'reqrep-mod-event.mod',
      expectedClientBody:     'raw request',
      backendCommand:         'reqrep-mod-event.response',
      backendBody:            'raw response',
      expectedBackendCommand: 'reqrep-mod-event.response.mod',
      expectedBackendBody:    'raw response'
    });

    testReqRep('modified body', {
      clientCommand:          'reqrep-mod-body',
      clientBody:             'raw request',
      expectedClientCommand:  'reqrep-mod-body',
      expectedClientBody:     'modified request',
      backendCommand:         'reqrep-mod-body.response',
      backendBody:            'raw response',
      expectedBackendCommand: 'reqrep-mod-body.response',
      expectedBackendBody:    'modified response'
    });

    test('multiple clients', function(done) {
      var messages = [
        '0-a',
        '1-a',
        '2-a',
        '0-b',
        '1-b',
        '2-b'
      ];
      var clientReceiver;
      utils.setupApplication()
        .next(function(result) {
          server     = result.server;
          connection = result.connection;
          backend    = result.backend;
          socketIoAdaptor.register(result.application, server, {
            tag:      'test',
            connection: connection,
            plugins: [testPlugin]
          });
        })
        .createClientSockets(3)
        .next(function(newClientSockets) {
          clientSockets = clientSockets.concat(newClientSockets);
          clientSockets[0].emit('reqrep', messages[0]);
        }).wait(0.01).next(function() {
          clientSockets[1].emit('reqrep', messages[1]);
        }).wait(0.01).next(function() {
          clientSockets[2].emit('reqrep', messages[2]);
        }).wait(0.01).next(function() {
          clientSockets[0].emit('reqrep', messages[3]);
        }).wait(0.01).next(function() {
          clientSockets[1].emit('reqrep', messages[4]);
        }).wait(0.01).next(function() {
          clientSockets[2].emit('reqrep', messages[5]);
        }).wait(0.01).next(function() {
          assert.deepEqual(backend.getBodies(), messages);

          var responses = backend.getMessages().map(function(envelope) {
            return utils.createReplyEnvelope(envelope, 'reqrep', envelope.body);
          });

          clientReceiver = nodemock
            .mock('receive').takes('0:' + messages[0])
            .mock('receive').takes('1:' + messages[1])
            .mock('receive').takes('2:' + messages[2])
            .mock('receive').takes('0:' + messages[3])
            .mock('receive').takes('1:' + messages[4])
            .mock('receive').takes('2:' + messages[5]);
          clientSockets[0].on('reqrep', function(data) {
            clientReceiver.receive('0:' + data);
          });
          clientSockets[1].on('reqrep', function(data) {
            clientReceiver.receive('1:' + data);
          });
          clientSockets[2].on('reqrep', function(data) {
            clientReceiver.receive('2:' + data);
          });

          return utils
            .sendPacketTo(utils.createPacket(responses[0]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[1]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[2]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[3]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[4]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[5]), utils.testReceivePort);
        })
        .wait(0.01)
        .next(function() {
          clientReceiver.assertThrows();
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });

  suite('publish-subscribe', function() {
    function testPubSub(description, params) {
      test(description, function(done) {
        var mockedReceiver;
        utils.setupApplication()
          .next(function(result) {
            server     = result.server;
            connection = result.connection;
            backend    = result.backend;
            socketIoAdaptor.register(result.application, server, {
              tag:      'test',
              connection: connection,
              plugins: [testPlugin]
            });
          })
          .createClientSocket()
          .next(function(newClientSocket) {
            clientSockets.push(newClientSocket);
            clientSockets[0].emit(params.clientCommand, params.clientBody);
          })
          .wait(0.01)
          .next(function() {
            assert.deepEqual(backend.getMessages().map(function(message) {
                               return { type: message.type,
                                        body: message.body };
                             }),
                             [{ type: params.expectedClientCommand,
                                body: params.expectedClientBody }]);

            mockedReceiver = nodemock
              .mock('receive')
                .takes(params.expectedBackendBody);
            clientSockets[0].on(params.expectedBackendCommand, function(data) {
              mockedReceiver.receive(data);
            });

            var published = utils.createEnvelope(params.backendCommand,
                                                 params.backendBody);
            return utils.sendPacketTo(utils.createPacket(published),
                                      utils.testReceivePort)
          })
          .wait(0.01)
          .next(function() {
            mockedReceiver.assertThrows();
            done();
          })
          .error(function(error) {
            done(error);
          });
      });
    }

    testPubSub('basic', {
      clientCommand:          'pubsub.subscribe',
      clientBody:             'raw request',
      expectedClientCommand:  'pubsub.subscribe',
      expectedClientBody:     'raw request',
      backendCommand:         'pubsub',
      backendBody:            'raw response',
      expectedBackendCommand: 'pubsub',
      expectedBackendBody:    'raw response'
    });

    testPubSub('modified event type', {
      clientCommand:          'pubsub-mod-event.subscribe',
      clientBody:             'raw request',
      expectedClientCommand:  'pubsub-mod-event.mod.subscribe',
      expectedClientBody:     'raw request',
      backendCommand:         'pubsub-mod-event',
      backendBody:            'raw response',
      expectedBackendCommand: 'pubsub-mod-event.mod',
      expectedBackendBody:    'raw response'
    });

    testPubSub('modified body', {
      clientCommand:          'pubsub-mod-body.subscribe',
      clientBody:             'raw request',
      expectedClientCommand:  'pubsub-mod-body.subscribe',
      expectedClientBody:     'modified request',
      backendCommand:         'pubsub-mod-body',
      backendBody:            'raw response',
      expectedBackendCommand: 'pubsub-mod-body',
      expectedBackendBody:    'modified response'
    });

    test('multiple clients', function(done) {
      var messages = [
        'a',
        'b'
      ];
      var clientReceiver;
      utils.setupApplication()
        .next(function(result) {
          server     = result.server;
          connection = result.connection;
          backend    = result.backend;
          socketIoAdaptor.register(result.application, server, {
            tag:      'test',
            connection: connection,
            plugins: [testPlugin]
          });
        })
        .createClientSockets(3)
        .next(function(newClientSockets) {
          clientSockets = clientSockets.concat(newClientSockets);
          clientSockets[0].emit('pubsub.subscribe', 0);
        }).wait(0.01).next(function() {
          clientSockets[1].emit('pubsub.subscribe', 1);
        }).wait(0.01).next(function() {
          clientSockets[2].emit('pubsub.subscribe', 2);
        }).wait(0.01).next(function() {
          assert.deepEqual(backend.getBodies(),
                           [0, 1, 2]);

          var publisheds = messages.map(function(message) {
            return utils.createEnvelope('pubsub', message);
          });

          clientReceiver = nodemock
            .mock('receive').takes('0:' + messages[0])
            .mock('receive').takes('1:' + messages[0])
            .mock('receive').takes('2:' + messages[0])
            .mock('receive').takes('0:' + messages[1])
            .mock('receive').takes('1:' + messages[1])
            .mock('receive').takes('2:' + messages[1]);
          clientSockets[0].on('pubsub', function(data) {
            clientReceiver.receive('0:' + data);
          });
          clientSockets[1].on('pubsub', function(data) {
            clientReceiver.receive('1:' + data);
          });
          clientSockets[2].on('pubsub', function(data) {
            clientReceiver.receive('2:' + data);
          });

          return utils
            .sendPacketTo(utils.createPacket(publisheds[0]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(publisheds[1]), utils.testReceivePort);
        })
        .wait(0.01)
        .next(function() {
          clientReceiver.assertThrows();
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });
});

<commit_msg>test: No need to load Connection module from the Socket.IO API test<commit_after>var assert = require('chai').assert;
var nodemock = require('nodemock');
var Deferred = require('jsdeferred').Deferred;
var express = require('express');

var utils = require('./test-utils');

var socketIoAdaptor = require('../lib/frontend/socket.io-adaptor');
var model = require('../lib/model');
var scoketIoCommands = require('../lib/frontend/default-commands/socket.io');

suite('Socket.IO API', function() {
  var connection;
  var server;
  var clientSockets;
  var backend;

  var testPlugin = {
    'reqrep': new model.SocketRequestResponse(),
    'reqrep-mod-event': new model.SocketRequestResponse({
      toBackend: function(event, data) { return [event + '.mod', data]; },
      toClient: function(event, data) { return [event + '.mod', data]; }
    }),
    'reqrep-mod-body': new model.SocketRequestResponse({
      toBackend: function(event, data) { return [event, 'modified request']; },
      toClient: function(event, data) { return [event, 'modified response']; }
    }),
    'pubsub': new model.SocketPublishSubscribe(),
    'pubsub-mod-event': new model.SocketPublishSubscribe({
      toBackend: function(event, data) { return [event + '.mod', data]; },
      toClient: function(event, data) { return [event + '.mod', data]; }
    }),
    'pubsub-mod-body': new model.SocketPublishSubscribe({
      toBackend: function(event, data) { return [event, 'modified request']; },
      toClient: function(event, data) { return [event, 'modified response']; }
    })
  };

  setup(function() {
    clientSockets = [];
  });

  teardown(function() {
    if (clientSockets.length) {
      clientSockets.forEach(function(clientSocket) {
        clientSocket.disconnect();
      });
    }
    utils.teardownApplication({ backend:    backend,
                                server:     server,
                                conncetion: connection });
  });

  test('registeration of plugin commands', function(done) {
    var basePlugin = {
      getCommand: new model.SocketRequestResponse(),
      putCommand: new model.SocketRequestResponse(),
      postCommand: new model.SocketRequestResponse(),
      deleteCommand: new model.SocketRequestResponse(),
      ignored: new model.REST()
    };
    var overridingPlugin = {
      postCommand: new model.SocketRequestResponse(),
      deleteCommand: new model.SocketRequestResponse()
    };

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;

        var registeredCommands = socketIoAdaptor.register(application, server, {
          connection: utils.createStubbedBackendConnection(),
          plugins: [
            basePlugin,
            overridingPlugin
          ]
        });

        registeredCommands = registeredCommands.map(function(command) {
          return {
            name:       command.name,
            definition: command.definition
          };
        });
        assert.deepEqual(registeredCommands,
                         [{ name:       'search',
                            definition: scoketIoCommands.search },
                          { name:       'getCommand',
                            definition: basePlugin.getCommand },
                          { name:       'putCommand',
                            definition: basePlugin.putCommand },
                          { name:       'postCommand',
                            definition: overridingPlugin.postCommand },
                          { name:       'deleteCommand',
                            definition: overridingPlugin.deleteCommand }]);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('initialization', function(done) {
    var mockedListener = nodemock
      .mock('connected');

    var application = express();
    application.on('connection', function(socket) {
      mockedListener.connected();
    });

    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: utils.createStubbedBackendConnection(),
          plugins: [testPlugin]
        });

        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSockets.push(newClientSocket);
      })
      .wait(0.01)
      .next(function() {
        mockedListener.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  suite('request-response', function() {
    function testReqRep(description, params) {
      test(description, function(done) {
        var mockedReceiver;
        utils.setupApplication()
          .next(function(result) {
            server     = result.server;
            connection = result.connection;
            backend    = result.backend;
            socketIoAdaptor.register(result.application, server, {
              tag:      'test',
              connection: connection,
              plugins: [testPlugin]
            });
          })
          .createClientSocket()
          .next(function(newClientSocket) {
            clientSockets.push(newClientSocket);
            clientSockets[0].emit(params.clientCommand, params.clientBody);
          })
          .wait(0.01)
          .next(function() {
            assert.deepEqual(backend.getMessages().map(function(message) {
                               return { type: message.type,
                                        body: message.body };
                             }),
                             [{ type: params.expectedClientCommand,
                                body: params.expectedClientBody }]);

            mockedReceiver = nodemock
              .mock('receive')
                .takes(params.expectedBackendBody);
            clientSockets[0].on(params.expectedBackendCommand, function(data) {
              mockedReceiver.receive(data);
            });

            var request = backend.getMessages()[0];
            var response = utils.createReplyEnvelope(request,
                                                     params.backendCommand,
                                                     params.backendBody);
            return utils.sendPacketTo(utils.createPacket(response),
                                      utils.testReceivePort)
          })
          .wait(0.01)
          .next(function() {
            mockedReceiver.assertThrows();
            done();
          })
          .error(function(error) {
            done(error);
          });
      });
    }

    testReqRep('basic', {
      clientCommand:          'reqrep',
      clientBody:             'raw request',
      expectedClientCommand:  'reqrep',
      expectedClientBody:     'raw request',
      backendCommand:         'reqrep.response',
      backendBody:            'raw response',
      expectedBackendCommand: 'reqrep.response',
      expectedBackendBody:    'raw response'
    });

    testReqRep('modified event type', {
      clientCommand:          'reqrep-mod-event',
      clientBody:             'raw request',
      expectedClientCommand:  'reqrep-mod-event.mod',
      expectedClientBody:     'raw request',
      backendCommand:         'reqrep-mod-event.response',
      backendBody:            'raw response',
      expectedBackendCommand: 'reqrep-mod-event.response.mod',
      expectedBackendBody:    'raw response'
    });

    testReqRep('modified body', {
      clientCommand:          'reqrep-mod-body',
      clientBody:             'raw request',
      expectedClientCommand:  'reqrep-mod-body',
      expectedClientBody:     'modified request',
      backendCommand:         'reqrep-mod-body.response',
      backendBody:            'raw response',
      expectedBackendCommand: 'reqrep-mod-body.response',
      expectedBackendBody:    'modified response'
    });

    test('multiple clients', function(done) {
      var messages = [
        '0-a',
        '1-a',
        '2-a',
        '0-b',
        '1-b',
        '2-b'
      ];
      var clientReceiver;
      utils.setupApplication()
        .next(function(result) {
          server     = result.server;
          connection = result.connection;
          backend    = result.backend;
          socketIoAdaptor.register(result.application, server, {
            tag:      'test',
            connection: connection,
            plugins: [testPlugin]
          });
        })
        .createClientSockets(3)
        .next(function(newClientSockets) {
          clientSockets = clientSockets.concat(newClientSockets);
          clientSockets[0].emit('reqrep', messages[0]);
        }).wait(0.01).next(function() {
          clientSockets[1].emit('reqrep', messages[1]);
        }).wait(0.01).next(function() {
          clientSockets[2].emit('reqrep', messages[2]);
        }).wait(0.01).next(function() {
          clientSockets[0].emit('reqrep', messages[3]);
        }).wait(0.01).next(function() {
          clientSockets[1].emit('reqrep', messages[4]);
        }).wait(0.01).next(function() {
          clientSockets[2].emit('reqrep', messages[5]);
        }).wait(0.01).next(function() {
          assert.deepEqual(backend.getBodies(), messages);

          var responses = backend.getMessages().map(function(envelope) {
            return utils.createReplyEnvelope(envelope, 'reqrep', envelope.body);
          });

          clientReceiver = nodemock
            .mock('receive').takes('0:' + messages[0])
            .mock('receive').takes('1:' + messages[1])
            .mock('receive').takes('2:' + messages[2])
            .mock('receive').takes('0:' + messages[3])
            .mock('receive').takes('1:' + messages[4])
            .mock('receive').takes('2:' + messages[5]);
          clientSockets[0].on('reqrep', function(data) {
            clientReceiver.receive('0:' + data);
          });
          clientSockets[1].on('reqrep', function(data) {
            clientReceiver.receive('1:' + data);
          });
          clientSockets[2].on('reqrep', function(data) {
            clientReceiver.receive('2:' + data);
          });

          return utils
            .sendPacketTo(utils.createPacket(responses[0]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[1]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[2]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[3]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[4]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(responses[5]), utils.testReceivePort);
        })
        .wait(0.01)
        .next(function() {
          clientReceiver.assertThrows();
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });

  suite('publish-subscribe', function() {
    function testPubSub(description, params) {
      test(description, function(done) {
        var mockedReceiver;
        utils.setupApplication()
          .next(function(result) {
            server     = result.server;
            connection = result.connection;
            backend    = result.backend;
            socketIoAdaptor.register(result.application, server, {
              tag:      'test',
              connection: connection,
              plugins: [testPlugin]
            });
          })
          .createClientSocket()
          .next(function(newClientSocket) {
            clientSockets.push(newClientSocket);
            clientSockets[0].emit(params.clientCommand, params.clientBody);
          })
          .wait(0.01)
          .next(function() {
            assert.deepEqual(backend.getMessages().map(function(message) {
                               return { type: message.type,
                                        body: message.body };
                             }),
                             [{ type: params.expectedClientCommand,
                                body: params.expectedClientBody }]);

            mockedReceiver = nodemock
              .mock('receive')
                .takes(params.expectedBackendBody);
            clientSockets[0].on(params.expectedBackendCommand, function(data) {
              mockedReceiver.receive(data);
            });

            var published = utils.createEnvelope(params.backendCommand,
                                                 params.backendBody);
            return utils.sendPacketTo(utils.createPacket(published),
                                      utils.testReceivePort)
          })
          .wait(0.01)
          .next(function() {
            mockedReceiver.assertThrows();
            done();
          })
          .error(function(error) {
            done(error);
          });
      });
    }

    testPubSub('basic', {
      clientCommand:          'pubsub.subscribe',
      clientBody:             'raw request',
      expectedClientCommand:  'pubsub.subscribe',
      expectedClientBody:     'raw request',
      backendCommand:         'pubsub',
      backendBody:            'raw response',
      expectedBackendCommand: 'pubsub',
      expectedBackendBody:    'raw response'
    });

    testPubSub('modified event type', {
      clientCommand:          'pubsub-mod-event.subscribe',
      clientBody:             'raw request',
      expectedClientCommand:  'pubsub-mod-event.mod.subscribe',
      expectedClientBody:     'raw request',
      backendCommand:         'pubsub-mod-event',
      backendBody:            'raw response',
      expectedBackendCommand: 'pubsub-mod-event.mod',
      expectedBackendBody:    'raw response'
    });

    testPubSub('modified body', {
      clientCommand:          'pubsub-mod-body.subscribe',
      clientBody:             'raw request',
      expectedClientCommand:  'pubsub-mod-body.subscribe',
      expectedClientBody:     'modified request',
      backendCommand:         'pubsub-mod-body',
      backendBody:            'raw response',
      expectedBackendCommand: 'pubsub-mod-body',
      expectedBackendBody:    'modified response'
    });

    test('multiple clients', function(done) {
      var messages = [
        'a',
        'b'
      ];
      var clientReceiver;
      utils.setupApplication()
        .next(function(result) {
          server     = result.server;
          connection = result.connection;
          backend    = result.backend;
          socketIoAdaptor.register(result.application, server, {
            tag:      'test',
            connection: connection,
            plugins: [testPlugin]
          });
        })
        .createClientSockets(3)
        .next(function(newClientSockets) {
          clientSockets = clientSockets.concat(newClientSockets);
          clientSockets[0].emit('pubsub.subscribe', 0);
        }).wait(0.01).next(function() {
          clientSockets[1].emit('pubsub.subscribe', 1);
        }).wait(0.01).next(function() {
          clientSockets[2].emit('pubsub.subscribe', 2);
        }).wait(0.01).next(function() {
          assert.deepEqual(backend.getBodies(),
                           [0, 1, 2]);

          var publisheds = messages.map(function(message) {
            return utils.createEnvelope('pubsub', message);
          });

          clientReceiver = nodemock
            .mock('receive').takes('0:' + messages[0])
            .mock('receive').takes('1:' + messages[0])
            .mock('receive').takes('2:' + messages[0])
            .mock('receive').takes('0:' + messages[1])
            .mock('receive').takes('1:' + messages[1])
            .mock('receive').takes('2:' + messages[1]);
          clientSockets[0].on('pubsub', function(data) {
            clientReceiver.receive('0:' + data);
          });
          clientSockets[1].on('pubsub', function(data) {
            clientReceiver.receive('1:' + data);
          });
          clientSockets[2].on('pubsub', function(data) {
            clientReceiver.receive('2:' + data);
          });

          return utils
            .sendPacketTo(utils.createPacket(publisheds[0]), utils.testReceivePort)
            .wait(0.01)
            .sendPacketTo(utils.createPacket(publisheds[1]), utils.testReceivePort);
        })
        .wait(0.01)
        .next(function() {
          clientReceiver.assertThrows();
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });
});

<|endoftext|>


<commit_before>var assert = require('chai').assert;
var nodemock = require('nodemock');
var Deferred = require('jsdeferred').Deferred;
var express = require('express');

var utils = require('./test-utils');

var socketIoAdaptor = require('../lib/frontend/socket.io-adaptor');
var model = require('../lib/model');
var scoketIoCommands = require('../lib/frontend/default-commands/socket.io');
var Connection = require('../lib/backend/connection').Connection;

suite('Socket.IO API', function() {
  var connection;
  var server;
  var clientSocket;

  var testPlugin = {
    'request-response': new model.SocketRequestResponse(),
    'publish-subscribe': new model.SocketPublishSubscribe(),
    'foobar': new model.SocketPublishSubscribe(),
    'builder': new model.SocketPublishSubscribe({
      toBackend: function(event, data) { return [event, 'builder request']; },
      toClient: function(event, data) { return [event, 'builder response'] }
    }),
    'customevent': new model.SocketPublishSubscribe({
      toBackend: function(event, data) { return ['custom', data] },
      toClient: function(event, data) { return ['custom', 'custom response']; }
    })
  };

  teardown(function() {
    if (connection) {
      utils.readyToDestroyMockedConnection(connection);
      connection = undefined;
    }
    if (clientSocket) {
      clientSocket.disconnect();
      clientSocket = undefined;
    }
    if (server) {
      server.close();
      server = undefined;
    }
  });

  test('registeration of plugin commands', function(done) {
    var basePlugin = {
      getCommand: new model.SocketRequestResponse(),
      putCommand: new model.SocketRequestResponse(),
      postCommand: new model.SocketRequestResponse(),
      deleteCommand: new model.SocketRequestResponse(),
      ignored: new model.REST()
    };
    var overridingPlugin = {
      postCommand: new model.SocketRequestResponse(),
      deleteCommand: new model.SocketRequestResponse()
    };

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;

        var registeredCommands = socketIoAdaptor.register(application, server, {
          connection: utils.createStubbedBackendConnection(),
          plugins: [
            basePlugin,
            overridingPlugin
          ]
        });

        registeredCommands = registeredCommands.map(function(command) {
          return {
            name:       command.name,
            definition: command.definition
          };
        });
        assert.deepEqual(registeredCommands,
                         [{ name:       'search',
                            definition: scoketIoCommands.search },
                          { name:       'getCommand',
                            definition: basePlugin.getCommand },
                          { name:       'putCommand',
                            definition: basePlugin.putCommand },
                          { name:       'postCommand',
                            definition: overridingPlugin.postCommand },
                          { name:       'deleteCommand',
                            definition: overridingPlugin.deleteCommand }]);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  function createEnvelope(type, body) {
    var now = new Date();
    var envelope = {
      id:         now.getTime(),
      date:       now.toISOString(),
      replyTo:    'localhost:' + utils.testReceivePort,
      statusCode: 200,
      type:       type,
      body:       body
    };
    return envelope;
  }

  test('initialization', function(done) {
    var mockedListener = nodemock
      .mock('connected');

    var application = express();
    application.on('connection', function(socket) {
      mockedListener.connected();
    });

    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: utils.createStubbedBackendConnection(),
          plugins: [testPlugin]
        });

        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSocket = newClientSocket;
      })
      .wait(0.01)
      .next(function() {
        mockedListener.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('one way: single client, front to back', function(done) {
    connection = utils.createMockedBackendConnection(testPlugin);

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSocket = newClientSocket;
        connection.assertThrows();

        var messages = [
          Math.random(),
          Math.random(),
          Math.random()
        ];
        connection = connection
          .mock('emitMessage')
            .takes('publish-subscribe', messages[0], null, {})
          .mock('emitMessage')
            .takes('publish-subscribe', messages[1], null, {})
          .mock('emitMessage')
            .takes('publish-subscribe', messages[2], null, {});

        clientSocket.emit('publish-subscribe', messages[0]);
        clientSocket.emit('publish-subscribe', messages[1]);
        clientSocket.emit('publish-subscribe', messages[2]);
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('one way: single client, back to front', function(done) {
    connection = utils.createMockedBackendConnection(testPlugin);

    var messages = [
      Math.random(),
      Math.random(),
      Math.random()
    ];
    var clientReceiver = nodemock
          .mock('receive')
            .takes(messages[0])
          .mock('receive')
            .takes(messages[1])
          .mock('receive')
            .takes(messages[2]);

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSocket = newClientSocket;
        connection.assertThrows();

        clientSocket.on('publish-subscribe', function(data) {
          clientReceiver.receive(data);
        });

        connection.controllers['publish-subscribe']
          .trigger(createEnvelope('publish-subscribe', messages[0]));
        connection.controllers['publish-subscribe']
          .trigger(createEnvelope('publish-subscribe', messages[1]));
        connection.controllers['publish-subscribe']
          .trigger(createEnvelope('publish-subscribe', messages[2]));
      })
      .wait(0.01)
      .next(function() {
        clientReceiver.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('request-response style message: single client', function(done) {
    connection = utils.createMockedBackendConnection(testPlugin);
    var onReceived = [{}, {}, {}];
    var messages = [
      Math.random(),
      Math.random(),
      Math.random()
    ];
    var clientReceiver;

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSocket = newClientSocket;
        connection.assertThrows();

        connection = connection
          .mock('emitMessage')
            .takes('request-response', messages[0], function() {}, {})
            .ctrl(2, onReceived[0])
          .mock('emitMessage')
            .takes('request-response', messages[1], function() {}, {})
            .ctrl(2, onReceived[1])
          .mock('emitMessage')
            .takes('request-response', messages[2], function() {}, {})
            .ctrl(2, onReceived[2]);

        clientSocket.emit('request-response', messages[0]);
        clientSocket.emit('request-response', messages[1]);
        clientSocket.emit('request-response', messages[2]);
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();

        clientReceiver = nodemock
          .mock('receive')
            .takes(messages[0])
          .mock('receive')
            .takes(messages[1])
          .mock('receive')
            .takes(messages[2]);
        clientSocket.on('request-response', function(data) {
          clientReceiver.receive(data);
        });

        onReceived[0].trigger(null,
                              createEnvelope('request-response', messages[0]));
        onReceived[1].trigger(null,
                              createEnvelope('request-response', messages[1]));
        onReceived[2].trigger(null,
                              createEnvelope('request-response', messages[2]));
      })
      .wait(0.01)
      .next(function() {
        clientReceiver.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('front to back, extra command (without builder)', function(done) {
    var extraController = {};
    connection = utils.createMockedBackendConnection(testPlugin);

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });

        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSocket = newClientSocket;
        connection.assertThrows();

        var message = Math.random();
        connection = connection
          .mock('emitMessage')
            .takes('foobar', message, null, {});
        clientSocket.emit('foobar', message);
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('front to back, extra command (with builder)', function(done) {
    var extraController = {};
    connection = utils.createMockedBackendConnection(testPlugin);

    var mockedReceiver = nodemock
          .mock('receive')
            .takes('builder response');

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSocket = newClientSocket;
        connection.assertThrows();

        connection = connection
          .mock('emitMessage')
            .takes('builder', 'builder request', null, {});
        clientSocket.on('builder.result', function(data) {
          mockedReceiver.receive(data);
        });
        clientSocket.emit('builder', { requestMessage: true });
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();
        connection.controllers.builder.trigger({
          statusCode: 200,
          type: 'builder.result',
          body: { responseMessage: true }
        });
      })
      .wait(0.01)
      .next(function() {
        mockedReceiver.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('front to back, extra command (custom event name)', function(done) {
    var extraController = {};
    connection = utils.createMockedBackendConnection(testPlugin);

    var mockedReceiver = nodemock
          .mock('receive')
            .takes('custom response');

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSocket = newClientSocket;
        connection.assertThrows();

        connection = connection
          .mock('emitMessage')
            .takes('custom', { requestMessage: true }, null, {});
        clientSocket.on('custom', function(data) {
          mockedReceiver.receive(data);
        });
        clientSocket.emit('customevent', { requestMessage: true });
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();
        connection.controllers.customevent.trigger({
          statusCode: 200,
          type: 'customevent.result',
          body: { responseMessage: true }
        });
      })
      .wait(0.01)
      .next(function() {
        mockedReceiver.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });
});

<commit_msg>test: Accept multiple client sockets<commit_after>var assert = require('chai').assert;
var nodemock = require('nodemock');
var Deferred = require('jsdeferred').Deferred;
var express = require('express');

var utils = require('./test-utils');

var socketIoAdaptor = require('../lib/frontend/socket.io-adaptor');
var model = require('../lib/model');
var scoketIoCommands = require('../lib/frontend/default-commands/socket.io');
var Connection = require('../lib/backend/connection').Connection;

suite('Socket.IO API', function() {
  var connection;
  var server;
  var clientSockets;

  var testPlugin = {
    'request-response': new model.SocketRequestResponse(),
    'publish-subscribe': new model.SocketPublishSubscribe(),
    'foobar': new model.SocketPublishSubscribe(),
    'builder': new model.SocketPublishSubscribe({
      toBackend: function(event, data) { return [event, 'builder request']; },
      toClient: function(event, data) { return [event, 'builder response'] }
    }),
    'customevent': new model.SocketPublishSubscribe({
      toBackend: function(event, data) { return ['custom', data] },
      toClient: function(event, data) { return ['custom', 'custom response']; }
    })
  };

  setup(function() {
    clientSockets = [];
  });

  teardown(function() {
    if (connection) {
      utils.readyToDestroyMockedConnection(connection);
      connection = undefined;
    }
    if (clientSockets.length) {
      clientSockets.forEach(function(clientSocket) {
        clientSocket.disconnect();
      });
    }
    if (server) {
      server.close();
      server = undefined;
    }
  });

  test('registeration of plugin commands', function(done) {
    var basePlugin = {
      getCommand: new model.SocketRequestResponse(),
      putCommand: new model.SocketRequestResponse(),
      postCommand: new model.SocketRequestResponse(),
      deleteCommand: new model.SocketRequestResponse(),
      ignored: new model.REST()
    };
    var overridingPlugin = {
      postCommand: new model.SocketRequestResponse(),
      deleteCommand: new model.SocketRequestResponse()
    };

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;

        var registeredCommands = socketIoAdaptor.register(application, server, {
          connection: utils.createStubbedBackendConnection(),
          plugins: [
            basePlugin,
            overridingPlugin
          ]
        });

        registeredCommands = registeredCommands.map(function(command) {
          return {
            name:       command.name,
            definition: command.definition
          };
        });
        assert.deepEqual(registeredCommands,
                         [{ name:       'search',
                            definition: scoketIoCommands.search },
                          { name:       'getCommand',
                            definition: basePlugin.getCommand },
                          { name:       'putCommand',
                            definition: basePlugin.putCommand },
                          { name:       'postCommand',
                            definition: overridingPlugin.postCommand },
                          { name:       'deleteCommand',
                            definition: overridingPlugin.deleteCommand }]);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  function createEnvelope(type, body) {
    var now = new Date();
    var envelope = {
      id:         now.getTime(),
      date:       now.toISOString(),
      replyTo:    'localhost:' + utils.testReceivePort,
      statusCode: 200,
      type:       type,
      body:       body
    };
    return envelope;
  }

  test('initialization', function(done) {
    var mockedListener = nodemock
      .mock('connected');

    var application = express();
    application.on('connection', function(socket) {
      mockedListener.connected();
    });

    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: utils.createStubbedBackendConnection(),
          plugins: [testPlugin]
        });

        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSockets.push(newClientSocket);
      })
      .wait(0.01)
      .next(function() {
        mockedListener.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('one way: single client, front to back', function(done) {
    connection = utils.createMockedBackendConnection(testPlugin);

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSockets.push(newClientSocket);
        connection.assertThrows();

        var messages = [
          Math.random(),
          Math.random(),
          Math.random()
        ];
        connection = connection
          .mock('emitMessage')
            .takes('publish-subscribe', messages[0], null, {})
          .mock('emitMessage')
            .takes('publish-subscribe', messages[1], null, {})
          .mock('emitMessage')
            .takes('publish-subscribe', messages[2], null, {});

        clientSockets[0].emit('publish-subscribe', messages[0]);
        clientSockets[0].emit('publish-subscribe', messages[1]);
        clientSockets[0].emit('publish-subscribe', messages[2]);
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('one way: single client, back to front', function(done) {
    connection = utils.createMockedBackendConnection(testPlugin);

    var messages = [
      Math.random(),
      Math.random(),
      Math.random()
    ];
    var clientReceiver = nodemock
          .mock('receive')
            .takes(messages[0])
          .mock('receive')
            .takes(messages[1])
          .mock('receive')
            .takes(messages[2]);

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSockets.push(newClientSocket);
        connection.assertThrows();

        clientSockets[0].on('publish-subscribe', function(data) {
          clientReceiver.receive(data);
        });

        connection.controllers['publish-subscribe']
          .trigger(createEnvelope('publish-subscribe', messages[0]));
        connection.controllers['publish-subscribe']
          .trigger(createEnvelope('publish-subscribe', messages[1]));
        connection.controllers['publish-subscribe']
          .trigger(createEnvelope('publish-subscribe', messages[2]));
      })
      .wait(0.01)
      .next(function() {
        clientReceiver.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('request-response style message: single client', function(done) {
    connection = utils.createMockedBackendConnection(testPlugin);
    var onReceived = [{}, {}, {}];
    var messages = [
      Math.random(),
      Math.random(),
      Math.random()
    ];
    var clientReceiver;

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSockets.push(newClientSocket);
        connection.assertThrows();

        connection = connection
          .mock('emitMessage')
            .takes('request-response', messages[0], function() {}, {})
            .ctrl(2, onReceived[0])
          .mock('emitMessage')
            .takes('request-response', messages[1], function() {}, {})
            .ctrl(2, onReceived[1])
          .mock('emitMessage')
            .takes('request-response', messages[2], function() {}, {})
            .ctrl(2, onReceived[2]);

        clientSockets[0].emit('request-response', messages[0]);
        clientSockets[0].emit('request-response', messages[1]);
        clientSockets[0].emit('request-response', messages[2]);
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();

        clientReceiver = nodemock
          .mock('receive')
            .takes(messages[0])
          .mock('receive')
            .takes(messages[1])
          .mock('receive')
            .takes(messages[2]);
        clientSockets[0].on('request-response', function(data) {
          clientReceiver.receive(data);
        });

        onReceived[0].trigger(null,
                              createEnvelope('request-response', messages[0]));
        onReceived[1].trigger(null,
                              createEnvelope('request-response', messages[1]));
        onReceived[2].trigger(null,
                              createEnvelope('request-response', messages[2]));
      })
      .wait(0.01)
      .next(function() {
        clientReceiver.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('front to back, extra command (without builder)', function(done) {
    var extraController = {};
    connection = utils.createMockedBackendConnection(testPlugin);

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });

        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSockets.push(newClientSocket);
        connection.assertThrows();

        var message = Math.random();
        connection = connection
          .mock('emitMessage')
            .takes('foobar', message, null, {});
        clientSockets[0].emit('foobar', message);
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('front to back, extra command (with builder)', function(done) {
    var extraController = {};
    connection = utils.createMockedBackendConnection(testPlugin);

    var mockedReceiver = nodemock
          .mock('receive')
            .takes('builder response');

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSockets.push(newClientSocket);
        connection.assertThrows();

        connection = connection
          .mock('emitMessage')
            .takes('builder', 'builder request', null, {});
        clientSockets[0].on('builder.result', function(data) {
          mockedReceiver.receive(data);
        });
        clientSockets[0].emit('builder', { requestMessage: true });
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();
        connection.controllers.builder.trigger({
          statusCode: 200,
          type: 'builder.result',
          body: { responseMessage: true }
        });
      })
      .wait(0.01)
      .next(function() {
        mockedReceiver.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('front to back, extra command (custom event name)', function(done) {
    var extraController = {};
    connection = utils.createMockedBackendConnection(testPlugin);

    var mockedReceiver = nodemock
          .mock('receive')
            .takes('custom response');

    var application = express();
    utils.setupServer(application)
      .next(function(newServer) {
        server = newServer;
        socketIoAdaptor.register(application, server, {
          connection: connection,
          plugins: [testPlugin]
        });
        return utils.createClientSocket();
      })
      .next(function(newClientSocket) {
        clientSockets.push(newClientSocket);
        connection.assertThrows();

        connection = connection
          .mock('emitMessage')
            .takes('custom', { requestMessage: true }, null, {});
        clientSockets[0].on('custom', function(data) {
          mockedReceiver.receive(data);
        });
        clientSockets[0].emit('customevent', { requestMessage: true });
      })
      .wait(0.01)
      .next(function() {
        connection.assertThrows();
        connection.controllers.customevent.trigger({
          statusCode: 200,
          type: 'customevent.result',
          body: { responseMessage: true }
        });
      })
      .wait(0.01)
      .next(function() {
        mockedReceiver.assertThrows();
        done();
      })
      .error(function(error) {
        done(error);
      });
  });
});

<|endoftext|>


<commit_before>exports['should correctly honor promoteValues when creating an instance using Db'] = {
  // Add a tag that our runner can trigger on
  // in this case we are setting that node needs to be higher than 0.10.X to run
  metadata: {
    requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
  },

  // The actual test we wish to run
  test: function(configuration, test) {
    var Long = configuration.require.Long,
      Int32 = configuration.require.Int32,
      Double = configuration.require.Double;

    var o = configuration.writeConcernMax();
    var client = configuration.newDbInstance(configuration.writeConcernMax(), {
      poolSize: 1,
      promoteValues: false
    });
    client.connect(function(err, client) {
      var db = client.db(configuration.database);

      db.collection('shouldCorrectlyHonorPromoteValues').insert({
        doc: Long.fromNumber(10),
        int: 10,
        double: 2.2222,
        array: [[Long.fromNumber(10)]]
      }, function(err, doc) {
        test.equal(null, err);

        db.collection('shouldCorrectlyHonorPromoteValues').findOne(function(err, doc) {
          test.equal(null, err);

          test.deepEqual(Long.fromNumber(10), doc.doc);
          test.deepEqual(new Int32(10), doc.int);
          test.deepEqual(new Double(2.2222), doc.double);

          client.close();
          test.done();
        });
      });
    });
  }
};

exports['should correctly honor promoteValues when creating an instance using MongoClient'] = {
  // Add a tag that our runner can trigger on
  // in this case we are setting that node needs to be higher than 0.10.X to run
  metadata: {
    requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
  },

  // The actual test we wish to run
  test: function(configuration, test) {
    var Long = configuration.require.Long,
      Int32 = configuration.require.Int32,
      Double = configuration.require.Double,
      MongoClient = configuration.require.MongoClient;

    MongoClient.connect(
      configuration.url(),
      {
        promoteValues: false
      },
      function(err, client) {
        var db = client.db(configuration.database);
        db.collection('shouldCorrectlyHonorPromoteValues').insert({
          doc: Long.fromNumber(10),
          int: 10,
          double: 2.2222,
          array: [[Long.fromNumber(10)]]
        }, function(err, doc) {
          test.equal(null, err);

          db.collection('shouldCorrectlyHonorPromoteValues').findOne(function(err, doc) {
            test.equal(null, err);

            test.deepEqual(Long.fromNumber(10), doc.doc);
            test.deepEqual(new Int32(10), doc.int);
            test.deepEqual(new Double(2.2222), doc.double);

            client.close();
            test.done();
          });
        });
      }
    );
  }
};

exports['should correctly honor promoteValues at cursor level'] = {
  // Add a tag that our runner can trigger on
  // in this case we are setting that node needs to be higher than 0.10.X to run
  metadata: {
    requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
  },

  // The actual test we wish to run
  test: function(configuration, test) {
    var Long = configuration.require.Long,
      Int32 = configuration.require.Int32,
      Double = configuration.require.Double,
      MongoClient = configuration.require.MongoClient;

    MongoClient.connect(
      configuration.url(),
      {
        promoteValues: false
      },
      function(err, client) {
        var db = client.db(configuration.database);
        db.collection('shouldCorrectlyHonorPromoteValues').insert({
          doc: Long.fromNumber(10),
          int: 10,
          double: 2.2222,
          array: [[Long.fromNumber(10)]]
        }, function(err, doc) {
          test.equal(null, err);

          db.collection('shouldCorrectlyHonorPromoteValues').find().next(function(err, doc) {
            test.equal(null, err);

            test.deepEqual(Long.fromNumber(10), doc.doc);
            test.deepEqual(new Int32(10), doc.int);
            test.deepEqual(new Double(2.2222), doc.double);

            client.close();
            test.done();
          });
        });
      }
    );
  }
};

exports['should correctly honor promoteValues at cursor find level'] = {
  // Add a tag that our runner can trigger on
  // in this case we are setting that node needs to be higher than 0.10.X to run
  metadata: {
    requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
  },

  // The actual test we wish to run
  test: function(configuration, test) {
    var Long = configuration.require.Long,
      Int32 = configuration.require.Int32,
      Double = configuration.require.Double,
      MongoClient = configuration.require.MongoClient;

    MongoClient.connect(configuration.url(), {}, function(err, client) {
      var db = client.db(configuration.database);
      db.collection('shouldCorrectlyHonorPromoteValues').insert({
        doc: Long.fromNumber(10),
        int: 10,
        double: 2.2222,
        array: [[Long.fromNumber(10)]]
      }, function(err, doc) {
        test.equal(null, err);

        db
          .collection('shouldCorrectlyHonorPromoteValues')
          .find({}, {}, { promoteValues: false })
          .next(function(err, doc) {
            test.equal(null, err);

            test.deepEqual(Long.fromNumber(10), doc.doc);
            test.deepEqual(new Int32(10), doc.int);
            test.deepEqual(new Double(2.2222), doc.double);

            client.close();
            test.done();
          });
      });
    });
  }
};

exports['should correctly honor promoteValues at aggregate level'] = {
  // Add a tag that our runner can trigger on
  // in this case we are setting that node needs to be higher than 0.10.X to run
  metadata: {
    requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
  },

  // The actual test we wish to run
  test: function(configuration, test) {
    var Long = configuration.require.Long,
      Int32 = configuration.require.Int32,
      Double = configuration.require.Double,
      MongoClient = configuration.require.MongoClient;

    MongoClient.connect(configuration.url(), {}, function(err, client) {
      var db = client.db(configuration.database);
      db.collection('shouldCorrectlyHonorPromoteValues2').insert({
        doc: Long.fromNumber(10),
        int: 10,
        double: 2.2222,
        array: [[Long.fromNumber(10)]]
      }, function(err, doc) {
        test.equal(null, err);

        db
          .collection('shouldCorrectlyHonorPromoteValues2')
          .aggregate([{ $match: {} }], { promoteValues: false })
          .next(function(err, doc) {
            test.equal(null, err);

            test.deepEqual(Long.fromNumber(10), doc.doc);
            test.deepEqual(new Int32(10), doc.int);
            test.deepEqual(new Double(2.2222), doc.double);

            client.close();
            test.done();
          });
      });
    });
  }
};

exports['Should correctly promoteValues when calling getMore on queries'] = {
  metadata: {
    requires: {
      node: '>0.8.0',
      topology: ['single', 'ssl', 'wiredtiger']
    }
  },

  // The actual test we wish to run
  test: function(configuration, test) {
    var MongoClient = configuration.require.MongoClient;
    var Long = configuration.require.Long;

    MongoClient.connect(configuration.url(), function(err, client) {
      var docs = new Array(150).fill(0).map(function(_, i) {
        return {
          _id: 'needle_' + i,
          is_even: i % 2,
          long: Long.fromString('1234567890'),
          double: 0.23456,
          int: 1234
        };
      });

      var db = client.db(configuration.database);

      db.collection('haystack').insert(docs, function(errInsert) {
        if (errInsert) throw errInsert;
        // change limit from 102 to 101 and this test passes.
        // seems to indicate that the promoteValues flag is used for the
        // initial find, but not for subsequent getMores
        db
          .collection('haystack')
          .find({}, { limit: 102, promoteValues: false })
          .on('data', function(doc) {
            test.equal(typeof doc.int, 'object');
            test.equal(doc.int._bsontype, 'Int32');
            test.equal(typeof doc.long, 'object');
            test.equal(doc.long._bsontype, 'Long');
            test.equal(typeof doc.double, 'object');
            test.equal(doc.double._bsontype, 'Double');
          })
          .on('end', function() {
            db.dropCollection('haystack', function() {
              client.close();
              test.done();
            });
          });
      });
    });
  }
};
<commit_msg>test(promote-values): convert `promote_values` tests to mocha style<commit_after>'use strict';
var test = require('./shared').assert;
var setupDatabase = require('./shared').setupDatabase;

describe('Promote Values', function() {
  before(function() {
    return setupDatabase(this.configuration);
  });

  it('should correctly honor promoteValues when creating an instance using Db', {
    // Add a tag that our runner can trigger on
    // in this case we are setting that node needs to be higher than 0.10.X to run
    metadata: {
      requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
    },

    // The actual test we wish to run
    test: function(done) {
      var configuration = this.configuration;
      var Long = configuration.require.Long,
        Int32 = configuration.require.Int32,
        Double = configuration.require.Double;

      var client = configuration.newClient(configuration.writeConcernMax(), {
        poolSize: 1,
        promoteValues: false
      });

      client.connect(function(err, client) {
        var db = client.db(configuration.db);

        db.collection('shouldCorrectlyHonorPromoteValues').insert({
          doc: Long.fromNumber(10),
          int: 10,
          double: 2.2222,
          array: [[Long.fromNumber(10)]]
        }, function(err) {
          test.equal(null, err);

          db.collection('shouldCorrectlyHonorPromoteValues').findOne(function(err, doc) {
            test.equal(null, err);

            test.deepEqual(Long.fromNumber(10), doc.doc);
            test.deepEqual(new Int32(10), doc.int);
            test.deepEqual(new Double(2.2222), doc.double);

            client.close();
            done();
          });
        });
      });
    }
  });

  it('should correctly honor promoteValues when creating an instance using MongoClient', {
    // Add a tag that our runner can trigger on
    // in this case we are setting that node needs to be higher than 0.10.X to run
    metadata: {
      requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
    },

    // The actual test we wish to run
    test: function(done) {
      var configuration = this.configuration;
      var Long = configuration.require.Long,
        Int32 = configuration.require.Int32,
        Double = configuration.require.Double,
        MongoClient = configuration.require.MongoClient;

      MongoClient.connect(
        configuration.url(),
        {
          promoteValues: false
        },
        function(err, client) {
          var db = client.db(configuration.db);
          db.collection('shouldCorrectlyHonorPromoteValues').insert({
            doc: Long.fromNumber(10),
            int: 10,
            double: 2.2222,
            array: [[Long.fromNumber(10)]]
          }, function(err) {
            test.equal(null, err);

            db.collection('shouldCorrectlyHonorPromoteValues').findOne(function(err, doc) {
              test.equal(null, err);

              test.deepEqual(Long.fromNumber(10), doc.doc);
              test.deepEqual(new Int32(10), doc.int);
              test.deepEqual(new Double(2.2222), doc.double);

              client.close();
              done();
            });
          });
        }
      );
    }
  });

  it('should correctly honor promoteValues at cursor level', {
    // Add a tag that our runner can trigger on
    // in this case we are setting that node needs to be higher than 0.10.X to run
    metadata: {
      requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
    },

    // The actual test we wish to run
    test: function(done) {
      var configuration = this.configuration;
      var Long = configuration.require.Long,
        Int32 = configuration.require.Int32,
        Double = configuration.require.Double,
        MongoClient = configuration.require.MongoClient;

      MongoClient.connect(
        configuration.url(),
        {
          promoteValues: false
        },
        function(err, client) {
          var db = client.db(configuration.db);
          db.collection('shouldCorrectlyHonorPromoteValues').insert({
            doc: Long.fromNumber(10),
            int: 10,
            double: 2.2222,
            array: [[Long.fromNumber(10)]]
          }, function(err) {
            test.equal(null, err);

            db.collection('shouldCorrectlyHonorPromoteValues').find().next(function(err, doc) {
              test.equal(null, err);

              test.deepEqual(Long.fromNumber(10), doc.doc);
              test.deepEqual(new Int32(10), doc.int);
              test.deepEqual(new Double(2.2222), doc.double);

              client.close();
              done();
            });
          });
        }
      );
    }
  });

  it('should correctly honor promoteValues at cursor find level', {
    // Add a tag that our runner can trigger on
    // in this case we are setting that node needs to be higher than 0.10.X to run
    metadata: {
      requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
    },

    // The actual test we wish to run
    test: function(done) {
      var configuration = this.configuration;
      var Long = configuration.require.Long,
        Int32 = configuration.require.Int32,
        Double = configuration.require.Double,
        MongoClient = configuration.require.MongoClient;

      MongoClient.connect(configuration.url(), {}, function(err, client) {
        var db = client.db(configuration.db);
        db.collection('shouldCorrectlyHonorPromoteValues').insert({
          doc: Long.fromNumber(10),
          int: 10,
          double: 2.2222,
          array: [[Long.fromNumber(10)]]
        }, function(err) {
          test.equal(null, err);

          db
            .collection('shouldCorrectlyHonorPromoteValues')
            .find({}, {}, { promoteValues: false })
            .next(function(err, doc) {
              test.equal(null, err);

              test.deepEqual(Long.fromNumber(10), doc.doc);
              test.deepEqual(new Int32(10), doc.int);
              test.deepEqual(new Double(2.2222), doc.double);

              client.close();
              done();
            });
        });
      });
    }
  });

  it('should correctly honor promoteValues at aggregate level', {
    // Add a tag that our runner can trigger on
    // in this case we are setting that node needs to be higher than 0.10.X to run
    metadata: {
      requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
    },

    // The actual test we wish to run
    test: function(done) {
      var configuration = this.configuration;
      var Long = configuration.require.Long,
        Int32 = configuration.require.Int32,
        Double = configuration.require.Double,
        MongoClient = configuration.require.MongoClient;

      MongoClient.connect(configuration.url(), {}, function(err, client) {
        var db = client.db(configuration.db);
        db.collection('shouldCorrectlyHonorPromoteValues2').insert({
          doc: Long.fromNumber(10),
          int: 10,
          double: 2.2222,
          array: [[Long.fromNumber(10)]]
        }, function(err) {
          test.equal(null, err);

          db
            .collection('shouldCorrectlyHonorPromoteValues2')
            .aggregate([{ $match: {} }], { promoteValues: false })
            .next(function(err, doc) {
              test.equal(null, err);

              test.deepEqual(Long.fromNumber(10), doc.doc);
              test.deepEqual(new Int32(10), doc.int);
              test.deepEqual(new Double(2.2222), doc.double);

              client.close();
              done();
            });
        });
      });
    }
  });

  it('Should correctly promoteValues when calling getMore on queries', {
    metadata: {
      requires: {
        node: '>0.8.0',
        topology: ['single', 'ssl', 'wiredtiger']
      }
    },

    // The actual test we wish to run
    test: function(done) {
      var configuration = this.configuration;
      var MongoClient = configuration.require.MongoClient;
      var Long = configuration.require.Long;

      MongoClient.connect(configuration.url(), function(err, client) {
        var docs = new Array(150).fill(0).map(function(_, i) {
          return {
            _id: 'needle_' + i,
            is_even: i % 2,
            long: Long.fromString('1234567890'),
            double: 0.23456,
            int: 1234
          };
        });

        var db = client.db(configuration.db);

        db.collection('haystack').insert(docs, function(errInsert) {
          if (errInsert) throw errInsert;
          // change limit from 102 to 101 and this test passes.
          // seems to indicate that the promoteValues flag is used for the
          // initial find, but not for subsequent getMores
          db
            .collection('haystack')
            .find({}, { limit: 102, promoteValues: false })
            .on('data', function(doc) {
              test.equal(typeof doc.int, 'object');
              test.equal(doc.int._bsontype, 'Int32');
              test.equal(typeof doc.long, 'object');
              test.equal(doc.long._bsontype, 'Long');
              test.equal(typeof doc.double, 'object');
              test.equal(doc.double._bsontype, 'Double');
            })
            .on('end', function() {
              db.dropCollection('haystack', function() {
                client.close();
                done();
              });
            });
        });
      });
    }
  });
});
<|endoftext|>


<commit_before>import nock from 'nock';

export default function() {
  nock('https://api.stripe.com:443', { encodedQueryParams: true })
    .post('/v1/customers', 'source=tok_1BvCA5DjPFcHOcTmg1234567&email=user1%40opencollective.com')
    .reply(
      200,
      {
        id: 'cus_BSeRpSPOYo1234',
        object: 'customer',
        account_balance: 0,
        created: 1506294253,
        currency: null,
        default_source: 'card_1B5j8xDjPFcHOcTmDV3bGhAI',
        delinquent: false,
        description: 'https://opencollective.com/john-smith',
        discount: null,
        email: '',
        livemode: false,
        metadata: {},
        shipping: null,
        sources: {
          object: 'list',
          data: [
            {
              id: 'card_1B5j8xDjPFcHOcTmDV3bGhAI',
              object: 'card',
              address_city: null,
              address_country: null,
              address_line1: null,
              address_line1_check: null,
              address_line2: null,
              address_state: null,
              address_zip: null,
              address_zip_check: null,
              brand: 'Visa',
              country: 'US',
              customer: 'cus_BSeRpSPOYoLmLY',
              cvc_check: 'pass',
              dynamic_last4: null,
              exp_month: 12,
              exp_year: 2028,
              fingerprint: 'ftgJeBXvQSZ4HMCg',
              funding: 'credit',
              last4: '4242',
              metadata: {},
              name: null,
              tokenization_method: null,
            },
          ],
          has_more: false,
          total_count: 1,
          url: '/v1/customers/cus_BSeRpSPOYoLmLY/sources',
        },
        subscriptions: {
          object: 'list',
          data: [],
          has_more: false,
          total_count: 0,
          url: '/v1/customers/cus_BSeRpSPOYoLmLY/subscriptions',
        },
      },
      ['Server'],
    );
  nock('https://api.stripe.com:443', { encodedQueryParams: true })
    .post('/v1/setup_intents', 'customer=cus_BSeRpSPOYo1234&payment_method=card_1B5j8xDjPFcHOcTmDV3bGhAI&confirm=true')
    .reply(
      200,
      {
        id: 'seti_123456789',
        object: 'setup_intent',
        application: null,
        cancellation_reason: null,
        client_secret: null,
        created: 123456789,
        customer: null,
        description: null,
        last_setup_error: null,
        livemode: false,
        metadata: {
          user_id: 'guest',
        },
        next_action: null,
        on_behalf_of: null,
        payment_method: null,
        payment_method_options: {},
        payment_method_types: ['card'],
        status: 'succeeded',
        usage: 'off_session',
      },
      ['Server'],
    );
}
<commit_msg>fix: test after nock update<commit_after>import nock from 'nock';

export default function() {
  nock('https://api.stripe.com:443', { encodedQueryParams: true })
    .post('/v1/customers', 'source=tok_1BvCA5DjPFcHOcTmg1234567&email=user1%40opencollective.com')
    .reply(200, {
      id: 'cus_BSeRpSPOYo1234',
      object: 'customer',
      account_balance: 0,
      created: 1506294253,
      currency: null,
      default_source: 'card_1B5j8xDjPFcHOcTmDV3bGhAI',
      delinquent: false,
      description: 'https://opencollective.com/john-smith',
      discount: null,
      email: '',
      livemode: false,
      metadata: {},
      shipping: null,
      sources: {
        object: 'list',
        data: [
          {
            id: 'card_1B5j8xDjPFcHOcTmDV3bGhAI',
            object: 'card',
            address_city: null,
            address_country: null,
            address_line1: null,
            address_line1_check: null,
            address_line2: null,
            address_state: null,
            address_zip: null,
            address_zip_check: null,
            brand: 'Visa',
            country: 'US',
            customer: 'cus_BSeRpSPOYoLmLY',
            cvc_check: 'pass',
            dynamic_last4: null,
            exp_month: 12,
            exp_year: 2028,
            fingerprint: 'ftgJeBXvQSZ4HMCg',
            funding: 'credit',
            last4: '4242',
            metadata: {},
            name: null,
            tokenization_method: null,
          },
        ],
        has_more: false,
        total_count: 1,
        url: '/v1/customers/cus_BSeRpSPOYoLmLY/sources',
      },
      subscriptions: {
        object: 'list',
        data: [],
        has_more: false,
        total_count: 0,
        url: '/v1/customers/cus_BSeRpSPOYoLmLY/subscriptions',
      },
    });
  nock('https://api.stripe.com:443', { encodedQueryParams: true })
    .post('/v1/setup_intents', 'customer=cus_BSeRpSPOYo1234&payment_method=card_1B5j8xDjPFcHOcTmDV3bGhAI&confirm=true')
    .reply(200, {
      id: 'seti_123456789',
      object: 'setup_intent',
      application: null,
      cancellation_reason: null,
      client_secret: null,
      created: 123456789,
      customer: null,
      description: null,
      last_setup_error: null,
      livemode: false,
      metadata: {
        user_id: 'guest',
      },
      next_action: null,
      on_behalf_of: null,
      payment_method: null,
      payment_method_options: {},
      payment_method_types: ['card'],
      status: 'succeeded',
      usage: 'off_session',
    });
}
<|endoftext|>