<commit_before>"""
Tests for queue-related classes.
"""
import unittest
import uuid

from stompclient.frame import Frame

from coilmq.queue import QueueManager
from coilmq.store.memory import MemoryQueue
 
from coilmq.tests.mock import MockConnection

__authors__ = ['"<NAME>" <<EMAIL>>']
__copyright__ = "Copyright 2009 <NAME>"
__license__ = """Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License."""

class QueueManagerTest(unittest.TestCase):
    """ Test the QueueManager class. """
    
    def _queuestore(self):
        """
        Returns the configured L{QueueStore} instance to use.
        
        Can be overridden by subclasses that wish to change out any queue store parameters.
        
        @rtype: L{QueueStore}
        """
        return MemoryQueue()
        
    def setUp(self):
        self.store = self._queuestore()
        self.qm = QueueManager(self.store)
        self.conn = MockConnection()
    
    def test_subscribe(self):
        """ Test subscribing a connection to the queue. """
        dest = '/queue/dest'
        
        self.qm.subscribe(self.conn, dest)
        f = Frame('MESSAGE', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        print self.conn.frames
        assert len(self.conn.frames) == 1
        assert self.conn.frames[0] == f
    
    def test_unsubscribe(self):
        """ Test unsubscribing a connection from the queue. """
        dest = '/queue/dest'
        
        self.qm.subscribe(self.conn, dest)
        f = Frame('MESSAGE', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        print self.conn.frames
        assert len(self.conn.frames) == 1
        assert self.conn.frames[0] == f
        
        self.qm.unsubscribe(self.conn, dest)
        f = Frame('MESSAGE', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        assert len(self.conn.frames) == 1
        assert len(self.store.frames(dest)) == 1
        
    def send_simple(self):
        """ Test a basic send command. """
        dest = '/queue/dest'
        
        f = Frame('SEND', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        assert dest in self.store.destinations()
        assert len(self.store.frames(dest)) == 1
        
        # Assert some side-effects
        assert 'message-id' in f.headers
        assert f.command == 'MESSAGE'
        
    
    def test_send_err(self):
        """ Test sending a message when delivery results in error. """
        
        class ExcThrowingConn(object):
            reliable_subscriber = True
            def send_frame(self, frame):
                raise RuntimeError("Error sending data.")
        
        dest = '/queue/dest'
        
        # This reliable subscriber will be chosen first
        conn = ExcThrowingConn()
        self.qm.subscribe(conn, dest)
        
        f = Frame('SEND', headers={'destination': dest}, body='Empty')
        try:
            self.qm.send(f)
            self.fail("Expected failure when there was an error sending.")
        except RuntimeError:
            pass
        
        
    def test_send_backlog_err_reliable(self):
        """ Test errors when sending backlog to reliable subscriber. """
        
        class ExcThrowingConn(object):
            reliable_subscriber = True
            def send_frame(self, frame):
                raise RuntimeError("Error sending data.")
        
        dest = '/queue/dest'
        
        f = Frame('SEND', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        conn = ExcThrowingConn()
        try:
            self.qm.subscribe(conn, dest)
            self.fail("Expected error when sending backlog.")
        except RuntimeError:
            pass
        
        # The message will have been requeued at this point, so add a valid
        # subscriber
        
        self.qm.subscribe(self.conn, dest)
        
        print "Frames: %r" % self.conn.frames
        
        assert len(self.conn.frames) == 1, "Expected frame to be delivered"
        assert self.conn.frames[0] == f
        
    def test_send_backlog_err_unreliable(self):
        """ Test errors when sending backlog to reliable subscriber. """
        
        class ExcThrowingConn(object):
            reliable_subscriber = False
            def send_frame(self, frame):
                raise RuntimeError("Error sending data.")
        
        dest = '/queue/dest'
        
        f = Frame('SEND', headers={'destination': dest}, body='123')
        self.qm.send(f)
        
        f2 = Frame('SEND', headers={'destination': dest}, body='12345')
        self.qm.send(f2)
        
        conn = ExcThrowingConn()
        try:
            self.qm.subscribe(conn, dest)
            self.fail("Expected error when sending backlog.")
        except RuntimeError:
            pass
        
        # The message will have been requeued at this point, so add a valid
        # subscriber
        
        print "Queue state: %r" % (self.store._messages,)
        
        self.qm.subscribe(self.conn, dest)
        
        print "Frames: %r" % self.conn.frames
        <commit_msg>Removed MemoryStore-specific introspection from the unit tests.<commit_after>"""
Tests for queue-related classes.
"""
import unittest
import uuid

from stompclient.frame import Frame

from coilmq.queue import QueueManager
from coilmq.store.memory import MemoryQueue
 
from coilmq.tests.mock import MockConnection

__authors__ = ['"<NAME>" <<EMAIL>>']
__copyright__ = "Copyright 2009 <NAME>"
__license__ = """Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License."""

class QueueManagerTest(unittest.TestCase):
    """ Test the QueueManager class. """
    
    def _queuestore(self):
        """
        Returns the configured L{QueueStore} instance to use.
        
        Can be overridden by subclasses that wish to change out any queue store parameters.
        
        @rtype: L{QueueStore}
        """
        return MemoryQueue()
        
    def setUp(self):
        self.store = self._queuestore()
        self.qm = QueueManager(self.store)
        self.conn = MockConnection()
    
    def test_subscribe(self):
        """ Test subscribing a connection to the queue. """
        dest = '/queue/dest'
        
        self.qm.subscribe(self.conn, dest)
        f = Frame('MESSAGE', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        print self.conn.frames
        assert len(self.conn.frames) == 1
        assert self.conn.frames[0] == f
    
    def test_unsubscribe(self):
        """ Test unsubscribing a connection from the queue. """
        dest = '/queue/dest'
        
        self.qm.subscribe(self.conn, dest)
        f = Frame('MESSAGE', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        print self.conn.frames
        assert len(self.conn.frames) == 1
        assert self.conn.frames[0] == f
        
        self.qm.unsubscribe(self.conn, dest)
        f = Frame('MESSAGE', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        assert len(self.conn.frames) == 1
        assert len(self.store.frames(dest)) == 1
        
    def send_simple(self):
        """ Test a basic send command. """
        dest = '/queue/dest'
        
        f = Frame('SEND', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        assert dest in self.store.destinations()
        assert len(self.store.frames(dest)) == 1
        
        # Assert some side-effects
        assert 'message-id' in f.headers
        assert f.command == 'MESSAGE'
        
    
    def test_send_err(self):
        """ Test sending a message when delivery results in error. """
        
        class ExcThrowingConn(object):
            reliable_subscriber = True
            def send_frame(self, frame):
                raise RuntimeError("Error sending data.")
        
        dest = '/queue/dest'
        
        # This reliable subscriber will be chosen first
        conn = ExcThrowingConn()
        self.qm.subscribe(conn, dest)
        
        f = Frame('SEND', headers={'destination': dest}, body='Empty')
        try:
            self.qm.send(f)
            self.fail("Expected failure when there was an error sending.")
        except RuntimeError:
            pass
        
        
    def test_send_backlog_err_reliable(self):
        """ Test errors when sending backlog to reliable subscriber. """
        
        class ExcThrowingConn(object):
            reliable_subscriber = True
            def send_frame(self, frame):
                raise RuntimeError("Error sending data.")
        
        dest = '/queue/dest'
        
        f = Frame('SEND', headers={'destination': dest}, body='Empty')
        self.qm.send(f)
        
        conn = ExcThrowingConn()
        try:
            self.qm.subscribe(conn, dest)
            self.fail("Expected error when sending backlog.")
        except RuntimeError:
            pass
        
        # The message will have been requeued at this point, so add a valid
        # subscriber
        
        self.qm.subscribe(self.conn, dest)
        
        print "Frames: %r" % self.conn.frames
        
        assert len(self.conn.frames) == 1, "Expected frame to be delivered"
        assert self.conn.frames[0] == f
        
    def test_send_backlog_err_unreliable(self):
        """ Test errors when sending backlog to reliable subscriber. """
        
        class ExcThrowingConn(object):
            reliable_subscriber = False
            def send_frame(self, frame):
                raise RuntimeError("Error sending data.")
        
        dest = '/queue/dest'
        
        f = Frame('SEND', headers={'destination': dest}, body='123')
        self.qm.send(f)
        
        f2 = Frame('SEND', headers={'destination': dest}, body='12345')
        self.qm.send(f2)
        
        conn = ExcThrowingConn()
        try:
            self.qm.subscribe(conn, dest)
            self.fail("Expected error when sending backlog.")
        except RuntimeError:
            pass
        
        # The message will have been requeued at this point, so add a valid
        # subscriber
        
        self.qm.subscribe(self.conn, dest)
        
        print "Frames: %r" % self.conn.frames
        
{'fraction_non_alphanumeric': 0.10353646706058735, 'fraction_numerical': 0.004762324719992945, 'mean_word_length': 1.9952456418383517, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3595570', 'n_tokens_mistral': 3130, 'n_tokens_neox': 3056, 'n_words': 903}