import autopath
import py
import socket
from httpmp2.outchannel import OutChannel, BufferOverload

class config:
    max_events_per_request = 2
    max_events_in_buffer = 2

class MockHTTPChannel(object):
    def __init__(self):
        self.pushed = []
        self.closed = False

    def push_with_producer(self, p):
        if self.closed:
            raise socket.error(1)
        self.pushed.append(p)

    def close_when_done(self):
        self.closed = True

class TestOutChannel(object):
    def setup_method(self, meth):
        self.httpchannel = h = MockHTTPChannel()
        self.outchannel = OutChannel(config, h)

    def test_outchannel_basic(self):
        self.outchannel.push_command('foo')
        assert self.httpchannel.pushed == ['foo']
        self.outchannel.push_command('bar')
        assert self.httpchannel.pushed == ['foo', 'bar']

    def test_reconnect(self):
        self.httpchannel.closed = True
        self.outchannel.push_command('foo')
        self.outchannel.httpchannel = h2 = MockHTTPChannel()
        self.outchannel.push_command('bar')
        assert h2.pushed == ['foo', 'bar']

    def test_max_events_per_request(self):
        self.outchannel.push_command('foo')
        self.outchannel.push_command('bar')
        self.outchannel.push_command('baz')
        assert self.httpchannel.pushed == ['foo', 'bar']
        self.outchannel.httpchannel = h2 = MockHTTPChannel()
        self.outchannel.push_command('qux')
        assert h2.pushed == ['baz', 'qux']

    def test_max_events_in_buffer(self):
        self.outchannel.push_command('foo')
        self.outchannel.push_command('bar')
        assert self.httpchannel.closed
        self.outchannel.push_command('baz')
        self.outchannel.push_command('qux')
        py.test.raises(BufferOverload, "self.outchannel.push_command('quux')")



