[TIP] Testing asynchronous method
Pere Martir
pere.martir4 at gmail.com
Tue Oct 18 10:40:15 PDT 2011
I want to test if a callback is called within a predefined time. I am
surprised that I cannot find a simple solution on Internet.
I don't want to use Twisted Trial or tornado.testing but only Python
built-in unittest, is it possible ? I am developing an asynchronous
library by TDD, and I don't want to depend on Twisted or Tornado.
http://twistedmatrix.com/trac/wiki/TwistedTrial
http://www.tornadoweb.org/documentation/testing.html
Inspired by tornado.testing, I've implemented the following, which I
believe is not correct:
class TestMyAsync(unittest.TestCase):
def setUp(self):
self._stopped = False
def _wait(self, timeout):
if self._stopped: return True
t = 0
self._running = True
while self._running:
time.sleep(1)
if not self._running:
break
t += 1
if t == timeout:
return False
return True
def _stop(self):
self._stopped = True
self._running = False
def test_async_method(self):
def callback(ticket):
self.assertEqual(ticket, 998)
self._stop()
x = SomeAysncModules()
x.async_method(999, callback)
self.assertTrue(self._wait(3))
More information about the testing-in-python
mailing list