Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing in tornado

I'm building a simple web application in tornado.web using mongodb as the backend. 90% of the server-side codebase lives in a set of RequestHandlers, and 90% of the data objects are json. As a result, the basic use case for testing handlers is:

"Given Request Y and DB in state X,
 verify that handler method Z returns json object J"

How do I set up this kind of test?

I've found a few blog posts and discussion threads on the topic, but they mainly focus on setting up asyncronous. I can't find anything on setting up the right kind of DB state or GET/POST request arguments.

  • http://emptysquare.net/blog/tornado-unittesting-eventually-correct/
  • http://www.tornadoweb.org/documentation/testing.html
  • https://groups.google.com/group/python-tornado/browse_thread/thread/867cfb2665ea10a9/319555e619fe6c5c
like image 525
Abe Avatar asked Jun 01 '12 15:06

Abe


1 Answers

I would typically mock out the inputs and just test the output. This is a contrived example using this mocking library - http://www.voidspace.org.uk/python/mock/. You would have to mock out the correct mongodb query function. I'm not sure what you are using.

from mock import Mock, patch
import json


@patch('my_tornado_server.mongo_db_connection.query')
def test_a_random_handler_returns_some_json(self, mock_mongo_query):

    request = Mock()
    # Set any other attributes on the request that you need
    mock_mongo_query.return_value = ['pink', 'orange', 'purple']

    application = Mock()
    handler = RandomHandler(application, request)
    handler.write = Mock()

    handler.get('some_arg')

    self.assertEqual(handler.write.call_args_list, json.dumps({'some': 'data'}))
like image 187
aychedee Avatar answered Nov 05 '22 05:11

aychedee