我一直在尝试测试"从我的博客上阅读帖子"但看起来处理程序使用的数据存储区与测试使用的数据存储区不同。
这是测试:
def test_read_handler(self):
self.testbed.init_memcache_stub()
self.testbed.init_datastore_v3_stub()
self.testbed.init_user_stub()
data = {
'primary_title': 'Primary Post Title',
'secondary_title': 'Secondary Post Title',
'content': 'This is a sample'
}
new_post = models.Post(primary_title=data['primary_title'], secondary_title=data['secondary_title'],
content=data['content'])
key = new_post.put()
response = self.test_app.get('/read', {'id': key.id()})
self.assertEqual(response.status_int, 200)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(response.json, 'OK')
这是处理程序:
class ReadHandler(webapp2.RequestHandler):
def get(self):
post_id = self.request.get('id')
returned_post = models.Post.get_by_id(post_id)
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(returned_post.to_dict()))
这是我得到的错误:
test_read_handler (tests.BlogTest) ... ERROR:root:'NoneType' object has no attribute 'to_dict'
Traceback (most recent call last):
File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/vagrant/blog.py", line 28, in get
self.response.out.write(json.dumps(returned_post.to_dict()))
AttributeError: 'NoneType' object has no attribute 'to_dict'
知道我可能缺少什么?
答案 0 :(得分:1)
在你的处理程序中,你需要将你正在查找的id转换为int - 作为一个请求参数,它将被视为一个字符串:
class ReadHandler(webapp2.RequestHandler):
def get(self):
post_id = int(self.request.get('id'))
returned_post = models.Post.get_by_id(post_id)
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(returned_post.to_dict()))