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

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

var Connection = require('../lib/backend/connection').Connection;

suite('Connection', function() {
  suite('initialization', function() {
    var connection;

    teardown(function() {
      if (connection) {
        connection.close();
        connection = undefined;
      }
    });

    function assertEventEmitter(object) {
      assert.equal(typeof object,
                   'object',
                   'should be an instance of EventEmitter');
      assert.equal(typeof object.emit,
                   'function',
                   'should be an instance of EventEmitter');
    }

    test('sender', function() {
      connection = new Connection({ tag: 'test' });
      assertEventEmitter(connection._sender);
    });

    test('receiver', function(done) {
      connection = new Connection({ tag: 'test' });
      assertEventEmitter(connection._receiver);
      assert.equal(connection.receivePort,
                   undefined,
                   'should be not-initialized');

      Deferred
        .wait(0.01)
        .next(function() {
          assert.notEqual(connection.receivePort,
                          undefined,
                          'should be initialized');
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });

  suite('simple communication', function() {
    var connection;
    var backend;

    setup(function(done) {
      utils.createBackend()
        .next(function(newBackend) {
          backend = newBackend;
          connection = new Connection({
            tag:      'test',
            hostName: 'localhost',
            port:     utils.testSendPort,
            receivePort: utils.testReceivePort,
            maxRetyrCount: 3,
            retryDelay: 1
          });
          done();
        });
    });

    teardown(function() {
      if (backend) {
        backend.close();
        backend = undefined;
      }
      if (connection) {
        connection.close();
        connection = undefined;
      }
    });

    function createMockedMessageCallback() {
      var mockedCallback = nodemock;
      var callback = function() {
        mockedCallback.receive.apply(mockedCallback, arguments);
      };
      callback.takes = function() {
        callback.assert = function() {
          mockedCallback.assertThrows();
        };
        mockedCallback = mockedCallback.mock('receive');
        mockedCallback = mockedCallback.takes.apply(mockedCallback, arguments);
        return this;
      };
      callback.mock = mockedCallback;
      return callback;
    }

    function getBackendReceivedMessages() {
      return backend.received.map(function(packet) {
        return packet[2];
      });
    }

    suite('one way message', function() {
      test('from front to back', function(done) {
        var objectMessage = connection.emitMessage('object', { command: 'foobar' });
        assert.envelopeEqual(objectMessage,
                             utils.createExpectedEnvelope('object',
                                                    { command: 'foobar' }));

        var stringMessage = connection.emitMessage('string', 'string');
        assert.envelopeEqual(stringMessage,
                             utils.createExpectedEnvelope('string', 'string'));

        var numericMessage = connection.emitMessage('numeric', 1234);
        assert.envelopeEqual(numericMessage,
                             utils.createExpectedEnvelope('numeric', 1234));

        Deferred
          .wait(0.01)
          .next(function() {
            assert.deepEqual(getBackendReceivedMessages(),
                             [objectMessage,
                              stringMessage,
                              numericMessage]);
            done();
          })
          .error(function(error) {
            done(error);
          });
      });

      test('from back to front', function(done) {
        var callback = createMockedMessageCallback();
        connection.on('string', callback);
        connection.on('numeric', callback);
        connection.on('object', callback);
        connection.on('unknown, ignored', callback);

        var stringMessage = utils.createEnvelope('string', 'string');
        var numericMessage = utils.createEnvelope('numeric', 1234);
        var objectMessage = utils.createEnvelope('object', { value: true });
        callback
          .takes(stringMessage.body)
          .takes(numericMessage.body)
          .takes(objectMessage.body);

        utils
          .sendPacketTo(utils.createPacket(stringMessage), utils.testReceivePort)
          .sendPacketTo(utils.createPacket(numericMessage), utils.testReceivePort)
          .sendPacketTo(utils.createPacket(objectMessage), utils.testReceivePort)
          .sendPacketTo(utils.createPacket({}, 'unknown, ignored'), utils.testReceivePort)
          .next(function() {
            callback.assert();
            done();
          })
          .error(function(error) {
            done(error);
          });
      });
    });

    suite('request-response', function() {
      test('success', function(done) {
        var callback = createMockedMessageCallback();
        var messages = [
          connection.emitMessage('first request', Math.random(), callback),
          connection.emitMessage('second request', Math.random(), callback)
        ];
        var responses = [
          utils.createReplyEnvelopeFor(messages[0], 'first response', Math.random()),
          utils.createReplyEnvelopeFor(messages[1], 'second response', Math.random())
        ];
        callback
          .takes(null, responses[0])
          .takes(null, responses[1]);
        Deferred
          .wait(0.01)
          .next(function() {
            assert.deepEqual(getBackendReceivedMessages(), messages);
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [1,1],
              'response listeners should be registered'
            );
          })
          .sendPacketTo(utils.createPacket(responses[0]), utils.testReceivePort)
          .sendPacketTo(utils.createPacket(responses[1]), utils.testReceivePort)
          .wait(0.01)
          .next(function() {
            callback.assert();
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [0,0],
              'response listeners should be removed'
            );
            done();
          })
          .error(function(error) {
            done(error);
          });
      });

      test('error', function(done) {
        var callback = createMockedMessageCallback();
        var messages = [
          connection.emitMessage('first request', Math.random(), callback),
          connection.emitMessage('second request', Math.random(), callback)
        ];
        var responses = [
          utils.createReplyEnvelopeFor(messages[0], 'first response', Math.random()),
          utils.createReplyEnvelopeFor(messages[1], 'second response', Math.random())
        ];
        // make them error responses
        responses[0].statusCode = 502;
        responses[1].statusCode = 503;
        callback
          .takes(responses[0].statusCode, responses[0])
          .takes(responses[1].statusCode, responses[1]);
        Deferred
          .wait(0.01)
          .next(function() {
            assert.deepEqual(getBackendReceivedMessages(), messages);
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [1,1],
              'response listeners should be registered'
            );
          })
          .sendPacketTo(utils.createPacket(responses[0]), utils.testReceivePort)
          .sendPacketTo(utils.createPacket(responses[1]), utils.testReceivePort)
          .wait(0.01)
          .next(function() {
            callback.assert();
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [0,0],
              'response listeners should be removed'
            );
            done();
          })
          .error(function(error) {
            done(error);
          });
      });

      test('duplicated', function(done) {
        var callback = createMockedMessageCallback();
        var messages = [
          connection.emitMessage('first request', Math.random(), callback),
          connection.emitMessage('second request', Math.random(), callback)
        ];
        var responses = [
          utils.createReplyEnvelopeFor(messages[0], 'first response', Math.random()),
          utils.createReplyEnvelopeFor(messages[1], 'second response', Math.random()),
          utils.createReplyEnvelopeFor(messages[0], 'duplicated, ignored', 0),
          utils.createReplyEnvelopeFor(messages[1], 'duplicated, ignored', 0)
        ];
        responses[1].statusCode = 503;
        callback
          .takes(null, responses[0])
          .takes(responses[1].statusCode, responses[1]);
        Deferred
          .wait(0.01)
          .next(function() {
            assert.deepEqual(getBackendReceivedMessages(), messages);
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [1,1],
              'response listeners should be registered'<commit_msg>test: Test registered listeners which shouldn't be called by replies<commit_after>var assert = require('chai').assert;
var nodemock = require('nodemock');
var Deferred = require('jsdeferred').Deferred;

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

var Connection = require('../lib/backend/connection').Connection;

suite('Connection', function() {
  suite('initialization', function() {
    var connection;

    teardown(function() {
      if (connection) {
        connection.close();
        connection = undefined;
      }
    });

    function assertEventEmitter(object) {
      assert.equal(typeof object,
                   'object',
                   'should be an instance of EventEmitter');
      assert.equal(typeof object.emit,
                   'function',
                   'should be an instance of EventEmitter');
    }

    test('sender', function() {
      connection = new Connection({ tag: 'test' });
      assertEventEmitter(connection._sender);
    });

    test('receiver', function(done) {
      connection = new Connection({ tag: 'test' });
      assertEventEmitter(connection._receiver);
      assert.equal(connection.receivePort,
                   undefined,
                   'should be not-initialized');

      Deferred
        .wait(0.01)
        .next(function() {
          assert.notEqual(connection.receivePort,
                          undefined,
                          'should be initialized');
          done();
        })
        .error(function(error) {
          done(error);
        });
    });
  });

  suite('simple communication', function() {
    var connection;
    var backend;

    setup(function(done) {
      utils.createBackend()
        .next(function(newBackend) {
          backend = newBackend;
          connection = new Connection({
            tag:      'test',
            hostName: 'localhost',
            port:     utils.testSendPort,
            receivePort: utils.testReceivePort,
            maxRetyrCount: 3,
            retryDelay: 1
          });
          done();
        });
    });

    teardown(function() {
      if (backend) {
        backend.close();
        backend = undefined;
      }
      if (connection) {
        connection.close();
        connection = undefined;
      }
    });

    function createMockedMessageCallback() {
      var mockedCallback = nodemock;
      var callback = function() {
        mockedCallback.receive.apply(mockedCallback, arguments);
      };
      callback.takes = function() {
        callback.assert = function() {
          mockedCallback.assertThrows();
        };
        mockedCallback = mockedCallback.mock('receive');
        mockedCallback = mockedCallback.takes.apply(mockedCallback, arguments);
        return this;
      };
      callback.mock = mockedCallback;
      return callback;
    }

    function getBackendReceivedMessages() {
      return backend.received.map(function(packet) {
        return packet[2];
      });
    }

    suite('one way message', function() {
      test('from front to back', function(done) {
        var objectMessage = connection.emitMessage('object', { command: 'foobar' });
        assert.envelopeEqual(objectMessage,
                             utils.createExpectedEnvelope('object',
                                                    { command: 'foobar' }));

        var stringMessage = connection.emitMessage('string', 'string');
        assert.envelopeEqual(stringMessage,
                             utils.createExpectedEnvelope('string', 'string'));

        var numericMessage = connection.emitMessage('numeric', 1234);
        assert.envelopeEqual(numericMessage,
                             utils.createExpectedEnvelope('numeric', 1234));

        Deferred
          .wait(0.01)
          .next(function() {
            assert.deepEqual(getBackendReceivedMessages(),
                             [objectMessage,
                              stringMessage,
                              numericMessage]);
            done();
          })
          .error(function(error) {
            done(error);
          });
      });

      test('from back to front', function(done) {
        var callback = createMockedMessageCallback();
        connection.on('string', callback);
        connection.on('numeric', callback);
        connection.on('object', callback);
        connection.on('unknown, ignored', callback);

        var stringMessage = utils.createEnvelope('string', 'string');
        var numericMessage = utils.createEnvelope('numeric', 1234);
        var objectMessage = utils.createEnvelope('object', { value: true });
        callback
          .takes(stringMessage.body)
          .takes(numericMessage.body)
          .takes(objectMessage.body);

        utils
          .sendPacketTo(utils.createPacket(stringMessage), utils.testReceivePort)
          .sendPacketTo(utils.createPacket(numericMessage), utils.testReceivePort)
          .sendPacketTo(utils.createPacket(objectMessage), utils.testReceivePort)
          .sendPacketTo(utils.createPacket({}, 'unknown, ignored'), utils.testReceivePort)
          .next(function() {
            callback.assert();
            done();
          })
          .error(function(error) {
            done(error);
          });
      });
    });

    suite('request-response', function() {
      test('success', function(done) {
        var callback = createMockedMessageCallback();

        // these events should not be emitted!
        connection.on('first response', callback);
        connection.on('second response', callback);

        var messages = [
          connection.emitMessage('first request', Math.random(), callback),
          connection.emitMessage('second request', Math.random(), callback)
        ];
        var responses = [
          utils.createReplyEnvelopeFor(messages[0], 'first response', Math.random()),
          utils.createReplyEnvelopeFor(messages[1], 'second response', Math.random())
        ];
        callback
          .takes(null, responses[0])
          .takes(null, responses[1]);
        Deferred
          .wait(0.01)
          .next(function() {
            assert.deepEqual(getBackendReceivedMessages(), messages);
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [1,1],
              'response listeners should be registered'
            );
          })
          .sendPacketTo(utils.createPacket(responses[0]), utils.testReceivePort)
          .sendPacketTo(utils.createPacket(responses[1]), utils.testReceivePort)
          .wait(0.01)
          .next(function() {
            callback.assert();
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [0,0],
              'response listeners should be removed'
            );
            done();
          })
          .error(function(error) {
            done(error);
          });
      });

      test('error', function(done) {
        var callback = createMockedMessageCallback();

        // these events should not be emitted!
        connection.on('first response', callback);
        connection.on('second response', callback);

        var messages = [
          connection.emitMessage('first request', Math.random(), callback),
          connection.emitMessage('second request', Math.random(), callback)
        ];
        var responses = [
          utils.createReplyEnvelopeFor(messages[0], 'first response', Math.random()),
          utils.createReplyEnvelopeFor(messages[1], 'second response', Math.random())
        ];
        // make them error responses
        responses[0].statusCode = 502;
        responses[1].statusCode = 503;
        callback
          .takes(responses[0].statusCode, responses[0])
          .takes(responses[1].statusCode, responses[1]);
        Deferred
          .wait(0.01)
          .next(function() {
            assert.deepEqual(getBackendReceivedMessages(), messages);
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [1,1],
              'response listeners should be registered'
            );
          })
          .sendPacketTo(utils.createPacket(responses[0]), utils.testReceivePort)
          .sendPacketTo(utils.createPacket(responses[1]), utils.testReceivePort)
          .wait(0.01)
          .next(function() {
            callback.assert();
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [0,0],
              'response listeners should be removed'
            );
            done();
          })
          .error(function(error) {
            done(error);
          });
      });

      test('duplicated', function(done) {
        var callback = createMockedMessageCallback();

        // these events should not be emitted!
        connection.on('first response', callback);
        connection.on('second response', callback);
        connection.on('duplicated, ignored', callback);

        var messages = [
          connection.emitMessage('first request', Math.random(), callback),
          connection.emitMessage('second request', Math.random(), callback)
        ];
        var responses = [
          utils.createReplyEnvelopeFor(messages[0], 'first response', Math.random()),
          utils.createReplyEnvelopeFor(messages[1], 'second response', Math.random()),
          utils.createReplyEnvelopeFor(messages[0], 'duplicated, ignored', 0),
          utils.createReplyEnvelopeFor(messages[1], 'duplicated, ignored', 0)
        ];
        responses[1].statusCode = 503;
        callback
          .takes(null, responses[0])
          .takes(responses[1].statusCode, responses[1]);
        Deferred
          .wait(0.01)
          .next(function() {
            assert.deepEqual(getBackendReceivedMessages(), messages);
            assert.deepEqual(
              [connection.listeners('reply:' + messages[0].id).length,
               connection.listeners('reply:' + messages[1].id).length],
              [1,1],
              'response listeners should be registered'
{'fraction_non_alphanumeric': 0.12590192902370784, 'fraction_numerical': 0.008933392234820595, 'mean_word_length': 2.0072324723247235, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5373036', 'n_tokens_mistral': 5168, 'n_tokens_neox': 5098, 'n_words': 943}