mardi 28 juin 2016

Tornado Unittest mock yield statements

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.

Aucun commentaire:

Enregistrer un commentaire