[Twisted-Python] testing for error conditions

Jonathan Lange jml at mumak.net
Fri Feb 2 01:01:31 EST 2007


On 2/2/07, gary jefferson <garyjefferson123 at gmail.com> wrote:
> I've got a little test program that checks to make sure my protocol
> behaves correctly.  Each function returns a deferred, and sets the
> next function as the callback, and some common function as errback.
> This seems to work great -- the test runs through all the test funcs
> when working properly, and halts at the problem point if not.
>
<snip>
> Whats the right way to test conditions that should trigger errbacks?
> I couldn't see a tutorial or doc that covered this.
>

Hey Gary,

Twisted's unit testing framework, Trial, already has a bunch of
features to make this really easy.

Make a module that contains subclasses of
twisted.trial.unittest.TestCase. The code should look something like
this:

from twisted.trial import unittest

class YourTests(unittest.TestCase):
    def setUp(self):
        self.interestingProtocol = InterestingProtocol()

    def test_successPath(self):
        d = self.interestingProtocol.doSomethingSuccessfully()
        d.addCallback(lambda val: self.assertEqual(val, "expected"))
        return d

    def test_failurePath(self):
        d = self.interestingProtocol.causeErrback()
        return self.assertFailure(d, ExpectedError)


Notice that the two tests in this module both return Deferreds. Trial
will notice this and make sure that the tests are run in sequence.

To run the tests, simple go "trial
yourpackage.test.test_interestingprotocol" on the command line. Trial
accepts paths to files or fully-qualified Python names. If you specify
a package, it will recursively look for all modules under that package
that have names starting with 'test_'.

For more information, consult the API docs for twisted.trial.unittest
and the man page for 'trial'.

I'm sorry that there's not a better overview document for writing
tests for Twisted applications. As the Trial maintainer, it's been on
my radar for some time.

Hope this helps,
jml




More information about the Twisted-Python mailing list