我正在尝试测试我的webapp2处理程序。为了做到这一点,我认为向处理程序发送请求是一个好主意,例如:
request = webapp2.Request.blank('/')
# Get a response for that request.
response = request.get_response(main.app)
问题在于响应中大多数是一堆HTML代码等等。
我想查看从处理程序传递给jinja2模板之前的内容。
我希望我的测试可以访问处理程序类代码中的状态。我想要查看响应处理程序中某些变量的值,然后我想要查看传递给render_to_response()之前字典模板的样子。
我想测试这些变量是否具有正确的值。
这是目前我的测试代码,但我卡住了,因为response = request.get_response()只会给我一堆HTML而不是原始变量。import unittest
import main
import webapp2
class DemoTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testNothing(self):
self.assertEqual(42, 21 + 21)
def testHomeHandler(self):
# Build a request object passing the URI path to be tested.
# You can also pass headers, query arguments etc.
request = webapp2.Request.blank('/')
# Get a response for that request.
response = request.get_response(main.app)
# Let's check if the response is correct.
self.assertEqual(response.status_int, 200)
self.assertEqual(response.body, 'Hello, world!')
if __name__ == '__main__':
unittest.main()
这是我的处理程序:
class HomeHandler(BaseHandler):
def get(self, file_name_filter=None, category_filter=None):
file_names = os.listdir('blog_posts')
blogs = []
get_line = lambda file_: file_.readline().strip().replace("<!--","").replace("-->","")
for fn in file_names:
with open('blog_posts/%s' % fn) as file_:
heading = get_line(file_)
link_name = get_line(file_)
category = get_line(file_)
date_ = datetime.strptime(fn.split("_")[0], "%Y%m%d")
blog_dict = {'date': date_, 'heading': heading,
'link_name': link_name,
'category': category,
'filename': fn.replace(".html", ""),
'raw_file_name': fn}
blogs.append(blog_dict)
categories = Counter(d['category'] for d in blogs)
templates = {'categories': categories,
'blogs': blogs,
'file_name_filter': file_name_filter,
'category_filter': category_filter}
assert(len(file_names) == len(set(d['link_name'] for d in blogs)))
self.render_template('home.html', **templates)
这是我的基础处理程序:
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **kwargs):
#kwargs.update({})
#TODO() datastore caching here for caching of (handlername, handler parameters, changeable parameters, app_upload_date)
#TODO() write rendered page to its own html file, and just serve that whole file. (includes all posts). JQuery can show/hide posts.
self.response.write(self.jinja2.render_template(filename, **kwargs))
也许我对如何进行单元测试的理解有误,或者我应该以更易于测试的方式编写代码?还是有一些方法可以获取我的代码状态呢?
此外,如果有人重新编写代码并更改变量名称,则测试将失败。