import cStringIO
from twisted.spread import pb
from twisted.trial import unittest
from twisted.test import proto_helpers

class Document(pb.Root):

    def remote_convert(self, props):
        self.props = props


class DocTestCase(unittest.TestCase):

    def setUp(self):
        # set up server
        self.doc = Document()
        factory = pb.PBServerFactory(self.doc)
        self.broker = factory.buildProtocol(('127.0.0.1', 0))
        tr = proto_helpers.StringTransport()
        self.broker.makeConnection(tr)


        # this is what a client sends
        self.props = {'name': 'MyDoc',
                      'path': '/path/'}

        # prepare data
        serialized_props = self.broker.serialize(self.props)
        msg = ('message', 1, 'root', 'convert', 1,
               ['tuple', serialized_props], ['dictionary'])
        io = cStringIO.StringIO()
        self.broker._encode(msg, io.write)
        self.chunk = io.getvalue()

    def test_convert(self):
        # data arrived
        self.broker.dataReceived(self.chunk)

        self.assertEqual(self.props, self.doc.props)
