testClientHandler.py 49.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#
# Copyright (C) 2009  Nexedi SA
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import os
import unittest
import logging
21
import threading
22
from mock import Mock, ReturnValues
Grégory Wisniewski's avatar
Grégory Wisniewski committed
23
from neo.tests.base import NeoTestBase
24
from neo import protocol
25
from neo.protocol import Packet, UnexpectedPacketError, INVALID_UUID
26 27 28 29 30 31 32 33 34 35 36 37 38 39
from neo.protocol import ERROR, REQUEST_NODE_IDENTIFICATION, ACCEPT_NODE_IDENTIFICATION, \
     PING, PONG, ASK_PRIMARY_MASTER, ANSWER_PRIMARY_MASTER, ANNOUNCE_PRIMARY_MASTER, \
     REELECT_PRIMARY_MASTER, NOTIFY_NODE_INFORMATION, START_OPERATION, \
     STOP_OPERATION, ASK_LAST_IDS, ANSWER_LAST_IDS, ASK_PARTITION_TABLE, \
     ANSWER_PARTITION_TABLE, SEND_PARTITION_TABLE, NOTIFY_PARTITION_CHANGES, \
     ASK_UNFINISHED_TRANSACTIONS, ANSWER_UNFINISHED_TRANSACTIONS, \
     ASK_OBJECT_PRESENT, ANSWER_OBJECT_PRESENT, \
     DELETE_TRANSACTION, COMMIT_TRANSACTION, ASK_NEW_TID, ANSWER_NEW_TID, \
     FINISH_TRANSACTION, NOTIFY_TRANSACTION_FINISHED, LOCK_INFORMATION, \
     NOTIFY_INFORMATION_LOCKED, INVALIDATE_OBJECTS, UNLOCK_INFORMATION, \
     ASK_NEW_OIDS, ANSWER_NEW_OIDS, ASK_STORE_OBJECT, ANSWER_STORE_OBJECT, \
     ABORT_TRANSACTION, ASK_STORE_TRANSACTION, ANSWER_STORE_TRANSACTION, \
     ASK_OBJECT, ANSWER_OBJECT, ASK_TIDS, ANSWER_TIDS, ASK_TRANSACTION_INFORMATION, \
     ANSWER_TRANSACTION_INFORMATION, ASK_OBJECT_HISTORY, ANSWER_OBJECT_HISTORY, \
40
     ASK_OIDS, ANSWER_OIDS, INVALID_PTID, \
41 42 43 44 45 46 47
     NOT_READY_CODE, OID_NOT_FOUND_CODE, SERIAL_NOT_FOUND_CODE, TID_NOT_FOUND_CODE, \
     PROTOCOL_ERROR_CODE, TIMEOUT_ERROR_CODE, BROKEN_NODE_DISALLOWED_CODE, \
     INTERNAL_ERROR_CODE, \
     STORAGE_NODE_TYPE, CLIENT_NODE_TYPE, MASTER_NODE_TYPE, \
     RUNNING_STATE, BROKEN_STATE, TEMPORARILY_DOWN_STATE, DOWN_STATE, \
     UP_TO_DATE_STATE, OUT_OF_DATE_STATE, FEEDING_STATE, DISCARDED_STATE
from neo.exception import ElectionFailure
48 49
from neo.client.handler import BaseClientEventHandler, PrimaryBoostrapEventHandler, \
        PrimaryEventHandler, StorageBootstrapEventHandler, StorageEventHandler
50
from neo.node import StorageNode
51
from neo.util import dump
52 53 54

MARKER = []

Grégory Wisniewski's avatar
Grégory Wisniewski committed
55
class BaseClientEventHandlerTest(NeoTestBase):
56 57 58 59 60 61 62

    def setUp(self):
        dispatcher = Mock({'getQueue': queue, 'connectToPrimaryMasterNode': None})
        self.handler = BaseClientEventHandler(dispatcher)

    def getConnection(self, uuid=None, port=10010, next_id=None, ip='127.0.0.1'):
        if uuid is None:
Grégory Wisniewski's avatar
Grégory Wisniewski committed
63
            uuid = self.getNewUUID()
64
        return Mock({'_addPacket': None,
65 66 67 68 69 70 71
                     'getUUID': uuid,
                     'getAddress': (ip, port),
                     'getNextId': next_id,
                     'lock': None,
                     'unlock': None})


Grégory Wisniewski's avatar
Grégory Wisniewski committed
72
class ClientEventHandlerTest(NeoTestBase):
73 74 75 76 77 78 79

    def setUp(self):
        # Silence all log messages
        logging.basicConfig(level=logging.CRITICAL + 1)

    def getConnection(self, uuid=None, port=10010, next_id=None, ip='127.0.0.1'):
        if uuid is None:
Grégory Wisniewski's avatar
Grégory Wisniewski committed
80
            uuid = self.getNewUUID()
81
        return Mock({'_addPacket': None,
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
                     'getUUID': uuid,
                     'getAddress': (ip, port),
                     'getNextId': next_id,
                     'lock': None,
                     'unlock': None})

    def getDispatcher(self, queue=None):
      return Mock({'getQueue': queue, 'connectToPrimaryMasterNode': None})

    def test_ping(self):
        """
        Simplest test: check that a PING packet is answered by a PONG
        packet.
        """
        dispatcher = self.getDispatcher()
97
        client_handler = BaseClientEventHandler(None, dispatcher)
98
        conn = self.getConnection()
99
        client_handler.packetReceived(conn, protocol.ping())
Grégory Wisniewski's avatar
Grégory Wisniewski committed
100
        self.checkAnswerPacket(conn, protocol.PONG)
101 102 103 104 105

    def _testInitialMasterWithMethod(self, method):
        class App:
            primary_master_node = None
        app = App()
106
        method(self.getDispatcher(), app, PrimaryBoostrapEventHandler)
107 108
        self.assertEqual(app.primary_master_node, -1)

109
    def _testMasterWithMethod(self, method, handler_class):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
110
        uuid = self.getNewUUID()
111 112 113
        app = Mock({'connectToPrimaryMasterNode': None})
        app.primary_master_node = Mock({'getUUID': uuid})
        app.master_conn = Mock({'close': None, 'getUUID': uuid})
114
        dispatcher = self.getDispatcher()
115
        method(dispatcher, app, handler_class, uuid=uuid)
116 117 118 119
        # XXX: should connection closure be tested ? It's not implemented in all cases
        #self.assertEquals(len(App.master_conn.mockGetNamedCalls('close')), 1)
        #self.assertEquals(app.master_conn, None)
        #self.assertEquals(app.primary_master_node, None)
120
        self.assertEquals(len(app.mockGetNamedCalls('connectToPrimaryMasterNode')), 1)
121

122
    def _testStorageWithMethod(self, method, handler_class, state=TEMPORARILY_DOWN_STATE):
123 124
        storage_ip = '127.0.0.1'
        storage_port = 10011
Grégory Wisniewski's avatar
Grégory Wisniewski committed
125
        fake_storage_node_uuid = self.getNewUUID()
126
        fake_storage_node = Mock({'getUUID': fake_storage_node_uuid, 'getServer': (storage_ip, storage_port), 'getNodeType': STORAGE_NODE_TYPE})
127 128
        master_node_next_packet_id = 1
        class App:
Grégory Wisniewski's avatar
Grégory Wisniewski committed
129
            primary_master_node = Mock({'getUUID': self.getNewUUID()})
130
            nm = Mock({'getNodeByServer': fake_storage_node})
131
            cp = Mock({'removeConnection': None})
132
            master_conn = Mock({
133
                '_addPacket': None,
Grégory Wisniewski's avatar
Grégory Wisniewski committed
134
                'getUUID': self.getNewUUID(),
135 136 137 138 139
                'getAddress': ('127.0.0.1', 10010),
                'getNextId': master_node_next_packet_id,
                'lock': None,
                'unlock': None
            })
140 141 142
        app = App()
        conn = self.getConnection(port=storage_port, ip=storage_ip)
        key_1 = (id(conn), 0)
143
        queue_1 = Mock({'put': None, '__hash__': 1})
144 145 146 147 148 149 150
        # Fake another Storage connection by adding 1 to id(conn)
        key_2 = (id(conn) + 1, 0)
        queue_2 = Mock({'put': None, '__hash__': 2})
        class Dispatcher:
            message_table = {key_1: queue_1,
                             key_2: queue_2}
        dispatcher = Dispatcher()
151
        method(dispatcher, app, handler_class, conn=conn)
152
        # Check that master was notified of the failure
Grégory Wisniewski's avatar
Grégory Wisniewski committed
153
        (node_list, ) = self.checkNotifyNodeInformation(app.master_conn, decode=True)
154
          # Test sanity check
155
        # the test below is disabled because the msg_id is now set by the connection
Grégory Wisniewski's avatar
Grégory Wisniewski committed
156 157
        expected_node_list = [(STORAGE_NODE_TYPE, storage_ip, storage_port, fake_storage_node_uuid, state), ]
        self.assertEquals(node_list, expected_node_list)
158 159 160 161 162 163 164 165 166 167 168
        # Check that failed connection got removed from connection pool
        removeConnection_call_list = app.cp.mockGetNamedCalls('removeConnection')
          # Test sanity check
        self.assertEqual(len(removeConnection_call_list), 1)
        self.assertTrue(removeConnection_call_list[0].getParam(0) is fake_storage_node)
        # Check that fake packet was put into queue_1, and none in queue_2.
        queue_1_put_call_list = queue_1.mockGetNamedCalls('put')
        self.assertEqual(len(queue_1_put_call_list), 1)
        self.assertEqual(queue_1_put_call_list[0].getParam(0), (conn, None))
        self.assertEqual(len(queue_2.mockGetNamedCalls('put')), 0)

169 170
    def _testConnectionFailed(self, dispatcher, app, handler_class, uuid=None, conn=None):
        client_handler = handler_class(app, dispatcher)
171 172 173 174 175 176 177 178
        if conn is None:
            conn = self.getConnection(uuid=uuid)
        client_handler.connectionFailed(conn)

    def test_initialMasterConnectionFailed(self):
        self._testInitialMasterWithMethod(self._testConnectionFailed)

    def test_storageConnectionFailed(self):
179 180
        self._testStorageWithMethod(self._testConnectionFailed, 
                StorageBootstrapEventHandler)
181

182 183
    def _testConnectionClosed(self, dispatcher, app, handler_class, uuid=None, conn=None):
        client_handler = handler_class(app, dispatcher)
184 185 186 187 188 189 190 191
        if conn is None:
            conn = self.getConnection(uuid=uuid)
        client_handler.connectionClosed(conn)

    def test_initialMasterConnectionClosed(self):
        self._testInitialMasterWithMethod(self._testConnectionClosed)

    def test_masterConnectionClosed(self):
192 193
        self._testMasterWithMethod(self._testConnectionClosed,
                PrimaryEventHandler)
194 195

    def test_storageConnectionClosed(self):
196 197 198 199
        self._testStorageWithMethod(self._testConnectionClosed, 
                StorageBootstrapEventHandler)
        self._testStorageWithMethod(self._testConnectionClosed, 
                StorageEventHandler)
200

201 202
    def _testTimeoutExpired(self, dispatcher, app, handler_class, uuid=None, conn=None):
        client_handler = handler_class(app, dispatcher)
203 204 205 206 207 208 209 210
        if conn is None:
            conn = self.getConnection(uuid=uuid)
        client_handler.timeoutExpired(conn)

    def test_initialMasterTimeoutExpired(self):
        self._testInitialMasterWithMethod(self._testTimeoutExpired)

    def test_masterTimeoutExpired(self):
211
        self._testMasterWithMethod(self._testTimeoutExpired, PrimaryEventHandler)
212 213

    def test_storageTimeoutExpired(self):
214 215 216 217
        self._testStorageWithMethod(self._testTimeoutExpired, 
                StorageEventHandler)
        self._testStorageWithMethod(self._testTimeoutExpired, 
                StorageBootstrapEventHandler)
218

219 220
    def _testPeerBroken(self, dispatcher, app, handler_class, uuid=None, conn=None):
        client_handler = handler_class(app, dispatcher)
221 222 223 224 225 226 227 228
        if conn is None:
            conn = self.getConnection(uuid=uuid)
        client_handler.peerBroken(conn)

    def test_initialMasterPeerBroken(self):
        self._testInitialMasterWithMethod(self._testPeerBroken)

    def test_masterPeerBroken(self):
229
        self._testMasterWithMethod(self._testPeerBroken, PrimaryEventHandler)
230 231

    def test_storagePeerBroken(self):
232 233 234 235
        self._testStorageWithMethod(self._testPeerBroken,
                StorageBootstrapEventHandler, state=BROKEN_STATE)
        self._testStorageWithMethod(self._testPeerBroken,
                StorageEventHandler, state=BROKEN_STATE)
236 237

    def test_notReady(self):
238
        app = Mock({'setNodeNotReady': None})
239
        dispatcher = self.getDispatcher()
240
        client_handler = PrimaryBoostrapEventHandler(app, dispatcher)
241 242
        conn = self.getConnection()
        client_handler.handleNotReady(conn, None, None)
243
        self.assertEquals(len(app.mockGetNamedCalls('setNodeNotReady')), 1)
244 245 246
        client_handler = StorageBootstrapEventHandler(app, dispatcher)
        client_handler.handleNotReady(conn, None, None)
        self.assertEquals(len(app.mockGetNamedCalls('setNodeNotReady')), 2)
247 248 249 250 251 252 253 254

    def test_clientAcceptNodeIdentification(self):
        class App:
            nm = Mock({'getNodeByServer': None})
            storage_node = None
            pt = None
        app = App()
        dispatcher = self.getDispatcher()
255
        client_handler = PrimaryBoostrapEventHandler(app, dispatcher)
256
        conn = self.getConnection()
Grégory Wisniewski's avatar
Grégory Wisniewski committed
257
        uuid = self.getNewUUID()
258
        app.uuid = 'C' * 16
259 260
        client_handler.handleAcceptNodeIdentification(conn, None, CLIENT_NODE_TYPE,
                                                      uuid, '127.0.0.1', 10010,
261
                                                      0, 0, INVALID_UUID)
Grégory Wisniewski's avatar
Grégory Wisniewski committed
262
        self.checkClosed(conn)
263 264
        self.assertEquals(app.storage_node, None)
        self.assertEquals(app.pt, None)
265
        self.assertEquals(app.uuid, 'C' * 16)
266 267 268

    def test_masterAcceptNodeIdentification(self):
        node = Mock({'setUUID': None})
269 270 271
        class FakeLocal:
            from Queue import Queue
            queue = Queue()
272 273 274 275
        class App:
            nm = Mock({'getNodeByServer': node})
            storage_node = None
            pt = None
276
            local_var = FakeLocal()
277 278
        app = App()
        dispatcher = self.getDispatcher()
279
        client_handler = PrimaryBoostrapEventHandler(app, dispatcher)
280
        conn = self.getConnection()
Grégory Wisniewski's avatar
Grégory Wisniewski committed
281
        uuid = self.getNewUUID()
282 283
        your_uuid = 'C' * 16
        app.uuid = INVALID_UUID
284 285
        client_handler.handleAcceptNodeIdentification(conn, None, MASTER_NODE_TYPE,
                                                      uuid, '127.0.0.1', 10010,
286
                                                      10, 2, your_uuid)
Grégory Wisniewski's avatar
Grégory Wisniewski committed
287 288
        self.checkNotClosed(conn)
        self.checkUUIDSet(conn, uuid)
289 290
        self.assertEquals(app.storage_node, None)
        self.assertTrue(app.pt is not None)
291
        self.assertEquals(app.uuid, your_uuid)
292 293 294 295 296 297 298 299 300

    def test_storageAcceptNodeIdentification(self):
        node = Mock({'setUUID': None})
        class App:
            nm = Mock({'getNodeByServer': node})
            storage_node = None
            pt = None
        app = App()
        dispatcher = self.getDispatcher()
301
        client_handler = StorageBootstrapEventHandler(app, dispatcher)
302
        conn = self.getConnection()
Grégory Wisniewski's avatar
Grégory Wisniewski committed
303
        uuid = self.getNewUUID()
304
        app.uuid = 'C' * 16
305 306
        client_handler.handleAcceptNodeIdentification(conn, None, STORAGE_NODE_TYPE,
                                                      uuid, '127.0.0.1', 10010,
307
                                                      0, 0, INVALID_UUID)
Grégory Wisniewski's avatar
Grégory Wisniewski committed
308 309
        self.checkNotClosed(conn)
        self.checkUUIDSet(conn, uuid)
310
        self.assertEquals(app.pt,  None)
311
        self.assertEquals(app.uuid, 'C' * 16)
312 313 314

    def _testHandleUnexpectedPacketCalledWithMedhod(self, client_handler, method, args=(), kw=()):
        call_list = []
315
        self.assertRaises(UnexpectedPacketError, method, *args, **dict(kw))
316 317 318

    # Master node handler
    def test_initialAnswerPrimaryMaster(self):
319
        client_handler = PrimaryBoostrapEventHandler(None, self.getDispatcher())
320
        conn = Mock({'getUUID': None})
321
        self._testHandleUnexpectedPacketCalledWithMedhod(
322 323 324 325 326 327 328 329 330
            client_handler, client_handler.handleAnswerPrimaryMaster,
            args=(conn, None, 0, []))
        
    def test_nonMasterAnswerPrimaryMaster(self):
        for node_type in (CLIENT_NODE_TYPE, STORAGE_NODE_TYPE):
            node = Mock({'getNodeType': node_type})
            class App:
                nm = Mock({'getNodeByUUID': node, 'getNodeByServer': None, 'add': None})
            app = App()
331
            client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
332 333 334 335 336 337 338 339 340 341 342 343
            conn = self.getConnection()
            client_handler.handleAnswerPrimaryMaster(conn, None, 0, [])
            # Check that nothing happened
            self.assertEqual(len(app.nm.mockGetNamedCalls('getNodeByServer')), 0)
            self.assertEqual(len(app.nm.mockGetNamedCalls('add')), 0)

    def test_unknownNodeAnswerPrimaryMaster(self):
        node = Mock({'getNodeType': MASTER_NODE_TYPE})
        class App:
            nm = Mock({'getNodeByUUID': node, 'getNodeByServer': None, 'add': None})
            primary_master_node = None
        app = App()
344
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
345
        conn = self.getConnection()
Grégory Wisniewski's avatar
Grégory Wisniewski committed
346
        test_master_list = [('127.0.0.1', 10010, self.getNewUUID())]
347
        client_handler.handleAnswerPrimaryMaster(conn, None, INVALID_UUID, test_master_list)
348 349 350 351
        # Test sanity check
        getNodeByUUID_call_list = app.nm.mockGetNamedCalls('getNodeByUUID')
        self.assertEqual(len(getNodeByUUID_call_list), 1)
        self.assertEqual(getNodeByUUID_call_list[0].getParam(0), conn.getUUID())
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        # Check that yet-unknown master node got added
        getNodeByServer_call_list = app.nm.mockGetNamedCalls('getNodeByServer')
        add_call_list = app.nm.mockGetNamedCalls('add')
        self.assertEqual(len(getNodeByServer_call_list), 1)
        self.assertEqual(len(add_call_list), 1)
        address, port, test_uuid = test_master_list[0]
        getNodeByServer_call = getNodeByServer_call_list[0]
        add_call = add_call_list[0]
        self.assertEquals((address, port), getNodeByServer_call.getParam(0))
        node_instance = add_call.getParam(0)
        self.assertEquals(test_uuid, node_instance.getUUID())
        # Check that primary master was not updated (it is not known yet,
        # hence INVALID_UUID in call).
        self.assertEquals(app.primary_master_node, None)

    def test_knownNodeUnknownUUIDNodeAnswerPrimaryMaster(self):
        node = Mock({'getNodeType': MASTER_NODE_TYPE, 'getUUID': None, 'setUUID': None})
        class App:
            nm = Mock({'getNodeByUUID': node, 'getNodeByServer': node, 'add': None})
            primary_master_node = None
        app = App()
373
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
374
        conn = self.getConnection()
Grégory Wisniewski's avatar
Grégory Wisniewski committed
375
        test_node_uuid = self.getNewUUID()
376 377
        test_master_list = [('127.0.0.1', 10010, test_node_uuid)]
        client_handler.handleAnswerPrimaryMaster(conn, None, INVALID_UUID, test_master_list)
378 379 380 381 382 383 384
        # Test sanity checks
        getNodeByUUID_call_list = app.nm.mockGetNamedCalls('getNodeByUUID')
        self.assertEqual(len(getNodeByUUID_call_list), 1)
        self.assertEqual(getNodeByUUID_call_list[0].getParam(0), conn.getUUID())
        getNodeByServer_call_list = app.nm.mockGetNamedCalls('getNodeByServer')
        self.assertEqual(len(getNodeByServer_call_list), 1)
        self.assertEqual(getNodeByServer_call_list[0].getParam(0), test_master_list[0][:2])
385 386 387 388 389 390
        # Check that known master node did not get added
        getNodeByServer_call_list = app.nm.mockGetNamedCalls('getNodeByServer')
        add_call_list = app.nm.mockGetNamedCalls('add')
        self.assertEqual(len(getNodeByServer_call_list), 1)
        self.assertEqual(len(add_call_list), 0)
        # Check that node UUID got updated
Grégory Wisniewski's avatar
Grégory Wisniewski committed
391
        self.checkUUIDSet(node, test_node_uuid)
392 393 394 395 396
        # Check that primary master was not updated (it is not known yet,
        # hence INVALID_UUID in call).
        self.assertEquals(app.primary_master_node, None)

    def test_knownNodeKnownUUIDNodeAnswerPrimaryMaster(self):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
397
        test_node_uuid = self.getNewUUID()
398 399 400 401 402
        node = Mock({'getNodeType': MASTER_NODE_TYPE, 'getUUID': test_node_uuid, 'setUUID': None})
        class App:
            nm = Mock({'getNodeByUUID': node, 'getNodeByServer': node, 'add': None})
            primary_master_node = None
        app = App()
403
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
404 405 406
        conn = self.getConnection()
        test_master_list = [('127.0.0.1', 10010, test_node_uuid)]
        client_handler.handleAnswerPrimaryMaster(conn, None, INVALID_UUID, test_master_list)
407 408 409 410
        # Test sanity checks
        getNodeByUUID_call_list = app.nm.mockGetNamedCalls('getNodeByUUID')
        self.assertEqual(len(getNodeByUUID_call_list), 1)
        self.assertEqual(getNodeByUUID_call_list[0].getParam(0), conn.getUUID())
411 412
        getNodeByServer_call_list = app.nm.mockGetNamedCalls('getNodeByServer')
        self.assertEqual(len(getNodeByServer_call_list), 1)
413 414 415
        self.assertEqual(getNodeByServer_call_list[0].getParam(0), test_master_list[0][:2])
        # Check that known master node did not get added
        add_call_list = app.nm.mockGetNamedCalls('add')
416 417 418 419 420
        self.assertEqual(len(add_call_list), 0)
        # Check that node UUID was untouched
        # XXX: should we just check that there was either no call or a call
        # with same uuid, or enforce no call ? Here we enforce no call just
        # because it's what implementation does.
Grégory Wisniewski's avatar
Grégory Wisniewski committed
421
        self.checkNoUUIDSet(node)
422 423 424 425 426 427 428 429
        # Check that primary master was not updated (it is not known yet,
        # hence INVALID_UUID in call).
        self.assertEquals(app.primary_master_node, None)

    # TODO: test known node, known but different uuid (not detected in code,
    # desired behaviour unknown)

    def test_alreadyDifferentPrimaryAnswerPrimaryMaster(self):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
430
        test_node_uuid = self.getNewUUID()
431 432
        test_primary_node_uuid = test_node_uuid
        while test_primary_node_uuid == test_node_uuid:
Grégory Wisniewski's avatar
Grégory Wisniewski committed
433
            test_primary_node_uuid = self.getNewUUID()
434 435 436 437 438 439
        test_primary_master_node = Mock({'getUUID': test_primary_node_uuid})
        node = Mock({'getNodeType': MASTER_NODE_TYPE, 'getUUID': test_node_uuid, 'setUUID': None})
        class App:
            nm = Mock({'getNodeByUUID': node, 'getNodeByServer': node, 'add': None})
            primary_master_node = test_primary_master_node
        app = App()
440
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
441 442 443 444 445 446
        conn = self.getConnection()
        # If primary master is already set *and* is not given primary master
        # handle call raises.
        # XXX: is it acceptable for a handle call to raise without any proper fallback ?
        self.assertRaises(ElectionFailure, client_handler.handleAnswerPrimaryMaster,
                          conn, None, test_node_uuid, [])
447 448 449 450 451 452
        # Test sanity checks
        getNodeByUUID_call_list = app.nm.mockGetNamedCalls('getNodeByUUID')
        self.assertEqual(len(getNodeByUUID_call_list), 1)
        self.assertEqual(getNodeByUUID_call_list[0].getParam(0), conn.getUUID())
        getNodeByServer_call_list = app.nm.mockGetNamedCalls('getNodeByServer')
        self.assertEqual(len(getNodeByServer_call_list), 0)
453 454

    def test_alreadySamePrimaryAnswerPrimaryMaster(self):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
455
        test_node_uuid = self.getNewUUID()
456 457 458 459 460
        node = Mock({'getNodeType': MASTER_NODE_TYPE, 'getUUID': test_node_uuid, 'setUUID': None})
        class App:
            nm = Mock({'getNodeByUUID': node, 'getNodeByServer': node, 'add': None})
            primary_master_node = node
        app = App()
461
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
462 463 464 465 466 467
        conn = self.getConnection()
        client_handler.handleAnswerPrimaryMaster(conn, None, test_node_uuid, [])
        # Check that primary node is (still) node.
        self.assertTrue(app.primary_master_node is node)

    def test_unknownNewPrimaryAnswerPrimaryMaster(self):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
468
        test_node_uuid = self.getNewUUID()
469 470
        test_primary_node_uuid = test_node_uuid
        while test_primary_node_uuid == test_node_uuid:
Grégory Wisniewski's avatar
Grégory Wisniewski committed
471
            test_primary_node_uuid = self.getNewUUID()
472 473 474 475 476
        node = Mock({'getNodeType': MASTER_NODE_TYPE, 'getUUID': test_node_uuid, 'setUUID': None})
        class App:
            nm = Mock({'getNodeByUUID': ReturnValues(node, None), 'getNodeByServer': node, 'add': None})
            primary_master_node = None
        app = App()
477
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
478 479
        conn = self.getConnection()
        client_handler.handleAnswerPrimaryMaster(conn, None, test_primary_node_uuid, [])
480 481 482 483 484
        # Test sanity checks
        getNodeByUUID_call_list = app.nm.mockGetNamedCalls('getNodeByUUID')
        self.assertEqual(len(getNodeByUUID_call_list), 2)
        self.assertEqual(getNodeByUUID_call_list[0].getParam(0), conn.getUUID())
        self.assertEqual(getNodeByUUID_call_list[1].getParam(0), test_primary_node_uuid)
485 486 487 488
        # Check that primary node was not updated.
        self.assertTrue(app.primary_master_node is None)

    def test_AnswerPrimaryMaster(self):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
489
        test_node_uuid = self.getNewUUID()
490 491 492 493 494
        node = Mock({'getNodeType': MASTER_NODE_TYPE, 'getUUID': test_node_uuid, 'setUUID': None})
        class App:
            nm = Mock({'getNodeByUUID': node, 'getNodeByServer': node, 'add': None})
            primary_master_node = None
        app = App()
495
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
496 497 498
        conn = self.getConnection()
        test_master_list = [('127.0.0.1', 10010, test_node_uuid)]
        client_handler.handleAnswerPrimaryMaster(conn, None, test_node_uuid, test_master_list)
499 500 501 502 503 504 505 506
        # Test sanity checks
        getNodeByUUID_call_list = app.nm.mockGetNamedCalls('getNodeByUUID')
        self.assertEqual(len(getNodeByUUID_call_list), 2)
        self.assertEqual(getNodeByUUID_call_list[0].getParam(0), conn.getUUID())
        self.assertEqual(getNodeByUUID_call_list[1].getParam(0), test_node_uuid)
        getNodeByServer_call_list = app.nm.mockGetNamedCalls('getNodeByServer')
        self.assertEqual(len(getNodeByServer_call_list), 1)
        self.assertEqual(getNodeByServer_call_list[0].getParam(0), test_master_list[0][:2])
507 508 509 510
        # Check that primary master was updated to known node
        self.assertTrue(app.primary_master_node is node)

    def test_initialSendPartitionTable(self):
511
        client_handler = PrimaryBoostrapEventHandler(None, self.getDispatcher())
512
        conn = Mock({'getUUID': None})
513
        self._testHandleUnexpectedPacketCalledWithMedhod(
514 515 516 517 518 519 520 521 522 523
            client_handler, client_handler.handleSendPartitionTable,
            args=(conn, None, None, None))

    def test_nonMasterSendPartitionTable(self):
        for node_type in (CLIENT_NODE_TYPE, STORAGE_NODE_TYPE):
            node = Mock({'getNodeType': node_type})
            class App:
                nm = Mock({'getNodeByUUID': node})
                pt = None
            app = App()
524
            client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
525 526 527 528 529 530 531 532 533 534 535 536 537
            conn = self.getConnection()
            client_handler.handleSendPartitionTable(conn, None, 0, [])
            # Check that nothing happened
            self.assertTrue(app.pt is None)

    def test_newSendPartitionTable(self):
        node = Mock({'getNodeType': MASTER_NODE_TYPE})
        test_ptid = 0
        class App:
            nm = Mock({'getNodeByUUID': node})
            pt = Mock({'clear': None})
            ptid = test_ptid
        app = App()
538
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
539 540 541 542 543 544 545 546 547 548 549 550 551
        conn = self.getConnection()
        client_handler.handleSendPartitionTable(conn, None, test_ptid + 1, [])
        # Check that partition table got cleared and ptid got updated
        self.assertEquals(app.ptid, test_ptid + 1)
        self.assertEquals(len(app.pt.mockGetNamedCalls('clear')), 1)

    def test_unknownNodeSendPartitionTable(self):
        test_node = Mock({'getNodeType': MASTER_NODE_TYPE})
        test_ptid = 0
        class App:
            nm = Mock({'getNodeByUUID': ReturnValues(test_node, None), 'add': None})
            pt = Mock({'setCell': None})
            ptid = test_ptid
Grégory Wisniewski's avatar
Grégory Wisniewski committed
552
        test_storage_uuid = self.getNewUUID()
553
        app = App()
554
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
555 556 557 558 559 560 561 562 563 564 565 566
        conn = self.getConnection()
        # TODO: use realistic values
        test_row_list = [(0, [(test_storage_uuid, 0)])]
        client_handler.handleSendPartitionTable(conn, None, test_ptid, test_row_list)
        # Check that node got created
        add_call_list = app.nm.mockGetNamedCalls('add')
        self.assertEquals(len(add_call_list), 1)
        created_node = add_call_list[0].getParam(0)
        self.assertEqual(created_node.getUUID(), test_storage_uuid)
        # Check that partition table cell got added
        setCell_call_list = app.pt.mockGetNamedCalls('setCell')
        self.assertEquals(len(setCell_call_list), 1)
567 568
        setCell_call_list[0].checkArgs(test_row_list[0][0], created_node,
                test_row_list[0][1][0][1])
569 570 571 572 573 574 575 576

    def test_knownNodeSendPartitionTable(self):
        test_node = Mock({'getNodeType': MASTER_NODE_TYPE})
        test_ptid = 0
        class App:
            nm = Mock({'getNodeByUUID': test_node, 'add': None})
            pt = Mock({'setCell': None})
            ptid = test_ptid
Grégory Wisniewski's avatar
Grégory Wisniewski committed
577
        test_storage_uuid = self.getNewUUID()
578
        app = App()
579
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
580 581 582 583 584 585 586 587 588
        conn = self.getConnection()
        # TODO: use realistic values
        test_row_list = [(0, [(test_storage_uuid, 0)])]
        client_handler.handleSendPartitionTable(conn, None, test_ptid, test_row_list)
        # Check that node did not get created
        self.assertEquals(len(app.nm.mockGetNamedCalls('add')), 0)
        # Check that partition table cell got added
        setCell_call_list = app.pt.mockGetNamedCalls('setCell')
        self.assertEquals(len(setCell_call_list), 1)
589 590
        setCell_call_list[0].checkArgs(test_row_list[0][0], test_node,
                test_row_list[0][1][0][1])
591 592

    def test_initialNotifyNodeInformation(self):
593
        client_handler = PrimaryBoostrapEventHandler(None, self.getDispatcher())
594
        conn = Mock({'getUUID': None})
595
        self._testHandleUnexpectedPacketCalledWithMedhod(
596 597 598 599 600
            client_handler, client_handler.handleNotifyNodeInformation,
            args=(conn, None, None))

    def test_nonMasterNotifyNodeInformation(self):
        for node_type in (CLIENT_NODE_TYPE, STORAGE_NODE_TYPE):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
601
            test_master_uuid = self.getNewUUID()
602 603 604 605
            node = Mock({'getNodeType': node_type})
            class App:
                nm = Mock({'getNodeByUUID': node})
            app = App()
606
            client_handler = PrimaryEventHandler(app, self.getDispatcher())
607
            conn = self.getConnection(uuid=test_master_uuid)
608
            client_handler.handleNotifyNodeInformation(conn, None, ())
609 610 611 612 613 614

    def test_nonIterableParameterRaisesNotifyNodeInformation(self):
        # XXX: this test is here for sanity self-check: it verifies the
        # assumption described in test_nonMasterNotifyNodeInformation
        # by making a valid call with a non-iterable parameter given as
        # node_list value.
Grégory Wisniewski's avatar
Grégory Wisniewski committed
615
        test_master_uuid = self.getNewUUID()
616 617 618 619
        node = Mock({'getNodeType': MASTER_NODE_TYPE})
        class App:
            nm = Mock({'getNodeByUUID': node})
        app = App()
620
        client_handler = PrimaryEventHandler(app, self.getDispatcher())
621 622 623 624 625 626 627 628
        conn = self.getConnection(uuid=test_master_uuid)
        self.assertRaises(TypeError, client_handler.handleNotifyNodeInformation,
            conn, None, None)

    def _testNotifyNodeInformation(self, test_node, getNodeByServer=None, getNodeByUUID=MARKER):
        invalid_uid_test_node = (test_node[0], test_node[1], test_node[2] + 1,
                                 INVALID_UUID, test_node[4])
        test_node_list = [test_node, invalid_uid_test_node]
Grégory Wisniewski's avatar
Grégory Wisniewski committed
629
        test_master_uuid = self.getNewUUID()
630 631 632 633 634 635 636 637 638
        node = Mock({'getNodeType': MASTER_NODE_TYPE})
        if getNodeByUUID is not MARKER:
            getNodeByUUID = ReturnValues(node, getNodeByUUID)
        class App:
            nm = Mock({'getNodeByUUID': getNodeByUUID,
                       'getNodeByServer': getNodeByServer,
                       'add': None,
                       'remove': None})
        app = App()
639 640
        #client_handler = ClientEventHandler(app, selClientEventHandlerf.getDispatcher())
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
641 642 643 644 645 646
        conn = self.getConnection(uuid=test_master_uuid)
        client_handler.handleNotifyNodeInformation(conn, None, test_node_list)
        # Return nm so caller can check handler actions.
        return app.nm

    def test_unknownMasterNotifyNodeInformation(self):
647
        # first notify unknown master nodes
Grégory Wisniewski's avatar
Grégory Wisniewski committed
648
        uuid = self.getNewUUID()
649 650 651 652 653 654 655 656 657 658
        test_node = (MASTER_NODE_TYPE, '127.0.0.1', 10010, uuid,
                     RUNNING_STATE)
        nm = self._testNotifyNodeInformation(test_node, getNodeByUUID=None)
        # Check that two nodes got added (second is with INVALID_UUID)
        add_call_list = nm.mockGetNamedCalls('add')
        self.assertEqual(len(add_call_list), 2)
        added_node = add_call_list[0].getParam(0)
        self.assertEquals(added_node.getUUID(), uuid)
        added_node = add_call_list[1].getParam(0)
        self.assertEquals(added_node.getUUID(), None)
659 660

    def test_knownMasterNotifyNodeInformation(self):
661
        node = Mock({})
Grégory Wisniewski's avatar
Grégory Wisniewski committed
662
        uuid = self.getNewUUID()
663 664 665 666 667 668 669
        test_node = (MASTER_NODE_TYPE, '127.0.0.1', 10010, uuid,
                     RUNNING_STATE)
        nm = self._testNotifyNodeInformation(test_node, getNodeByServer=node,
                getNodeByUUID=node)
        # Check that no node got added
        self.assertEqual(len(nm.mockGetNamedCalls('add')), 0)
        add_call_list = node.mockGetNamedCalls('add')
670 671

    def test_unknownStorageNotifyNodeInformation(self):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
672
        test_node = (STORAGE_NODE_TYPE, '127.0.0.1', 10010, self.getNewUUID(),
673
                     RUNNING_STATE)
674 675 676 677 678 679 680 681 682 683 684 685 686
        nm = self._testNotifyNodeInformation(test_node, getNodeByUUID=None)
        # Check that node got added
        add_call_list = nm.mockGetNamedCalls('add')
        self.assertEqual(len(add_call_list), 1)
        added_node = add_call_list[0].getParam(0)
        # XXX: this test does not check that node state got updated.
        # This is because there would be no way to tell the difference between
        # an updated state and default state if they are the same value (we
        # don't control node class/instance here)
        # Likewise for server address and node uuid.

    def test_knownStorageNotifyNodeInformation(self):
        node = Mock({'setState': None, 'setServer': None})
Grégory Wisniewski's avatar
Grégory Wisniewski committed
687
        test_node = (STORAGE_NODE_TYPE, '127.0.0.1', 10010, self.getNewUUID(),
688
                     RUNNING_STATE)
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
        nm = self._testNotifyNodeInformation(test_node, getNodeByUUID=node)
        # Check that no node got added
        self.assertEqual(len(nm.mockGetNamedCalls('add')), 0)
        # Check that server address got set
        setServer_call_list = node.mockGetNamedCalls('setServer')
        self.assertEqual(len(setServer_call_list), 1)
        self.assertEqual(setServer_call_list[0].getParam(0),
                         (test_node[1], test_node[2]))
        # Check node state has been updated
        setState_call_list = node.mockGetNamedCalls('setState')
        self.assertEqual(len(setState_call_list), 1)
        self.assertEqual(setState_call_list[0].getParam(0), test_node[4])

    def test_initialNotifyPartitionChanges(self):
        class App:
            nm = None
            pt = None
706
            ptid = INVALID_PTID
707
        app = App()
708
        client_handler = PrimaryBoostrapEventHandler(app, self.getDispatcher())
709
        conn = Mock({'getUUID': None})
710
        self._testHandleUnexpectedPacketCalledWithMedhod(
711 712 713 714 715
            client_handler, client_handler.handleNotifyPartitionChanges,
            args=(conn, None, None, None))

    def test_nonMasterNotifyPartitionChanges(self):
        for node_type in (CLIENT_NODE_TYPE, STORAGE_NODE_TYPE):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
716
            test_master_uuid = self.getNewUUID()
717 718 719 720
            node = Mock({'getNodeType': node_type, 'getUUID': test_master_uuid})
            class App:
                nm = Mock({'getNodeByUUID': node})
                pt = None
721
                ptid = INVALID_PTID
722 723
                primary_master_node = node
            app = App()
724
            client_handler = PrimaryEventHandler(app, self.getDispatcher())
725 726 727 728 729 730 731 732 733 734
            conn = self.getConnection(uuid=test_master_uuid)
            client_handler.handleNotifyPartitionChanges(conn, None, 0, [])
            # Check that nothing happened
            self.assertTrue(app.pt is None)

    def test_noPrimaryMasterNotifyPartitionChanges(self):
        node = Mock({'getNodeType': MASTER_NODE_TYPE})
        class App:
            nm = Mock({'getNodeByUUID': node})
            pt = None
735
            ptid = INVALID_PTID
736 737
            primary_master_node = None
        app = App()
738
        client_handler = PrimaryEventHandler(app, self.getDispatcher())
739 740 741 742 743 744
        conn = self.getConnection()
        client_handler.handleNotifyPartitionChanges(conn, None, 0, [])
        # Check that nothing happened
        self.assertTrue(app.pt is None)

    def test_nonPrimaryMasterNotifyPartitionChanges(self):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
745
        test_master_uuid = self.getNewUUID()
746 747
        test_sender_uuid = test_master_uuid
        while test_sender_uuid == test_master_uuid:
Grégory Wisniewski's avatar
Grégory Wisniewski committed
748
            test_sender_uuid = self.getNewUUID()
749 750 751 752 753
        node = Mock({'getNodeType': MASTER_NODE_TYPE})
        test_master_node = Mock({'getUUID': test_master_uuid})
        class App:
            nm = Mock({'getNodeByUUID': node})
            pt = None
754
            ptid = INVALID_PTID
755 756
            primary_master_node = test_master_node
        app = App()
757
        client_handler = PrimaryEventHandler(app, self.getDispatcher())
758 759 760 761 762 763
        conn = self.getConnection(uuid=test_sender_uuid)
        client_handler.handleNotifyPartitionChanges(conn, None, 0, [])
        # Check that nothing happened
        self.assertTrue(app.pt is None)

    def test_ignoreOutdatedPTIDNotifyPartitionChanges(self):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
764
        test_master_uuid = self.getNewUUID()
765 766 767 768 769 770 771 772
        node = Mock({'getNodeType': MASTER_NODE_TYPE, 'getUUID': test_master_uuid})
        test_ptid = 1
        class App:
            nm = Mock({'getNodeByUUID': node})
            pt = None
            primary_master_node = node
            ptid = test_ptid
        app = App()
773
        client_handler = PrimaryEventHandler(app, self.getDispatcher())
774 775 776 777 778 779 780
        conn = self.getConnection(uuid=test_master_uuid)
        client_handler.handleNotifyPartitionChanges(conn, None, test_ptid, [])
        # Check that nothing happened
        self.assertTrue(app.pt is None)
        self.assertEquals(app.ptid, test_ptid)

    def test_unknownNodeNotifyPartitionChanges(self):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
781
        test_master_uuid = self.getNewUUID()
782 783 784
        test_node = Mock({'getNodeType': MASTER_NODE_TYPE, 'getUUID': test_master_uuid})
        test_ptid = 1
        class App:
785
            nm = Mock({'getNodeByUUID': ReturnValues(None)})
786 787 788 789 790
            pt = Mock({'setCell': None})
            primary_master_node = test_node
            ptid = test_ptid
            uuid = None # XXX: Is it really needed ?
        app = App()
791
        client_handler = PrimaryEventHandler(app, self.getDispatcher())
792
        conn = self.getConnection(uuid=test_master_uuid)
Grégory Wisniewski's avatar
Grégory Wisniewski committed
793
        test_storage_uuid = self.getNewUUID()
794
        # TODO: use realistic values
795
        test_cell_list = [(0, test_storage_uuid, UP_TO_DATE_STATE)]
796 797 798 799 800 801 802 803
        client_handler.handleNotifyPartitionChanges(conn, None, test_ptid + 1, test_cell_list)
        # Check that a new node got added
        add_call_list = app.nm.mockGetNamedCalls('add')
        self.assertEqual(len(add_call_list), 1)
        added_node = add_call_list[0].getParam(0)
        # Check that partition got updated
        self.assertEqual(app.ptid, test_ptid + 1)
        setCell_call_list = app.pt.mockGetNamedCalls('setCell')
804 805
        setCell_call_list[0].checkArgs(test_cell_list[0][0], added_node,
                test_cell_list[0][2])
806 807 808 809 810

    # TODO: confirm condition under which an unknown node should be added with a TEMPORARILY_DOWN_STATE (implementation is unclear)

    def test_knownNodeNotifyPartitionChanges(self):
        test_ptid = 1
Grégory Wisniewski's avatar
Grégory Wisniewski committed
811 812
        uuid1, uuid2 = self.getNewUUID(), self.getNewUUID()
        uuid3, uuid4 = self.getNewUUID(), self.getNewUUID()
813
        test_node = Mock({'getNodeType': MASTER_NODE_TYPE, 'getUUID': uuid1})
814
        class App:
815
            nm = Mock({'getNodeByUUID': ReturnValues(test_node, None, None, None), 'add': None})
816 817 818
            pt = Mock({'setCell': None})
            primary_master_node = test_node
            ptid = test_ptid
819
            uuid = uuid4
820
        app = App()
821 822 823 824 825 826 827 828
        client_handler = PrimaryEventHandler(app, self.getDispatcher())
        conn = self.getConnection(uuid=uuid1)
        test_cell_list = [
            (0, uuid1, UP_TO_DATE_STATE),
            (0, uuid2, DISCARDED_STATE),
            (0, uuid3, FEEDING_STATE),
            (0, uuid4, UP_TO_DATE_STATE),
        ]
829
        client_handler.handleNotifyPartitionChanges(conn, None, test_ptid + 1, test_cell_list)
830 831 832 833 834 835 836 837
        # Check that the three last node got added
        calls = app.nm.mockGetNamedCalls('add')
        self.assertEquals(len(calls), 3)
        self.assertEquals(calls[0].getParam(0).getUUID(), uuid2)
        self.assertEquals(calls[1].getParam(0).getUUID(), uuid3)
        self.assertEquals(calls[2].getParam(0).getUUID(), uuid4)
        self.assertEquals(calls[0].getParam(0).getState(), TEMPORARILY_DOWN_STATE)
        self.assertEquals(calls[1].getParam(0).getState(), TEMPORARILY_DOWN_STATE)
838 839 840 841
        # check the discarded cell is removed from the pt
        calls = app.pt.mockGetNamedCalls('removeCell')
        self.assertEquals(len(calls), 1)
        self.assertEquals(calls[0].getParam(1).getUUID(), uuid2)
842
        # and the others are updated
843
        self.assertEqual(app.ptid, test_ptid + 1)
844
        calls = app.pt.mockGetNamedCalls('setCell')
845
        self.assertEqual(len(calls), 3)
846
        self.assertEquals(calls[0].getParam(1).getUUID(), uuid1)
847 848
        self.assertEquals(calls[1].getParam(1).getUUID(), uuid3)
        self.assertEquals(calls[2].getParam(1).getUUID(), uuid4)
849 850

    def test_AnswerNewTID(self):
851
        app = Mock({'setTID': None})
852
        dispatcher = self.getDispatcher()
853
        client_handler = PrimaryEventHandler(app, dispatcher)
854 855 856
        conn = self.getConnection()
        test_tid = 1
        client_handler.handleAnswerNewTID(conn, None, test_tid)
857 858 859
        setTID_call_list = app.mockGetNamedCalls('setTID')
        self.assertEquals(len(setTID_call_list), 1)
        self.assertEquals(setTID_call_list[0].getParam(0), test_tid)
860 861

    def test_NotifyTransactionFinished(self):
862 863
        test_tid = 1
        app = Mock({'getTID': test_tid, 'setTransactionFinished': None})
864
        dispatcher = self.getDispatcher()
865
        client_handler = PrimaryEventHandler(app, dispatcher)
866
        conn = self.getConnection()
867 868
        client_handler.handleNotifyTransactionFinished(conn, None, test_tid)
        self.assertEquals(len(app.mockGetNamedCalls('setTransactionFinished')), 1)
869 870 871 872 873 874 875 876 877 878
        # TODO: decide what to do when non-current transaction is notified as finished, and test that behaviour

    def test_InvalidateObjects(self):
        class App:
            def _cache_lock_acquire(self):
                pass

            def _cache_lock_release(self):
                pass

879 880 881 882 883 884
            def registerDB(self, db, limit):
                self.db = db

            def getDB(self):
                return self.db

885 886 887
            mq_cache = Mock({'__delitem__': None})
        app = App()
        dispatcher = self.getDispatcher()
888
        client_handler = StorageEventHandler(app, dispatcher)
889 890 891
        conn = self.getConnection()
        test_tid = 1
        test_oid_list = ['\x00\x00\x00\x00\x00\x00\x00\x01', '\x00\x00\x00\x00\x00\x00\x00\x02']
892 893
        test_db = Mock({'invalidate': None})
        app.registerDB(test_db, None)
894 895
        client_handler.handleInvalidateObjects(conn, None, test_oid_list[:], test_tid)
        # 'invalidate' is called just once
896 897 898
        db = app.getDB()
        self.assertTrue(db is test_db)
        invalidate_call_list = db.mockGetNamedCalls('invalidate')
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
        self.assertEquals(len(invalidate_call_list), 1)
        invalidate_call = invalidate_call_list[0]
        invalidate_tid = invalidate_call.getParam(0)
        self.assertEquals(invalidate_tid, test_tid)
        invalidate_oid_dict = invalidate_call.getParam(1)
        self.assertEquals(len(invalidate_oid_dict), len(test_oid_list))
        self.assertEquals(set(invalidate_oid_dict), set(test_oid_list))
        self.assertEquals(set(invalidate_oid_dict.itervalues()), set([test_tid]))
        # '__delitem__' is called once per invalidated object
        delitem_call_list = app.mq_cache.mockGetNamedCalls('__delitem__')
        self.assertEquals(len(delitem_call_list), len(test_oid_list))
        oid_list = [x.getParam(0) for x in delitem_call_list]
        self.assertEquals(set(oid_list), set(test_oid_list))

    def test_AnswerNewOIDs(self):
        class App:
            new_oid_list = []
        app = App()
        dispatcher = self.getDispatcher()
918
        client_handler = PrimaryEventHandler(app, dispatcher)
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
        conn = self.getConnection()
        test_oid_list = ['\x00\x00\x00\x00\x00\x00\x00\x01', '\x00\x00\x00\x00\x00\x00\x00\x02']
        client_handler.handleAnswerNewOIDs(conn, None, test_oid_list[:])
        self.assertEquals(set(app.new_oid_list), set(test_oid_list))

    def test_StopOperation(self):
        raise NotImplementedError

    # Storage node handler

    def test_AnswerObject(self):
        class FakeLocal:
            asked_object = ()
        class App:
            local_var = FakeLocal()
        app = App()
        dispatcher = self.getDispatcher()
936
        client_handler = StorageEventHandler(app, dispatcher)
937 938 939 940 941 942 943 944
        conn = self.getConnection()
        # TODO: use realistic values
        test_object_data = ('\x00\x00\x00\x00\x00\x00\x00\x01', 0, 0, 0, 0, 'test')
        client_handler.handleAnswerObject(conn, None, *test_object_data)
        self.assertEquals(app.local_var.asked_object, test_object_data)

    def _testAnswerStoreObject(self, app, conflicting, oid, serial):
        dispatcher = self.getDispatcher()
945
        client_handler = StorageEventHandler(app, dispatcher)
946 947 948 949 950
        conn = self.getConnection()
        client_handler.handleAnswerStoreObject(conn, None, conflicting, oid, serial)

    def test_conflictingAnswerStoreObject(self):
        class App:
951
            local_var = threading.local()
952
        app = App()
953
        app.local_var.object_stored = (0, 0)
954 955 956
        test_oid = '\x00\x00\x00\x00\x00\x00\x00\x01'
        test_serial = 1
        self._testAnswerStoreObject(app, 1, test_oid, test_serial)
957
        self.assertEqual(app.local_var.object_stored, (-1, test_serial))
958 959 960

    def test_AnswerStoreObject(self):
        class App:
961
            local_var = threading.local()
962
        app = App()
963
        app.local_var.object_stored = (0, 0)
964 965 966
        test_oid = '\x00\x00\x00\x00\x00\x00\x00\x01'
        test_serial = 1
        self._testAnswerStoreObject(app, 0, test_oid, test_serial)
967
        self.assertEqual(app.local_var.object_stored, (test_oid, test_serial))
968 969

    def test_AnswerStoreTransaction(self):
970 971
        test_tid = 10
        app = Mock({'getTID': test_tid, 'setTransactionVoted': None})
972
        dispatcher = self.getDispatcher()
973
        client_handler = StorageEventHandler(app, dispatcher)
974 975
        conn = self.getConnection()
        client_handler.handleAnswerStoreTransaction(conn, None, test_tid)
976
        self.assertEquals(len(app.mockGetNamedCalls('setTransactionVoted')), 1)
977 978 979 980 981 982 983 984 985
        # TODO: test handleAnswerObject with test_tid not matching app.tid (not handled in program)

    def test_AnswerTransactionInformation(self):
        class FakeLocal:
            txn_info = {}
        class App:
            local_var = FakeLocal()
        app = App()
        dispatcher = self.getDispatcher()
986
        client_handler = StorageEventHandler(app, dispatcher)
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
        conn = self.getConnection()
        tid = '\x00\x00\x00\x00\x00\x00\x00\x01' # TODO: use a more realistic tid
        user = 'bar'
        desc = 'foo'
        ext = 0 # XXX: unused in implementation
        oid_list = ['\x00\x00\x00\x00\x00\x00\x00\x01', '\x00\x00\x00\x00\x00\x00\x00\x02']
        client_handler.handleAnswerTransactionInformation(conn, None, tid, user, desc, ext, oid_list[:])
        stored_dict = app.local_var.txn_info
        # TODO: test 'time' value ?
        self.assertEquals(stored_dict['user_name'], user)
        self.assertEquals(stored_dict['description'], desc)
        self.assertEquals(stored_dict['id'], tid)
        self.assertEquals(stored_dict['oids'], oid_list)

    def test_AnswerObjectHistory(self):
        class FakeLocal:
            history = (0, [])
        class App:
            local_var = FakeLocal()
        app = App()
        dispatcher = self.getDispatcher()
1008
        client_handler = StorageEventHandler(app, dispatcher)
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
        conn = self.getConnection()
        test_oid = '\x00\x00\x00\x00\x00\x00\x00\x01'
        # TODO: use realistic values
        test_history_list = [(1, 2), (3, 4)]
        client_handler.handleAnswerObjectHistory(conn, None, test_oid, test_history_list[:])
        oid, history = app.local_var.history
        self.assertEquals(oid, test_oid)
        self.assertEquals(len(history), len(test_history_list))
        self.assertEquals(set(history), set(test_history_list))

    def test_OidNotFound(self):
        class FakeLocal:
            asked_object = 0
            history = 0
        class App:
            local_var = FakeLocal()
        app = App()
        dispatcher = self.getDispatcher()
1027
        client_handler = StorageEventHandler(app, dispatcher)
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        conn = self.getConnection()
        client_handler.handleOidNotFound(conn, None, None)
        self.assertEquals(app.local_var.asked_object, -1)
        self.assertEquals(app.local_var.history, -1)

    def test_TidNotFound(self):
        class FakeLocal:
            txn_info = 0
        class App:
            local_var = FakeLocal()
        app = App()
        dispatcher = self.getDispatcher()
1040
        client_handler = StorageEventHandler(app, dispatcher)
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
        conn = self.getConnection()
        client_handler.handleTidNotFound(conn, None, None)
        self.assertEquals(app.local_var.txn_info, -1)

    def test_AnswerTIDs(self):
        class FakeLocal:
            node_tids = {}
        class App:
            local_var = FakeLocal()
        app = App()
        dispatcher = self.getDispatcher()
1052
        client_handler = StorageEventHandler(app, dispatcher)
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        conn = self.getConnection()
        test_tid_list = ['\x00\x00\x00\x00\x00\x00\x00\x01', '\x00\x00\x00\x00\x00\x00\x00\x02']
        client_handler.handleAnswerTIDs(conn, None, test_tid_list[:])
        stored_tid_list = []
        for tid_list in app.local_var.node_tids.itervalues():
            stored_tid_list.extend(tid_list)
        self.assertEquals(len(stored_tid_list), len(test_tid_list))
        self.assertEquals(set(stored_tid_list), set(test_tid_list))

if __name__ == '__main__':
    unittest.main()