Beispiel #1
0
 def test_binary_body_invalid_eof(self):
     parser = StompParser()
     body = b'MESSAGE\ncontent-length:4\n\n\xf0\x00\n\t\x00'
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
     self.assertRaises(
         StompFrameError, parser.add,
         b'MESSAGE\ncontent-length:4\n\n\xf0\n\t\xff\x01\n\nCONNECT\n\x00'
     )  # \x00 behind invalid EOF
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
     self.assertRaises(StompFrameError, parser.add,
                       b'MESSAGE\ncontent-length:4\n\n\xf0\n\t\xff\x01\x00'
                       )  # \x00 just behind invalid EOF
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
     self.assertRaises(StompFrameError, parser.add,
                       b'MESSAGE\ncontent-length:4\n\n\xf0\x00\n\t\x01'
                       )  # \x00 before invalid EOF
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
     self.assertRaises(StompFrameError, parser.add,
                       b'MESSAGE\ncontent-length:4\n\n\xf0\n\t\x00\x01'
                       )  # \x00 just before invalid EOF
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
Beispiel #2
0
    def test_binary_body(self):
        body = b'\xf0\x00\x0a\x09'
        headers = {StompSpec.CONTENT_LENGTH_HEADER: textType(len(body))}
        frame = StompFrame(StompSpec.MESSAGE, body=body)
        frame.setContentLength()
        frameBytes = binaryType(frame)
        self.assertTrue(frameBytes.endswith(b'\x00'))
        parser = StompParser()
        for _ in range(2):
            for (j, _) in enumerate(frameBytes):
                parser.add(frameBytes[j:j + 1])
            frame = parser.get()
            self.assertEqual(StompSpec.MESSAGE, frame.command)
            self.assertEqual(headers, frame.headers)
            self.assertEqual(body, frame.body)
        self.assertEqual(parser.get(), None)

        frames = 2 * frameBytes
        split = len(frameBytes) - 1
        chunks = [frames[:split], frames[split:]]
        parser.add(chunks.pop(0))
        self.assertEqual(parser.get(), None)
        parser.add(chunks.pop(0))
        self.assertEqual(parser.get(), frame)
        self.assertEqual(parser.get(), frame)
        self.assertEqual(parser.get(), None)

        split = len(frameBytes) + 1
        chunks = [frames[:split], frames[split:]]
        parser.add(chunks.pop(0))
        self.assertEqual(parser.get(), frame)
        self.assertEqual(parser.get(), None)
        parser.add(chunks.pop(0))
        self.assertEqual(parser.get(), frame)
        self.assertEqual(parser.get(), None)
Beispiel #3
0
    def test_binary_body(self):
        body = b'\xf0\x00\x0a\x09'
        headers = {StompSpec.CONTENT_LENGTH_HEADER: textType(len(body))}
        frame = StompFrame(StompSpec.MESSAGE, body=body)
        frame.setContentLength()
        frameBytes = binaryType(frame)
        self.assertTrue(frameBytes.endswith(b'\x00'))
        parser = StompParser()
        for _ in range(2):
            for (j, _) in enumerate(frameBytes):
                parser.add(frameBytes[j:j + 1])
            frame = parser.get()
            self.assertEqual(StompSpec.MESSAGE, frame.command)
            self.assertEqual(headers, frame.headers)
            self.assertEqual(body, frame.body)
        self.assertEqual(parser.get(), None)

        frames = 2 * frameBytes
        split = len(frameBytes) - 1
        chunks = [frames[:split], frames[split:]]
        parser.add(chunks.pop(0))
        self.assertEqual(parser.get(), None)
        parser.add(chunks.pop(0))
        self.assertEqual(parser.get(), frame)
        self.assertEqual(parser.get(), frame)
        self.assertEqual(parser.get(), None)

        split = len(frameBytes) + 1
        chunks = [frames[:split], frames[split:]]
        parser.add(chunks.pop(0))
        self.assertEqual(parser.get(), frame)
        self.assertEqual(parser.get(), None)
        parser.add(chunks.pop(0))
        self.assertEqual(parser.get(), frame)
        self.assertEqual(parser.get(), None)
Beispiel #4
0
 def test_frames_with_optional_newlines_succeeds(self):
     parser = StompParser()
     disconnect = commands.disconnect()
     frame = '\n%s\n' % disconnect
     parser.add(2 * frame)
     for _ in xrange(2):
         self.assertEqual(parser.get(), disconnect)
     self.assertEqual(parser.get(), None)
Beispiel #5
0
 def test_frames_with_optional_newlines_succeeds(self):
     parser = StompParser()
     disconnect = commands.disconnect()
     frame = '\n%s\n' % disconnect
     parser.add(2 * frame)
     for _ in xrange(2):
         self.assertEqual(parser.get(), disconnect)
     self.assertEqual(parser.get(), None)
Beispiel #6
0
    def test_add_throws_FrameError_on_invalid_command(self):
        parser = StompParser()

        self.assertRaises(StompFrameError, parser.add, b'HELLO\n\n\x00')
        self.assertFalse(parser.canRead())
        parser.add(('%s\n\n\x00' % StompSpec.DISCONNECT).encode())
        self.assertEqual(StompFrame(StompSpec.DISCONNECT), parser.get())
        self.assertFalse(parser.canRead())
Beispiel #7
0
 def test_frames_with_optional_newlines_succeeds(self):
     parser = StompParser()
     disconnect = commands.disconnect()
     frame = b'\n' + binaryType(disconnect) + b'\n'
     parser.add(2 * frame)
     for _ in range(2):
         self.assertEqual(parser.get(), disconnect)
     self.assertIsNone(parser.get())
Beispiel #8
0
 def test_frames_with_optional_newlines_succeeds(self):
     parser = StompParser()
     disconnect = commands.disconnect()
     frame = b'\n' + binaryType(disconnect) + b'\n'
     parser.add(2 * frame)
     for _ in range(2):
         self.assertEqual(parser.get(), disconnect)
     self.assertIsNone(parser.get())
Beispiel #9
0
    def test_add_throws_FrameError_on_invalid_command(self):
        parser = StompParser()

        self.assertRaises(StompFrameError, parser.add, b'HELLO\n\n\x00')
        self.assertFalse(parser.canRead())
        parser.add(('%s\n\n\x00' % StompSpec.DISCONNECT).encode())
        self.assertEqual(StompFrame(StompSpec.DISCONNECT), parser.get())
        self.assertFalse(parser.canRead())
Beispiel #10
0
 def test_dont_unescape_bad_characters(self):
     parser = StompParser(StompSpec.VERSION_1_2)
     frame = commands.send('*queue')
     parser.add(binaryType(frame))
     self.assertEqual(parser.get(), frame)
     for badCharacter in (b'\r', b'\n', b'\c', b'\\', b':', b'\\h'):
         self.assertRaises(StompFrameError, parser.add, binaryType(frame).replace(b'*', badCharacter))
     self.assertRaises(StompFrameError, parser.add, binaryType(commands.send('queue\\')))
     self.assertIsNone(parser.get())
Beispiel #11
0
    def test_keep_first_of_repeated_headers(self):
        parser = StompParser()
        parser.add(("""
%s
repeat:1
repeat:2

\x00""" % StompSpec.CONNECT).encode())
        frame = parser.get()
        self.assertEqual(frame.headers['repeat'], '1')
Beispiel #12
0
    def test_keep_first_of_repeated_headers(self):
        parser = StompParser()
        parser.add(("""
%s
repeat:1
repeat:2

\x00""" % StompSpec.CONNECT).encode())
        frame = parser.get()
        self.assertEqual(frame.headers['repeat'], '1')
Beispiel #13
0
 def test_frames_with_heart_beats_succeeds(self):
     parser = StompParser(version=StompSpec.VERSION_1_1)
     disconnect = commands.disconnect()
     frame = b'\n' + binaryType(disconnect) + b'\n'
     parser.add(2 * frame)
     frames = []
     while parser.canRead():
         frames.append(parser.get())
     self.assertEqual(frames, [StompHeartBeat(), disconnect, StompHeartBeat(), StompHeartBeat(), disconnect, StompHeartBeat()])
     self.assertIsNone(parser.get())
Beispiel #14
0
def main():
    parser = StompParser(version=StompSpec.VERSION_1_2)
    frame = binaryType(binaryFrame) + binaryType(textFrame) + binaryType(heartBeatFrame)
    for _ in createRange(N):
        for j in itertools.count():
            packet = frame[j * SLICE:(j + 1) * SLICE]
            if not packet:
                break
            parser.add(packet)
        while parser.canRead():
            parser.get()
Beispiel #15
0
 def test_invalid_command(self):
     messages = [b'RECEIPT\nreceipt-id:message-12345\n\n\x00', b'NACK\nsubscription:0\nmessage-id:007\n\n\x00']
     parser = StompParser(StompSpec.VERSION_1_0)
     parser.add(messages[0])
     self.assertRaises(StompFrameError, parser.add, messages[1])
     self.assertEqual(parser.get(), StompFrame(StompSpec.RECEIPT, rawHeaders=(('receipt-id', 'message-12345'),)))
     self.assertFalse(parser.canRead())
     self.assertIsNone(parser.get())
     parser = StompParser(StompSpec.VERSION_1_1)
     parser.add(messages[1])
     self.assertEqual(parser.get(), StompFrame(command='NACK', rawHeaders=(('subscription', '0'), ('message-id', '007')), version=StompSpec.VERSION_1_1))
Beispiel #16
0
 def test_dont_unescape_bad_characters(self):
     parser = StompParser(StompSpec.VERSION_1_2)
     frame = commands.send('*queue')
     parser.add(binaryType(frame))
     self.assertEqual(parser.get(), frame)
     for badCharacter in (b'\r', b'\n', b'\c', b'\\', b':', b'\\h'):
         self.assertRaises(StompFrameError, parser.add,
                           binaryType(frame).replace(b'*', badCharacter))
     self.assertRaises(StompFrameError, parser.add,
                       binaryType(commands.send('queue\\')))
     self.assertIsNone(parser.get())
Beispiel #17
0
 def test_invalid_command(self):
     messages = ['RECEIPT\nreceipt-id:message-12345\n\n\x00', 'NACK\nsubscription:0\nmessage-id:007\n\n\x00']
     parser = StompParser('1.0')
     parser.add(messages[0])
     self.assertRaises(StompFrameError, parser.add, messages[1])
     self.assertEquals(parser.get(), StompFrame(StompSpec.RECEIPT, rawHeaders=((u'receipt-id', u'message-12345'),)))
     self.assertFalse(parser.canRead())
     self.assertEquals(parser.get(), None)
     parser = StompParser('1.1')
     parser.add(messages[1])
     self.assertEquals(parser.get(), StompFrame(command=u'NACK', rawHeaders=((u'subscription', u'0'), (u'message-id', u'007'))))
Beispiel #18
0
    def test_decode(self):
        headers = {u'fen\xeatre': u'\xbfqu\xe9 tal?, s\xfc\xdf'}
        frameBytes = str(StompFrame(command=StompSpec.DISCONNECT, headers=headers, version=StompSpec.VERSION_1_1))

        parser = StompParser(version=StompSpec.VERSION_1_1)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(frame.headers, headers)

        parser = StompParser(version=StompSpec.VERSION_1_0)
        self.assertRaises(UnicodeDecodeError, parser.add, frameBytes)
Beispiel #19
0
    def test_frame_parse_succeeds(self):
        frame = StompFrame(
            StompSpec.SEND,
            {'foo': 'bar', 'hello ': 'there-world with space ', 'empty-value':'', '':'empty-header', StompSpec.DESTINATION_HEADER: '/queue/blah'},
            b'some stuff\nand more'
        )

        parser = StompParser()
        parser.add(binaryType(frame))
        self.assertEqual(parser.get(), frame)
        self.assertIsNone(parser.get())
Beispiel #20
0
 def test_no_newline(self):
     headers = {'x': 'y'}
     body = b'testing 1 2 3'
     frameBytes = binaryType(StompFrame(StompSpec.MESSAGE, headers, body))
     self.assertTrue(frameBytes.endswith(b'\x00'))
     parser = StompParser()
     parser.add(frameBytes)
     frame = parser.get()
     self.assertEqual(StompSpec.MESSAGE, frame.command)
     self.assertEqual(headers, frame.headers)
     self.assertEqual(body, frame.body)
     self.assertEqual(parser.get(), None)
Beispiel #21
0
 def test_no_newline(self):
     headers = {'x': 'y'}
     body = 'testing 1 2 3'
     frameBytes = str(StompFrame(StompSpec.MESSAGE, headers, body))
     self.assertTrue(frameBytes.endswith('\x00'))
     parser = StompParser()
     parser.add(self._generate_bytes(frameBytes))
     frame = parser.get()
     self.assertEquals(StompSpec.MESSAGE, frame.command)
     self.assertEquals(headers, frame.headers)
     self.assertEquals(body, frame.body)
     self.assertEquals(parser.get(), None)
Beispiel #22
0
class BlackHoleStompServer(Protocol):
    delimiter = StompSpec.FRAME_DELIMITER

    def __init__(self):
        self.log = logging.getLogger(LOG_CATEGORY)
        self._parser = StompParser()
        self.commandMap = {
            StompSpec.CONNECT: self.handleConnect,
            StompSpec.DISCONNECT: self.handleDisconnect,
            StompSpec.SEND: self.handleSend,
            StompSpec.SUBSCRIBE: self.handleSubscribe,
            StompSpec.ACK: self.handleAck,
            StompSpec.NACK: self.handleNack
        }

    def connectionMade(self):
        self.log.debug('Connection made')

    def connectionLost(self, reason):
        self.log.debug('Connection lost: %s' % reason)

    def dataReceived(self, data):
        self._parser.add(data)

        for frame in iter(self._parser.get, self._parser.SENTINEL):
            try:
                self.log.debug('Received %s' % frame.info())
            except KeyError:
                raise StompFrameError('Unknown STOMP command: %s' %
                                      repr(frame))
            self.commandMap[frame.command](frame)

    def getFrame(self, command, headers, body):
        return binaryType(
            StompFrame(command, headers, body, version=self._parser.version))

    def handleConnect(self, frame):
        pass

    def handleDisconnect(self, frame):
        pass

    def handleSend(self, frame):
        pass

    def handleSubscribe(self, frame):
        pass

    def handleAck(self, frame):
        pass

    def handleNack(self, frame):
        pass
Beispiel #23
0
 def test_no_newline(self):
     headers = {'x': 'y'}
     body = b'testing 1 2 3'
     frameBytes = binaryType(StompFrame(StompSpec.MESSAGE, headers, body))
     self.assertTrue(frameBytes.endswith(b'\x00'))
     parser = StompParser()
     parser.add(frameBytes)
     frame = parser.get()
     self.assertEqual(StompSpec.MESSAGE, frame.command)
     self.assertEqual(headers, frame.headers)
     self.assertEqual(body, frame.body)
     self.assertEqual(parser.get(), None)
Beispiel #24
0
 def test_no_newline(self):
     headers = {'x': 'y'}
     body = 'testing 1 2 3'
     frameBytes = str(StompFrame(StompSpec.MESSAGE, headers, body))
     self.assertTrue(frameBytes.endswith('\x00'))
     parser = StompParser()
     parser.add(self._generate_bytes(frameBytes))
     frame = parser.get()
     self.assertEquals(StompSpec.MESSAGE, frame.command)
     self.assertEquals(headers, frame.headers)
     self.assertEquals(body, frame.body)
     self.assertEquals(parser.get(), None)
Beispiel #25
0
    def test_reset_succeeds(self):
        frame = StompFrame(
            command=StompSpec.SEND,
            headers={'foo': 'bar', 'hello ': 'there-world with space ', 'empty-value':'', '':'empty-header', StompSpec.DESTINATION_HEADER: '/queue/blah'},
            body=b'some stuff\nand more'
        )
        parser = StompParser()

        parser.add(binaryType(frame))
        parser.reset()
        self.assertIsNone(parser.get())
        parser.add(binaryType(frame)[:20])
        self.assertIsNone(parser.get())
Beispiel #26
0
    def test_binary_body(self):
        body = binascii.a2b_hex('f0000a09')
        headers = {'content-length': str(len(body))}
        frameBytes = str(StompFrame(StompSpec.MESSAGE, headers, body))
        self.assertTrue(frameBytes.endswith('\x00'))
        parser = StompParser()
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(StompSpec.MESSAGE, frame.command)
        self.assertEquals(headers, frame.headers)
        self.assertEquals(body, frame.body)

        self.assertEquals(parser.get(), None)
Beispiel #27
0
    def test_decode(self):
        key = b'fen\xc3\xaatre'.decode('utf-8')
        value = b'\xc2\xbfqu\xc3\xa9 tal?'.decode('utf-8')
        headers = {key: value}
        frameBytes = binaryType(StompFrame(command=StompSpec.DISCONNECT, headers=headers, version=StompSpec.VERSION_1_1))

        parser = StompParser(version=StompSpec.VERSION_1_1)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEqual(frame.headers, headers)

        parser = StompParser(version=StompSpec.VERSION_1_0)
        self.assertRaises(UnicodeDecodeError, parser.add, frameBytes)
Beispiel #28
0
    def test_duplicate_headers(self):
        command = StompSpec.SEND
        rawFrame = '%s\nfoo:bar1\nfoo:bar2\n\nsome stuff\nand more\x00' % (command,)

        parser = StompParser()
        parser.add(rawFrame.encode())
        parsedFrame = parser.get()
        self.assertIsNone(parser.get())

        self.assertEqual(parsedFrame.command, command)
        self.assertEqual(parsedFrame.headers, {'foo': 'bar1'})
        self.assertEqual(parsedFrame.rawHeaders, [('foo', 'bar1'), ('foo', 'bar2')])
        self.assertEqual(parsedFrame.body, b'some stuff\nand more')
Beispiel #29
0
    def test_binary_body(self):
        body = binascii.a2b_hex('f0000a09')
        headers = {'content-length': str(len(body))}
        frameBytes = str(StompFrame(StompSpec.MESSAGE, headers, body))
        self.assertTrue(frameBytes.endswith('\x00'))
        parser = StompParser()
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(StompSpec.MESSAGE, frame.command)
        self.assertEquals(headers, frame.headers)
        self.assertEquals(body, frame.body)

        self.assertEquals(parser.get(), None)
Beispiel #30
0
class BlackHoleStompServer(Protocol):
    delimiter = StompSpec.FRAME_DELIMITER

    def __init__(self):
        self.log = logging.getLogger(LOG_CATEGORY)
        self._parser = StompParser()
        self.commandMap = {
            StompSpec.CONNECT: self.handleConnect,
            StompSpec.DISCONNECT: self.handleDisconnect,
            StompSpec.SEND: self.handleSend,
            StompSpec.SUBSCRIBE: self.handleSubscribe,
            StompSpec.ACK: self.handleAck,
            StompSpec.NACK: self.handleNack
        }

    def connectionMade(self):
        self.log.debug('Connection made')

    def connectionLost(self, reason):
        self.log.debug('Connection lost: %s' % reason)

    def dataReceived(self, data):
        self._parser.add(data)

        for frame in iter(self._parser.get, self._parser.SENTINEL):
            try:
                self.log.debug('Received %s' % frame.info())
            except KeyError:
                raise StompFrameError('Unknown STOMP command: %s' % repr(frame))
            self.commandMap[frame.command](frame)

    def getFrame(self, command, headers, body):
        return binaryType(StompFrame(command, headers, body, version=self._parser.version))

    def handleConnect(self, frame):
        pass

    def handleDisconnect(self, frame):
        pass

    def handleSend(self, frame):
        pass

    def handleSubscribe(self, frame):
        pass

    def handleAck(self, frame):
        pass

    def handleNack(self, frame):
        pass
Beispiel #31
0
    def test_decode(self):
        headers = {u'fen\xeatre': u'\xbfqu\xe9 tal?, s\xfc\xdf'}
        frameBytes = str(
            StompFrame(command=StompSpec.DISCONNECT,
                       headers=headers,
                       version=StompSpec.VERSION_1_1))

        parser = StompParser(version=StompSpec.VERSION_1_1)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(frame.headers, headers)

        parser = StompParser(version=StompSpec.VERSION_1_0)
        self.assertRaises(UnicodeDecodeError, parser.add, frameBytes)
Beispiel #32
0
    def test_frame_parse_succeeds(self):
        frame = StompFrame(
            StompSpec.SEND, {
                'foo': 'bar',
                'hello ': 'there-world with space ',
                'empty-value': '',
                '': 'empty-header',
                StompSpec.DESTINATION_HEADER: '/queue/blah'
            }, b'some stuff\nand more')

        parser = StompParser()
        parser.add(binaryType(frame))
        self.assertEqual(parser.get(), frame)
        self.assertIsNone(parser.get())
Beispiel #33
0
    def test_duplicate_headers(self):
        command = StompSpec.SEND
        rawFrame = '%s\nfoo:bar1\nfoo:bar2\n\nsome stuff\nand more\x00' % (
            command, )

        parser = StompParser()
        parser.add(rawFrame.encode())
        parsedFrame = parser.get()
        self.assertIsNone(parser.get())

        self.assertEqual(parsedFrame.command, command)
        self.assertEqual(parsedFrame.headers, {'foo': 'bar1'})
        self.assertEqual(parsedFrame.rawHeaders, [('foo', 'bar1'),
                                                  ('foo', 'bar2')])
        self.assertEqual(parsedFrame.body, b'some stuff\nand more')
Beispiel #34
0
 def test_frames_with_heart_beats_succeeds(self):
     parser = StompParser(version=StompSpec.VERSION_1_1)
     disconnect = commands.disconnect()
     frame = b'\n' + binaryType(disconnect) + b'\n'
     parser.add(2 * frame)
     frames = []
     while parser.canRead():
         frames.append(parser.get())
     self.assertEqual(frames, [
         StompHeartBeat(), disconnect,
         StompHeartBeat(),
         StompHeartBeat(), disconnect,
         StompHeartBeat()
     ])
     self.assertIsNone(parser.get())
Beispiel #35
0
    def test_decode(self):
        key = b'fen\xc3\xaatre'.decode('utf-8')
        value = b'\xc2\xbfqu\xc3\xa9 tal?'.decode('utf-8')
        headers = {key: value}
        frameBytes = binaryType(
            StompFrame(command=StompSpec.DISCONNECT,
                       headers=headers,
                       version=StompSpec.VERSION_1_1))

        parser = StompParser(version=StompSpec.VERSION_1_1)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEqual(frame.headers, headers)

        parser = StompParser(version=StompSpec.VERSION_1_0)
        self.assertRaises(UnicodeDecodeError, parser.add, frameBytes)
Beispiel #36
0
 def test_binary_body_invalid_eof(self):
     parser = StompParser()
     body = b'MESSAGE\ncontent-length:4\n\n\xf0\x00\n\t\x00'
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
     self.assertRaises(StompFrameError, parser.add, b'MESSAGE\ncontent-length:4\n\n\xf0\n\t\xff\x01\n\nCONNECT\n\x00') # \x00 behind invalid EOF
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
     self.assertRaises(StompFrameError, parser.add, b'MESSAGE\ncontent-length:4\n\n\xf0\n\t\xff\x01\x00') # \x00 just behind invalid EOF
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
     self.assertRaises(StompFrameError, parser.add, b'MESSAGE\ncontent-length:4\n\n\xf0\x00\n\t\x01') # \x00 before invalid EOF
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
     self.assertRaises(StompFrameError, parser.add, b'MESSAGE\ncontent-length:4\n\n\xf0\n\t\x00\x01') # \x00 just before invalid EOF
     parser.add(body)
     self.assertEqual(binaryType(parser.get()), body)
Beispiel #37
0
    def test_reset_succeeds(self):
        frame = StompFrame(command=StompSpec.SEND,
                           headers={
                               'foo': 'bar',
                               'hello ': 'there-world with space ',
                               'empty-value': '',
                               '': 'empty-header',
                               StompSpec.DESTINATION_HEADER: '/queue/blah'
                           },
                           body=b'some stuff\nand more')
        parser = StompParser()

        parser.add(binaryType(frame))
        parser.reset()
        self.assertIsNone(parser.get())
        parser.add(binaryType(frame)[:20])
        self.assertIsNone(parser.get())
Beispiel #38
0
    def test_strip_line_delimiter(self):
        queue = '/queue/test'
        frame = commands.send(queue)
        frameWithStripLineDelimiter = commands.send(queue + '\r')
        for (version, stripLineDelimiter) in [
            (StompSpec.VERSION_1_0, False),
            (StompSpec.VERSION_1_1, False),
            (StompSpec.VERSION_1_2, True)
        ]:
            parser = StompParser(version)
            parser.add(binaryType(frameWithStripLineDelimiter))
            self.assertEqual(parser.get(), frame if stripLineDelimiter else frameWithStripLineDelimiter)

        frameWithCarriageReturn = commands.send(queue + '\r', version=StompSpec.VERSION_1_2)
        parser = StompParser(StompSpec.VERSION_1_2)
        parser.add(binaryType(frameWithCarriageReturn))
        self.assertEqual(parser.get().headers[StompSpec.DESTINATION_HEADER], queue + '\r')
Beispiel #39
0
    def test_strip_line_delimiter(self):
        queue = '/queue/test'
        frame = commands.send(queue)
        frameWithStripLineDelimiter = commands.send(queue + '\r')
        for (version, stripLineDelimiter) in [(StompSpec.VERSION_1_0, False),
                                              (StompSpec.VERSION_1_1, False),
                                              (StompSpec.VERSION_1_2, True)]:
            parser = StompParser(version)
            parser.add(binaryType(frameWithStripLineDelimiter))
            self.assertEqual(
                parser.get(),
                frame if stripLineDelimiter else frameWithStripLineDelimiter)

        frameWithCarriageReturn = commands.send(queue + '\r',
                                                version=StompSpec.VERSION_1_2)
        parser = StompParser(StompSpec.VERSION_1_2)
        parser.add(binaryType(frameWithCarriageReturn))
        self.assertEqual(parser.get().headers[StompSpec.DESTINATION_HEADER],
                         queue + '\r')
Beispiel #40
0
    def test_add_multiple_frames_per_read(self):
        body1 = b'boo'
        body2 = b'hoo'
        headers = {'x': 'y'}
        frameBytes = binaryType(StompFrame(StompSpec.MESSAGE, headers, body1)) + binaryType(StompFrame(StompSpec.MESSAGE, headers, body2))
        parser = StompParser()
        parser.add(frameBytes)

        frame = parser.get()
        self.assertEqual(StompSpec.MESSAGE, frame.command)
        self.assertEqual(headers, frame.headers)
        self.assertEqual(body1, frame.body)

        frame = parser.get()
        self.assertEqual(StompSpec.MESSAGE, frame.command)
        self.assertEqual(headers, frame.headers)
        self.assertEqual(body2, frame.body)

        self.assertIsNone(parser.get())
Beispiel #41
0
 def test_strip_line_delimiter(self):
     queue = '/queue/test'
     frame = commands.send(queue)
     rawFrameReplaced = str(commands.send(queue)).replace('\n', '\r\n')
     for (version, replace) in [(StompSpec.VERSION_1_0, False),
                                (StompSpec.VERSION_1_1, False),
                                (StompSpec.VERSION_1_2, True)]:
         if replace:
             parser = StompParser(version)
             parser.add(rawFrameReplaced)
             self.assertEquals(parser.get(), frame)
         else:
             self.assertRaises(StompFrameError,
                               StompParser(version).add, rawFrameReplaced)
     textWithCarriageReturn = 'there\rfolks'
     frame = commands.send(queue, headers={'hi': textWithCarriageReturn})
     parser = StompParser(StompSpec.VERSION_1_2)
     parser.add(str(frame))
     self.assertEquals(parser.get().headers['hi'], textWithCarriageReturn)
Beispiel #42
0
    def test_add_multiple_frames_per_read(self):
        body1 = 'boo'
        body2 = 'hoo'
        headers = {'x': 'y'}
        frameBytes = str(StompFrame(StompSpec.MESSAGE, headers, body1)) + str(StompFrame(StompSpec.MESSAGE, headers, body2))
        parser = StompParser()
        parser.add(frameBytes)

        frame = parser.get()
        self.assertEquals(StompSpec.MESSAGE, frame.command)
        self.assertEquals(headers, frame.headers)
        self.assertEquals(body1, frame.body)

        frame = parser.get()
        self.assertEquals(StompSpec.MESSAGE, frame.command)
        self.assertEquals(headers, frame.headers)
        self.assertEquals(body2, frame.body)

        self.assertEquals(parser.get(), None)
Beispiel #43
0
    def test_add_multiple_frames_per_read(self):
        body1 = 'boo'
        body2 = 'hoo'
        headers = {'x': 'y'}
        frameBytes = str(StompFrame(StompSpec.MESSAGE, headers, body1)) + str(
            StompFrame(StompSpec.MESSAGE, headers, body2))
        parser = StompParser()
        parser.add(frameBytes)

        frame = parser.get()
        self.assertEquals(StompSpec.MESSAGE, frame.command)
        self.assertEquals(headers, frame.headers)
        self.assertEquals(body1, frame.body)

        frame = parser.get()
        self.assertEquals(StompSpec.MESSAGE, frame.command)
        self.assertEquals(headers, frame.headers)
        self.assertEquals(body2, frame.body)

        self.assertEquals(parser.get(), None)
Beispiel #44
0
 def test_strip_line_delimiter(self):
     queue = '/queue/test'
     frame = commands.send(queue)
     rawFrameReplaced = str(commands.send(queue)).replace('\n', '\r\n')
     for (version, replace) in [
         (StompSpec.VERSION_1_0, False),
         (StompSpec.VERSION_1_1, False),
         (StompSpec.VERSION_1_2, True)
     ]:
         if replace:
             parser = StompParser(version)
             parser.add(rawFrameReplaced)
             self.assertEquals(parser.get(), frame)
         else:
             self.assertRaises(StompFrameError, StompParser(version).add, rawFrameReplaced)
     textWithCarriageReturn = 'there\rfolks'
     frame = commands.send(queue, headers={'hi': textWithCarriageReturn})
     parser = StompParser(StompSpec.VERSION_1_2)
     parser.add(str(frame))
     self.assertEquals(parser.get().headers['hi'], textWithCarriageReturn)
Beispiel #45
0
 def test_invalid_command(self):
     messages = [
         'RECEIPT\nreceipt-id:message-12345\n\n\x00',
         'NACK\nsubscription:0\nmessage-id:007\n\n\x00'
     ]
     parser = StompParser('1.0')
     parser.add(messages[0])
     self.assertRaises(StompFrameError, parser.add, messages[1])
     self.assertEquals(
         parser.get(),
         StompFrame(StompSpec.RECEIPT,
                    rawHeaders=((u'receipt-id', u'message-12345'), )))
     self.assertFalse(parser.canRead())
     self.assertEquals(parser.get(), None)
     parser = StompParser('1.1')
     parser.add(messages[1])
     self.assertEquals(
         parser.get(),
         StompFrame(command=u'NACK',
                    rawHeaders=((u'subscription', u'0'), (u'message-id',
                                                          u'007'))))
Beispiel #46
0
    def test_add_multiple_frames_per_read(self):
        body1 = b'boo'
        body2 = b'hoo'
        headers = {'x': 'y'}
        frameBytes = binaryType(StompFrame(
            StompSpec.MESSAGE, headers, body1)) + binaryType(
                StompFrame(StompSpec.MESSAGE, headers, body2))
        parser = StompParser()
        parser.add(frameBytes)

        frame = parser.get()
        self.assertEqual(StompSpec.MESSAGE, frame.command)
        self.assertEqual(headers, frame.headers)
        self.assertEqual(body1, frame.body)

        frame = parser.get()
        self.assertEqual(StompSpec.MESSAGE, frame.command)
        self.assertEqual(headers, frame.headers)
        self.assertEqual(body2, frame.body)

        self.assertIsNone(parser.get())
Beispiel #47
0
 def test_invalid_command(self):
     messages = [
         b'RECEIPT\nreceipt-id:message-12345\n\n\x00',
         b'NACK\nsubscription:0\nmessage-id:007\n\n\x00'
     ]
     parser = StompParser(StompSpec.VERSION_1_0)
     parser.add(messages[0])
     self.assertRaises(StompFrameError, parser.add, messages[1])
     self.assertEqual(
         parser.get(),
         StompFrame(StompSpec.RECEIPT,
                    rawHeaders=(('receipt-id', 'message-12345'), )))
     self.assertFalse(parser.canRead())
     self.assertIsNone(parser.get())
     parser = StompParser(StompSpec.VERSION_1_1)
     parser.add(messages[1])
     self.assertEqual(
         parser.get(),
         StompFrame(command='NACK',
                    rawHeaders=(('subscription', '0'), ('message-id',
                                                        '007')),
                    version=StompSpec.VERSION_1_1))
Beispiel #48
0
def socks_backend(msg, session):
    parser = StompParser('1.1')

    if msg.data:
        parser.add(msg.data.encode('UTF-8'))

    frame = parser.get()

    manager = sockjs.get_manager('clients', app)

    if msg.tp == sockjs.MSG_OPEN:
        pass

    elif msg.tp == sockjs.MSG_MESSAGE:
        if frame.command == 'CONNECT':
            headers = {}
            headers['session'] = session.id

            msg = StompFrame(command='CONNECTED', headers=headers)

            session.send(bytes(msg).decode('UTF-8'))

            session.subscriptions = {}

        elif frame.command == 'SUBSCRIBE':
            subscription = frame.headers['id']
            session.subscriptions[frame.headers['destination']] = subscription

        elif frame.command == 'UNSUBSCRIBE':
            del session.subscriptions[frame.headers['destination']]

    elif msg.tp == sockjs.MSG_CLOSE:
        pass

    elif msg.tp == sockjs.MSG_CLOSED:
        pass
Beispiel #49
0
    def test_unescape(self):
        frameBytes = ("""%s
\\n\\\\:\\c\t\\n

\x00""" % StompSpec.DISCONNECT).encode()

        for version in (StompSpec.VERSION_1_1, StompSpec.VERSION_1_2):
            parser = StompParser(version=version)
            parser.add(frameBytes)
            frame = parser.get()
            self.assertEqual(frame.headers, {'\n\\': ':\t\n'})

        parser = StompParser(version=StompSpec.VERSION_1_0)
        parser.add(frameBytes)
        self.assertEqual(
            parser.get(),
            StompFrame(command='DISCONNECT',
                       rawHeaders=[('\\n\\\\', '\\c\t\\n')]))

        frameBytes = ("""%s
\\n\\\\:\\c\\t

\x00""" % StompSpec.DISCONNECT).encode()

        for version in (StompSpec.VERSION_1_1, StompSpec.VERSION_1_2):
            self.assertRaises(StompFrameError,
                              StompParser(version=version).add, frameBytes)

        parser = StompParser(version=StompSpec.VERSION_1_0)
        parser.add(frameBytes)
        self.assertEqual(
            parser.get(),
            StompFrame(command='DISCONNECT',
                       rawHeaders=[('\\n\\\\', '\\c\\t')]))

        frameBytes = ("""%s
\\n\\\\:\\c\t\\r

\x00""" % StompSpec.DISCONNECT).encode()

        parser = StompParser(version=StompSpec.VERSION_1_2)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEqual(frame.headers, {'\n\\': ':\t\r'})
Beispiel #50
0
    def test_unescape(self):
        frameBytes = """%s
\\n\\\\:\\c\t\\n

\x00""" % StompSpec.DISCONNECT

        for version in (StompSpec.VERSION_1_1, StompSpec.VERSION_1_2):
            parser = StompParser(version=version)
            parser.add(frameBytes)
            frame = parser.get()
            self.assertEquals(frame.headers, {'\n\\': ':\t\n'})

        parser = StompParser(version=StompSpec.VERSION_1_0)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(frame.headers, {'\\n\\\\': '\\c\t\\n'})

        frameBytes = """%s
\\n\\\\:\\c\\t

\x00""" % StompSpec.DISCONNECT

        for version in (StompSpec.VERSION_1_1, StompSpec.VERSION_1_2):
            self.assertRaises(StompFrameError,
                              StompParser(version=version).add, frameBytes)

        parser = StompParser(version=StompSpec.VERSION_1_0)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(frame.headers, {'\\n\\\\': '\\c\\t'})

        frameBytes = """%s
\\n\\\\:\\c\t\\r

\x00""" % StompSpec.DISCONNECT

        parser = StompParser(version=StompSpec.VERSION_1_2)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(frame.headers, {'\n\\': ':\t\r'})
Beispiel #51
0
    def test_unescape(self):
        frameBytes = """%s
\\n\\\\:\\c\t\\n

\x00""" % StompSpec.DISCONNECT

        for version in (StompSpec.VERSION_1_1, StompSpec.VERSION_1_2):
            parser = StompParser(version=version)
            parser.add(frameBytes)
            frame = parser.get()
            self.assertEquals(frame.headers, {'\n\\': ':\t\n'})

        parser = StompParser(version=StompSpec.VERSION_1_0)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(frame.headers, {'\\n\\\\': '\\c\t\\n'})

        frameBytes = """%s
\\n\\\\:\\c\\t

\x00""" % StompSpec.DISCONNECT

        for version in (StompSpec.VERSION_1_1, StompSpec.VERSION_1_2):
            self.assertRaises(StompFrameError, StompParser(version=version).add, frameBytes)

        parser = StompParser(version=StompSpec.VERSION_1_0)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(frame.headers, {'\\n\\\\': '\\c\\t'})

        frameBytes = """%s
\\n\\\\:\\c\t\\r

\x00""" % StompSpec.DISCONNECT

        parser = StompParser(version=StompSpec.VERSION_1_2)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEquals(frame.headers, {'\n\\': ':\t\r'})
Beispiel #52
0
    def test_unescape(self):
        frameBytes = ("""%s
\\n\\\\:\\c\t\\n

\x00""" % StompSpec.DISCONNECT).encode()

        for version in (StompSpec.VERSION_1_1, StompSpec.VERSION_1_2):
            parser = StompParser(version=version)
            parser.add(frameBytes)
            frame = parser.get()
            self.assertEqual(frame.headers, {'\n\\': ':\t\n'})

        parser = StompParser(version=StompSpec.VERSION_1_0)
        parser.add(frameBytes)
        self.assertEqual(parser.get(), StompFrame(command='DISCONNECT', rawHeaders=[('\\n\\\\', '\\c\t\\n')]))

        frameBytes = ("""%s
\\n\\\\:\\c\\t

\x00""" % StompSpec.DISCONNECT).encode()

        for version in (StompSpec.VERSION_1_1, StompSpec.VERSION_1_2):
            self.assertRaises(StompFrameError, StompParser(version=version).add, frameBytes)

        parser = StompParser(version=StompSpec.VERSION_1_0)
        parser.add(frameBytes)
        self.assertEqual(parser.get(), StompFrame(command='DISCONNECT', rawHeaders=[('\\n\\\\', '\\c\\t')]))

        frameBytes = ("""%s
\\n\\\\:\\c\t\\r

\x00""" % StompSpec.DISCONNECT).encode()

        parser = StompParser(version=StompSpec.VERSION_1_2)
        parser.add(frameBytes)
        frame = parser.get()
        self.assertEqual(frame.headers, {'\n\\': ':\t\r'})
Beispiel #53
0
 def test_body_allowed_commands(self):
     head = str(commands.disconnect()).rstrip(StompSpec.FRAME_DELIMITER)
     for (version, bodyAllowed) in [(StompSpec.VERSION_1_0, True),
                                    (StompSpec.VERSION_1_1, False),
                                    (StompSpec.VERSION_1_2, False)]:
         parser = StompParser(version)
         parser.add(head)
         parser.add('ouch!')
         try:
             parser.add(StompSpec.FRAME_DELIMITER)
         except StompFrameError:
             if bodyAllowed:
                 raise
         except:
             raise
         else:
             if not bodyAllowed:
                 raise
Beispiel #54
0
 def test_body_allowed_commands(self):
     head = binaryType(commands.disconnect()).rstrip(StompSpec.FRAME_DELIMITER.encode())
     for (version, bodyAllowed) in [
         (StompSpec.VERSION_1_0, True),
         (StompSpec.VERSION_1_1, False),
         (StompSpec.VERSION_1_2, False)
     ]:
         parser = StompParser(version)
         parser.add(head)
         parser.add(b'ouch!')
         try:
             parser.add(StompSpec.FRAME_DELIMITER.encode())
         except StompFrameError:
             if bodyAllowed:
                 raise
         except:
             raise
         else:
             if not bodyAllowed:
                 raise
Beispiel #55
0
 def test_frame_without_header_or_body_succeeds(self):
     parser = StompParser()
     parser.add(binaryType(commands.disconnect()))
     self.assertEqual(parser.get(), commands.disconnect())
Beispiel #56
0
 def test_frame_without_header_or_body_succeeds(self):
     parser = StompParser()
     parser.add(binaryType(commands.disconnect()))
     self.assertEqual(parser.get(), commands.disconnect())
Beispiel #57
0
 def test_get_returns_None_if_not_done(self):
     parser = StompParser()
     self.assertEqual(None, parser.get())
     parser.add(StompSpec.CONNECT.encode())
     self.assertEqual(None, parser.get())
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))
Beispiel #59
0
 def test_colon_in_header_value(self):
     parser = StompParser()
     parser.add(
         ('%s\nheader:with:colon\n\n\x00' % StompSpec.DISCONNECT).encode())
     self.assertEqual(parser.get().headers['header'], 'with:colon')