[Twisted-Python] Avoiding network when testing Perspective Broker

Maxim Lacrima lacrima.maxim at gmail.com
Fri Oct 26 08:02:52 MDT 2012


Hi!

Your replies are very encouraging. Thank you!


> I'm curious, since we rarely get to see the positive impact of
> documentation, and only hear about it when it didn't exist - did you
> discover this testing style from
> http://twistedmatrix.com/documents/current/core/howto/trial.html#auto5 ?
> :)
>
>
Yes, I started from that document. It describes well how to call certain
parts of Twisted to check some behavior and this stimulated me to discover
Twisted API.

I think I have finally discovered a good way for writing tests that use PB.
I used `test.test_pb.IOPump` `test.test_pb.connectedServerAndClient` as a
basis for my tests.
--------
from twisted.spread import pb
from twisted.trial import unittest
from twisted.test import proto_helpers

class Document(pb.Root):

    def remote_convert(self):
        return 'I was called'


class IOPump:

    def __init__(self, client, server, clientIO, serverIO):
        self.client = client
        self.server = server
        self.clientIO = clientIO
        self.serverIO = serverIO

    def pump(self):
        cData = self.clientIO.value()
        sData = self.serverIO.value()
        self.clientIO.clear()
        self.serverIO.clear()
        self.server.dataReceived(cData)
        self.client.dataReceived(sData)


def connect(root):
    serverFactory = pb.PBServerFactory(root())
    serverBroker = serverFactory.buildProtocol(())

    clientFactory = pb.PBClientFactory()
    clientBroker = clientFactory.buildProtocol(())

    clientTransport = proto_helpers.StringTransport()
    serverTransport = proto_helpers.StringTransport()
    clientBroker.makeConnection(clientTransport)
    serverBroker.makeConnection(serverTransport)

    pump = IOPump(clientBroker, serverBroker, clientTransport,
serverTransport)
    # initial communication
    pump.pump()

    return clientFactory, serverFactory, pump


class DocTestCase(unittest.TestCase):

    def test_convert(self):
        def cb0(doc):
            d = doc.callRemote('convert')
            return d

        def cb1(res):
            self.assertEqual('I was called', res)
            return res

        client, server, pump = connect(Document)

        d = client.getRootObject()
        d.addCallback(cb0)
        d.addCallback(cb1)

        pump.pump()
        pump.pump()

        return d

--------

The only caveat here is that if I forget to call pump.pump() sufficient
number of times, then the callback with an assertion may not be executed
and this can lead to false positives

-- 
with regards,
Maxim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20121026/a10c59eb/attachment.html>


More information about the Twisted-Python mailing list