2011-06-03 45 views
5

我在如何使用Google App Engine-Python设置TDD环境方面很努力。 (我对Python也很新颖)。我的环境如下:单元测试GAE中的webapp.RequestHandler - Python

  • 谷歌App Engine的1.5.0
  • 的IntelliJ 10.2
  • 的IntelliJ设置使用Python 2.5.4本项目

我使用的IntelliJ使用Python插件,所以运行unittests就像点击ctrl-shft-f10一样简单。

我也读过了关于测试平台的文档,并成功测试了数据存储和内存缓存。但是,我卡住的地方是我如何单元测试我的RequestHandlers。我在Google上扫描了很多文章,其中大部分似乎都是以gae作为测试平台的合并版本。

在下面的代码示例中,我想知道如何写一个单元测试(这是在的IntelliJ可运行),其测试,要“/”返回一个呼叫 - >主页

from google.appengine.ext import webapp 
import wsgiref.handlers 

class MainHandler(webapp.RequestHandler): 

    def get(self): 
     self.response.out.write('Home Page') 

paths = [ 
      ('/', MainHandler) 
     ] 

application = webapp.WSGIApplication(paths, debug=True) 

def main(): 
    wsgiref.handlers.CGIHandler().run(application) 

if __name__ == '__main__': 
    main() 

从Nick Johnson的回答如下,我添加了一个名为test的新文件夹,并将一个文件添加到名为unit_test.py的文件夹中。对于该文件,我添加了下面的代码(修改自Kris的答案):

from StringIO import StringIO 
from main import MainHandler 
import unittest 
from google.appengine.ext import webapp 

class MyTestCase(unittest.TestCase): 
    def test_get(self): 
     request = webapp.Request({ 
      "wsgi.input": StringIO(), 
      "CONTENT_LENGTH": 0, 
      "METHOD": "GET", 
          "PATH_INFO": "/", 
     }) 
     response = webapp.Response() 
     handler = MainHandler() 
     handler.initialize(request, response) 
     handler.get() 
     self.assertEqual(response.out.getvalue(), "Home Page") 

它现在可以工作!

+0

我说我的环境信息以及代码示例中移动MainHandler这样的路径可以参考它 – Erds 2011-06-06 12:17:53

+0

加我从尼克·约翰逊的回答 – Erds 2011-06-06 12:36:39

回答

3

我发现我所需要的尼克·约翰逊的代码稍加修改的版本:

request = webapp.Request({ 
    "wsgi.input": StringIO.StringIO(), 
    "CONTENT_LENGTH": 0, 
    "METHOD": "GET", 
    "PATH_INFO": "/", 
}) 
response = webapp.Response() 
handler = MainHandler() 
handler.initialize(request, response) 
handler.get() 
self.assertEqual(response.out.getvalue(), "Home Page") 
+0

这样做了,谢谢! – Erds 2011-08-24 11:56:23

1

做到这一点,最简单的方法是实例化处理程序,并把它传递请求和响应对象,然后断言的结果:

request = webapp.Request({ 
    "wsgi.input": StringIO.StringIO(), 
    "CONTENT_LENGTH": 0, 
    "METHOD": "GET", 
}) 
request.path = '/' 
response = webapp.Response() 
handler = MainHandler() 
handler.initialize(request, response) 
handler.get() 
self.assertEqual(response.body, "Home Page") 
+0

酷使用的代码,我给一个去一次我下班回家! – Erds 2011-06-03 11:53:44

+0

我添加了你的代码,我尝试了上面的问题。我在'request.path'行收到一个错误。我得到'AttributeError:无法设置属性' – Erds 2011-06-06 12:39:45