[TIP] Testing asynchronous method
Gary Bernhardt
gary.bernhardt at gmail.com
Tue Oct 18 19:06:41 PDT 2011
I almost wrote this reply when I saw the thread. I think you should
absolutely write a mocked version as you propose. But you also want a
few integration tests to at least notice if the magic smoke comes out,
so you're back to needing some kind of reactor. :)
--
Gary
http://destroyallsoftware.com
On Tue, Oct 18, 2011 at 6:44 PM, Herman Sheremetyev <herman at swebpage.com> wrote:
> Maybe I'm missing something, but why can't you just set up a mock or
> spy on the callback with any of the existing tools?
>
> Flexmock example:
>
> from flexmock import flexmock
>
> class TestMyAsync(unittest.TestCase):
> def test_async_method(self):
> x = SomeAsyncModules()
> flexmock(x).should_call('callback').once # will let the
> callback method run and just check that it did
> # -- or --
> # flexmock(x).should_receive('callback').once # will stub
> callback out but check that it was called
> x.async_method(999, x.callback)
>
> More details here:
>
> http://has207.github.com/flexmock/
>
> Flexmock has a number of facilities that let you make assertions about
> whether things have been done or not. Whether they're async or not
> shouldn't make a difference..
>
> -Herman
>
> On Wed, Oct 19, 2011 at 2:40 AM, Pere Martir <pere.martir4 at gmail.com> wrote:
>> 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))
>>
>> _______________________________________________
>> testing-in-python mailing list
>> testing-in-python at lists.idyll.org
>> http://lists.idyll.org/listinfo/testing-in-python
>>
>
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python
>
More information about the testing-in-python
mailing list