[Twisted-Python] testing for error conditions
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. But now I want to verify that I get errors (errbacks) in all the places I should. I was hoping to do the same thing as before, only now swap the function of the errbacks with that of the callbacks. This doesn't seem to work. Returning a deferred from an errback still results in its parent errbacks getting called, terminating the test program prematurely. Whats the right way to test conditions that should trigger errbacks? I couldn't see a tutorial or doc that covered this. Thanks, Gary
On 2/2/07, gary jefferson <garyjefferson123@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
participants (2)
-
gary jefferson
-
Jonathan Lange