Example #1
0
    def test_session_disconnect(self):
        session = StompSession(StompSpec.VERSION_1_1)
        session.connect(login='', passcode='')
        session.connected(StompFrame(StompSpec.CONNECTED, {StompSpec.SESSION_HEADER: 'hi'}))
        headers = {StompSpec.ID_HEADER: 4711}
        session.subscribe('bla', headers)
        frame = session.disconnect(receipt='4711')
        self.assertEqual(frame, commands.disconnect(receipt='4711'))
        self.assertEqual(session.state, session.DISCONNECTING)
        session.close(flush=False)
        self.assertEqual(session.state, session.DISCONNECTED)
        self.assertEqual(list(session.replay()), [('bla', headers, None, None)])
        self.assertEqual(list(session.replay()), [])

        self.assertRaises(StompProtocolError, session.disconnect)
Example #2
0
    def test_session_disconnect(self):
        session = StompSession(StompSpec.VERSION_1_1)
        session.connect(login='', passcode='')
        session.connected(
            StompFrame(StompSpec.CONNECTED, {StompSpec.SESSION_HEADER: 'hi'}))
        headers = {StompSpec.ID_HEADER: 4711}
        session.subscribe('bla', headers)
        frame = session.disconnect(receipt='4711')
        self.assertEqual(frame, commands.disconnect(receipt='4711'))
        self.assertEqual(session.state, session.DISCONNECTING)
        session.close(flush=False)
        self.assertEqual(session.state, session.DISCONNECTED)
        self.assertEqual(list(session.replay()),
                         [('bla', headers, None, None)])
        self.assertEqual(list(session.replay()), [])

        self.assertRaises(StompProtocolError, session.disconnect)
Example #3
0
    def test_session_init(self):
        session = StompSession(check=False)
        self.assertEqual(session.version, StompSpec.DEFAULT_VERSION)
        session.send('', b'', {})
        session.subscribe('bla1', {'bla2': 'bla3'})
        session.unsubscribe((StompSpec.DESTINATION_HEADER, 'bla1'))

        session = StompSession()
        self.assertRaises(StompProtocolError, lambda: session.send('', b'', {}))
        self.assertRaises(StompProtocolError, lambda: session.subscribe('bla1', {'bla2': 'bla3'}))
        self.assertRaises(StompProtocolError, lambda: session.unsubscribe((StompSpec.DESTINATION_HEADER, 'bla1')))

        session = StompSession(StompSpec.VERSION_1_1)
        self.assertEqual(session.version, StompSpec.VERSION_1_1)

        self.assertRaises(StompProtocolError, lambda: StompSession(version='1.3'))
        self.assertRaises(StompProtocolError, lambda: session.send('', '', {}))
Example #4
0
    def test_session_init(self):
        session = StompSession(check=False)
        self.assertEquals(session.version, StompSpec.DEFAULT_VERSION)
        session.send('', '', {})
        session.subscribe('bla1', {'bla2': 'bla3'})
        session.unsubscribe((StompSpec.DESTINATION_HEADER, 'bla1'))

        session = StompSession()
        self.assertRaises(StompProtocolError, lambda: session.send('', '', {}))
        self.assertRaises(StompProtocolError,
                          lambda: session.subscribe('bla1', {'bla2': 'bla3'}))
        self.assertRaises(
            StompProtocolError, lambda: session.unsubscribe(
                (StompSpec.DESTINATION_HEADER, 'bla1')))

        session = StompSession(StompSpec.VERSION_1_1)
        self.assertEquals(session.version, StompSpec.VERSION_1_1)

        self.assertRaises(StompProtocolError,
                          lambda: StompSession(version='1.3'))
        self.assertRaises(StompProtocolError, lambda: session.send('', '', {}))
Example #5
0
    def test_session_subscribe(self):
        session = StompSession(check=False)
        headers = {'bla2': 'bla3'}
        frame, token = session.subscribe('bla1', headers, receipt='4711')
        self.assertEqual((frame, token),
                         commands.subscribe('bla1',
                                            headers,
                                            '4711',
                                            version=StompSpec.VERSION_1_0))

        self.assertEqual(token, (StompSpec.DESTINATION_HEADER, 'bla1'))
        self.assertEqual(
            token,
            commands.message(
                StompFrame(
                    StompSpec.MESSAGE,
                    dict([token, (StompSpec.MESSAGE_ID_HEADER, '4711')]))))

        headersWithId1 = {StompSpec.ID_HEADER: 'bla2', 'bla3': 'bla4'}
        frame, tokenWithId1 = session.subscribe('bla2', headersWithId1)
        self.assertEqual((frame, tokenWithId1),
                         commands.subscribe('bla2',
                                            headersWithId1,
                                            version=StompSpec.VERSION_1_0))
        self.assertEqual(tokenWithId1, (StompSpec.ID_HEADER, 'bla2'))
        self.assertEqual(
            tokenWithId1,
            commands.message(
                StompFrame(
                    StompSpec.MESSAGE,
                    dict([(StompSpec.SUBSCRIPTION_HEADER, 'bla2'),
                          (StompSpec.DESTINATION_HEADER, 'bla2'),
                          (StompSpec.MESSAGE_ID_HEADER, '4711')]))))

        headersWithId2 = {StompSpec.ID_HEADER: 'bla3', 'bla4': 'bla5'}
        session.subscribe('bla2', headersWithId2)

        subscriptions = list(session.replay())
        self.assertEqual(subscriptions, [('bla1', headers, '4711', None),
                                         ('bla2', headersWithId1, None, None),
                                         ('bla2', headersWithId2, None, None)])
        self.assertEqual(list(session.replay()), [])

        context = object()
        session.subscribe('bla2', headersWithId2, context=context)
        self.assertEqual(list(session.replay()),
                         [('bla2', headersWithId2, None, context)])
        session.subscribe('bla2', headersWithId2)
        self.assertRaises(StompProtocolError, session.subscribe, 'bla2',
                          headersWithId2)
        self.assertEqual(list(session.replay()),
                         [('bla2', headersWithId2, None, None)])
        session.subscribe('bla2', headersWithId2)
        session.disconnect()
        session.close(flush=False)
        self.assertEqual(list(session.replay()),
                         [('bla2', headersWithId2, None, None)])
        session.subscribe('bla2', headersWithId2)
        session.close(flush=True)
        self.assertEqual(list(session.replay()), [])

        subscriptionsWithoutId1 = [('bla1', headers, None, None),
                                   ('bla2', headersWithId2, None, None)]

        s = [
            session.subscribe(dest, headers_)
            for dest, headers_, _, _ in subscriptions
        ]
        session.unsubscribe(s[1][1])
        self.assertEqual(list(session.replay()), subscriptionsWithoutId1)

        subscriptionWithId2 = [('bla2', headersWithId2, None, None)]

        s = [
            session.subscribe(dest, headers_)
            for dest, headers_, _, _ in subscriptionsWithoutId1
        ]
        session.unsubscribe(s[0][1])
        self.assertEqual(list(session.replay()), subscriptionWithId2)

        session.disconnect()

        session = StompSession(check=False)
        session.connect(login='', passcode='')
        session.connected(
            StompFrame(StompSpec.CONNECTED, {StompSpec.SESSION_HEADER: 'hi'}))

        session.subscribe('bla1', headers)
        self.assertRaises(
            StompProtocolError, lambda: session.unsubscribe(
                (StompSpec.ID_HEADER, 'blub')))
        self.assertRaises(StompProtocolError, lambda: session.unsubscribe(
            ('bla', 'blub')))

        frame, token = session.subscribe('bla2', headersWithId1)
        session.subscribe('bla2', headersWithId2)
        session.unsubscribe(token)
        self.assertRaises(StompProtocolError,
                          lambda: session.unsubscribe(token))

        session = StompSession(version=StompSpec.VERSION_1_1, check=False)
        session.connect(login='', passcode='')
        session.connected(
            StompFrame(
                StompSpec.CONNECTED, {
                    StompSpec.SERVER_HEADER: 'moon',
                    StompSpec.SESSION_HEADER: '4711',
                    StompSpec.VERSION_HEADER: StompSpec.VERSION_1_1
                }))

        self.assertRaises(StompProtocolError,
                          lambda: session.subscribe('bla1', headers))
        self.assertRaises(
            StompProtocolError, lambda: session.unsubscribe(
                (StompSpec.DESTINATION_HEADER, 'bla1')))
        frame, token = session.subscribe('bla2', headersWithId1)
        session.subscribe('bla2', headersWithId2)
        session.unsubscribe(token)
        self.assertRaises(StompProtocolError,
                          lambda: session.unsubscribe(token))

        subscriptions = list(session.replay())
        self.assertEqual(subscriptions, subscriptionWithId2)

        session.subscribe('bla2', headersWithId2)
        session.close(flush=True)
        self.assertEqual(list(session.replay()), [])
class BlackjackClient(WebSocketClient):
    PLAYER_QUEUE = '/queue/player*'
    PLAYERS_QUEUE = '/queue/players*'
    ERRORS_QUEUE = '/queue/errors*'
    GAME_TOPIC = '/topic/game'
    queues = [PLAYER_QUEUE, PLAYERS_QUEUE, ERRORS_QUEUE, GAME_TOPIC]




    def __init__(self, url, playerStrategy):
        super(BlackjackClient, self).__init__(url)
        self.tokens = {}
        self.strategy = playerStrategy
        self.parser = StompParser(StompSpec.VERSION_1_1)
        self.session = StompSession(StompSpec.VERSION_1_1)
        self.connect()
        while self.session.state != 'connected':
            time.sleep(.1)
        self.__subscribe_to_queues()
        self.send_stomp('/app/register', json.dumps({'name': self.strategy.get_name()}))


    def __subscribe_to_queues(self):
        id = 0
        for queue in self.queues:
            subscribeFrame, token = self.session.subscribe(queue, headers={'id': id})
            self.tokens[queue] = token
            # print "sending frame\n" + str(subscribeFrame)
            self.send(str(subscribeFrame))
            id += 1


    def __get_player_from_gameinfo(self, gameInfo):
        if len(gameInfo['players']) == 0:
            return None
        for player in gameInfo['players']:
            if player['seatNum'] == self.strategy.seatNum and player['name'] == self.strategy.get_name():
                return player
        for player in gameInfo['players']:
            if player['name'] == self.strategy.get_name():
                return player
        raise Exception('player was removed from the game')


    def opened(self):
        print "opened"
        connectFrame = self.session.connect(host='{}:{}'.format(config.host, config.port))
        # print "sending frame\n" + str(connectFrame)
        self.send(str(connectFrame))


    def send_stomp(self, destination, message):
        sendFrame = self.session.send(destination, message)
        # print "sending frame\n" + str(sendFrame)
        self.send(str(sendFrame))


    def closed(self, code, reason=None):
        print "Closed down", code, reason


    def received_message(self, m):
        self.parser.add(str(m))
        frame = self.parser.get()
        print dict(frame)

        if frame.command == StompSpec.CONNECTED:
            self.session.connected(frame)
            return

        destination = frame.headers['destination']
        if destination == '/user/queue/player':
            self.strategy.handle_registration_info(json.loads(frame.body))
            bet = self.strategy.get_bet_amount()
            self.send_stomp('/app/bet', json.dumps({'playerId': self.strategy.get_player_id(), 'betAmount': bet}))

        elif destination == '/user/queue/players' or destination == '/topic/game':
            gameInfo = json.loads(frame.body)
            self.strategy.handle_game_info(gameInfo)
            player = self.__get_player_from_gameinfo(gameInfo)
            if player is None:
                pass
            if gameInfo['gameStatus'] == GameStatus.BETTING_ROUND and not player['betInForNextRound']:
                bet = self.strategy.get_bet_amount()
                self.send_stomp('/app/bet', json.dumps({'playerId': self.strategy.get_player_id(), 'betAmount': bet}))
            elif gameInfo['gameStatus'] == GameStatus.HAND_IN_PROGRESS:
                handNum = 0
                for hand in player['hands']:
                    if hand['turn']:
                        action = self.strategy.get_action(hand)
                        self.send_stomp('/app/action', json.dumps({'playerId': self.strategy.get_player_id(), 'handNum': handNum, 'action': action}))
                        break
                    handNum += 1

        elif destination == '/user/queue/errors':
            self.strategy.handle_error(json.loads(frame.body))
Example #7
0
    def test_session_subscribe(self):
        session = StompSession(check=False)
        headers = {'bla2': 'bla3'}
        frame, token = session.subscribe('bla1', headers, receipt='4711')
        self.assertEqual((frame, token), commands.subscribe('bla1', headers, '4711', version=StompSpec.VERSION_1_0))

        self.assertEqual(token, (StompSpec.DESTINATION_HEADER, 'bla1'))
        self.assertEqual(token, commands.message(StompFrame(StompSpec.MESSAGE, dict([token, (StompSpec.MESSAGE_ID_HEADER, '4711')]))))

        headersWithId1 = {StompSpec.ID_HEADER: 'bla2', 'bla3': 'bla4'}
        frame, tokenWithId1 = session.subscribe('bla2', headersWithId1)
        self.assertEqual((frame, tokenWithId1), commands.subscribe('bla2', headersWithId1, version=StompSpec.VERSION_1_0))
        self.assertEqual(tokenWithId1, (StompSpec.ID_HEADER, 'bla2'))
        self.assertEqual(tokenWithId1, commands.message(StompFrame(StompSpec.MESSAGE, dict([(StompSpec.SUBSCRIPTION_HEADER, 'bla2'), (StompSpec.DESTINATION_HEADER, 'bla2'), (StompSpec.MESSAGE_ID_HEADER, '4711')]))))

        headersWithId2 = {StompSpec.ID_HEADER: 'bla3', 'bla4': 'bla5'}
        session.subscribe('bla2', headersWithId2)

        subscriptions = list(session.replay())
        self.assertEqual(subscriptions, [('bla1', headers, '4711', None), ('bla2', headersWithId1, None, None), ('bla2', headersWithId2, None, None)])
        self.assertEqual(list(session.replay()), [])

        context = object()
        session.subscribe('bla2', headersWithId2, context=context)
        self.assertEqual(list(session.replay()), [('bla2', headersWithId2, None, context)])
        session.subscribe('bla2', headersWithId2)
        self.assertRaises(StompProtocolError, session.subscribe, 'bla2', headersWithId2)
        self.assertEqual(list(session.replay()), [('bla2', headersWithId2, None, None)])
        session.subscribe('bla2', headersWithId2)
        session.disconnect()
        session.close(flush=False)
        self.assertEqual(list(session.replay()), [('bla2', headersWithId2, None, None)])
        session.subscribe('bla2', headersWithId2)
        session.close(flush=True)
        self.assertEqual(list(session.replay()), [])

        subscriptionsWithoutId1 = [('bla1', headers, None, None), ('bla2', headersWithId2, None, None)]

        s = [session.subscribe(dest, headers_) for dest, headers_, _, _ in subscriptions]
        session.unsubscribe(s[1][1])
        self.assertEqual(list(session.replay()), subscriptionsWithoutId1)

        subscriptionWithId2 = [('bla2', headersWithId2, None, None)]

        s = [session.subscribe(dest, headers_) for dest, headers_, _, _ in subscriptionsWithoutId1]
        session.unsubscribe(s[0][1])
        self.assertEqual(list(session.replay()), subscriptionWithId2)

        session.disconnect()

        session = StompSession(check=False)
        session.connect(login='', passcode='')
        session.connected(StompFrame(StompSpec.CONNECTED, {StompSpec.SESSION_HEADER: 'hi'}))

        session.subscribe('bla1', headers)
        self.assertRaises(StompProtocolError, lambda: session.unsubscribe((StompSpec.ID_HEADER, 'blub')))
        self.assertRaises(StompProtocolError, lambda: session.unsubscribe(('bla', 'blub')))

        frame, token = session.subscribe('bla2', headersWithId1)
        session.subscribe('bla2', headersWithId2)
        session.unsubscribe(token)
        self.assertRaises(StompProtocolError, lambda: session.unsubscribe(token))

        session = StompSession(version=StompSpec.VERSION_1_1, check=False)
        session.connect(login='', passcode='')
        session.connected(StompFrame(StompSpec.CONNECTED, {StompSpec.SERVER_HEADER: 'moon', StompSpec.SESSION_HEADER: '4711', StompSpec.VERSION_HEADER: StompSpec.VERSION_1_1}))

        self.assertRaises(StompProtocolError, lambda: session.subscribe('bla1', headers))
        self.assertRaises(StompProtocolError, lambda: session.unsubscribe((StompSpec.DESTINATION_HEADER, 'bla1')))
        frame, token = session.subscribe('bla2', headersWithId1)
        session.subscribe('bla2', headersWithId2)
        session.unsubscribe(token)
        self.assertRaises(StompProtocolError, lambda: session.unsubscribe(token))

        subscriptions = list(session.replay())
        self.assertEqual(subscriptions, subscriptionWithId2)

        session.subscribe('bla2', headersWithId2)
        session.close(flush=True)
        self.assertEqual(list(session.replay()), [])