When running Unit tests for a tornado application i keep getting this error:
tornado.ioloop.TimeoutError: Operation timed out after 5 seconds
here's the test code:
class TestMongo(testing.AsyncTestCase):
def setUp(self):
super().setUp()
@patch('stashboard.checkers.events')
@testing.gen_test()
def test_check(self, event_mock,): # tests for Ok connection status
event_mock.STATUS_OK = events.STATUS_OK
event_mock.STATUS_FAIL = events.STATUS_FAIL
event_mock.save.return_value = Future()
d = {'path': '/test'}
test = MongoChecker(d, 1, None)
yield test.check()
event_mock.save.assert_called_with({'path': '/test'},
{'status': events.STATUS_OK,
'address': '#address#'})
and here's the code being tested:
class MongoChecker(Checker):
# pings Mongo servers noted in configuration to make sure
# they are still running
def __init__(self, event, frequency, params):
super().__init__(event, frequency, params)
self.clients = []
for server in configuration["mongodb"]:
host = server["host"]
port = server["port"]
address = 'mongodb://{}:{}'.format(host, port)
client = motor.motor_tornado.MotorClient(
address)
# creates client to test connection
client.address = address
self.clients.append(client)
@gen.coroutine
def check(self):
for client in self.clients:
try:
yield client.admin.command('ping')
data= {'address': client.address, 'status': events.STATUS_OK}
except ConnectionError:
data = {'address': client.address, 'status': events.STATUS_FAIL}
yield self.save(data)
This is the method that is actually called for the assertion:
@gen.coroutine
def save(self, data):
yield events.save(self.event, data)
When I remove the yield statement from yield self.save(data)
the test works fine. I need to mock a Future
object to return from self.save
and also get the actual results from that.
You have patched stashboard.checkers.events
and set Future
as return value, so the code:
@gen.coroutine
def save(self, data):
yield events.save(self.event, data)
become
@gen.coroutine
def save(self, data):
yield Future()
yield Future
means that Tornado will wait until the given future will be resolved, either by set_result
or by set_exception
. In the unit test for safety reasons (and sane) there is a time limit for the each test/suite. Since you haven't set the result, test would last forever, thankfully its timed out.
You could use tornado.gen.maybe_future
to set the result for coroutine. So the mock setup could look like:
@patch('stashboard.checkers.events')
@testing.gen_test()
def test_check(self, event_mock,): # tests for Ok connection status
event_mock.STATUS_OK = events.STATUS_OK
event_mock.STATUS_FAIL = events.STATUS_FAIL
event_mock.save.return_value = tornado.gen.maybe_future('some dummy ret')
# ...