Reputation: 231
I'm testing the MainHandler using the code below.
import tornado.httpserver
import tornado.httpclient
import tornado.ioloop
import tornado.web
import unittest
class MainHandler(tornado.web.RequestHandler):
def get(self):
kwargs = {'name' : 'world'}
self.render('template.html', **kwargs)
class TestTornadoWeb(unittest.TestCase):
http_server = None response = None
def setUp(self):
application = tornado.web.Application([
(r'/', MainHandler),
])
self.http_server = tornado.httpserver.HTTPServer(application)
self.http_server.listen(8888)
def tearDown(self):
self.http_server.stop()
def handle_request(self, response):
self.response = response
tornado.ioloop.IOLoop.instance().stop()
def testHelloWorldHandler(self):
http_client = tornado.httpclient.AsyncHTTPClient()
http_client.fetch('http://localhost:8888/', self.handle_request)
tornado.ioloop.IOLoop.instance().start()
self.failIf(self.response.error)
self.assertEqual(self.response.body, 'Hello, world')
if __name__ == '__main__':
unittest.main()
The template.html:
Hello, {{name}}
I wanna test the template and its variables.
How I can test if name was received correctly?
There's some attribute that I can use to do the asserts or this should be done another way?
Upvotes: 0
Views: 645
Reputation: 922
That's essentially what you're already doing in your assertion. Since the client instance is pulling the rendered template, you can't match the template variable. By using your kwargs in the template, it's rendering those kwargs into the template - where {{name}} is 'world' (the expected output), your template variable has been received and rendered.
If you need to test specific output, a fairly inelegant solution could be to assign each variable a meaningless <div>
tag (i.e., <div name="name">{{name}}</div>
) and then use the assertIn
method (i.e., self.assertIn(self.response.body, '<div name="name">world</div>')
) to test for the correct output.
Upvotes: 1