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.
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'}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With