[Twisted-Python] "blocking" on a response to a client

meejah meejah at meejah.ca
Mon Nov 5 11:32:38 MST 2018


Chris Withers <chris at simplistix.co.uk> writes:

> So, separate question: I have a client that's making a connection to a
> websocket from a server. The client needs to send an "auth" message
> once the websocket is up, and the client code shouldn't progress until
> it receives an affirmative response. How do I do this in a
> non-blocking way when using twisted? (inside an inlineDeferred method
> in this case!)

There's nothing really special about an @inlineCallbacks method -- it
just returns a Deferred so you can handle it like any other
Deferred-returning method.

> Similarly, how do I get this dance to happen again if the websocket
> drops? How would I do some kind of backoff on he connection retries?

The "Autobahn" Python libraries support all the above. They might not be
great as "examples" per se (because these libraries also support asyncio
so use a compatibility layer called txaio), but a connecting (+
reconnecting) client starts here:

   https://github.com/crossbario/autobahn-python/blob/master/autobahn/wamp/component.py#L494

You could also use the built-in Twisted "ClientService" to keep a
protocol connected (the above doesn't because it's also doing asyncio)
but see:

   https://twistedmatrix.com/documents/current/api/twisted.application.internet.ClientService.html

> And, icing on the cake, where can I find good examples of how to write
> automated tests for all of the above?

It's kind of well-hidden :/ but the "most modern" way is to use
something based on twisted.test.iosim.IOPump as I understand it. I
haven't used this, though so maybe someone else can explain. It's of
course possible to use more-traditional mocking and fakes to write
tests.

Essentially one way is to "drive" your protocol to the correct state
(e.g. right before an auth is required) and then do the various tests on
authentication. You can also do unit-tests of the actual authentication
methods themselves (e.g. "does it parse stuff properly", etc). Again
there's *some* examples in the Autobahn repository above.

Here are some "not IOPump" examples using the Twisted "StringTransport"
helper (this isn't WebSocket but should give some ideas):

   https://github.com/meejah/txtorcon/blob/master/test/test_torcontrolprotocol.py#L80

-- 
meejah




More information about the Twisted-Python mailing list