[Twisted-Python] Unit testing, trail, inlineCallbacks, deferreds and mocking

Patryk Ściborek patryk at sciborek.com
Tue Jan 27 06:00:18 MST 2015


Hi!

I've just started a new project using Twisted and I want to write unit
tests since the beginning. Unfortunately I've got some trouble
understanding how should I do it. I read 'Test-driven development with
Twisted', read some articles on the web and searched on the mailing list
but I couldn't find anything which make it clear for me.

I've got a class:

class SessionCleaner(object):
    def __init__(self, session_db, interval=10):
        self.session_db = session_db
        self.lc = task.LoopingCall(self.check_old_sessions)
        self.lc.start(interval)

    @defer.inlineCallbacks
    def check_old_sessions(self):
        log.msg('check_old_sessions()', logLevel=logging.DEBUG)
        try:
            old_sessions = yield self.session_db.get_old_sessions()
            for s in old_sessions:
                yield self.session_db.process_stopped(s)

        except txredisapi.ConnectionError as e:
            log.msg('check_old_sessions - connection error {}'
                    .format(e), logLevel=logging.WARNING)

session_db is a object with methods which makes some calls to Redis.

Testing if __init__ works correctly is easy - I can mock task.LoopingCall
and check if it was called with correct attributes.

I've got trouble testing check_old_sessions. Since I'm writing unit tests I
don't want to call real session_db methods and make real Redis queries. I'd
like to mock them and test just few things:
- is the method get_old_sessions called?
- is the method process_stopped called N times with the arguments returned
by mocked get_old_sessions?
- is txredisapi.ConnectionError handled correctly?

So is there any "right" way of mocking functions which returns deferreds?
Or maybe I should test this method differently?

Best regards,
Patryk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://twistedmatrix.com/pipermail/twisted-python/attachments/20150127/94ef0786/attachment.html>


More information about the Twisted-Python mailing list