我在如何使用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")
它現在可以工作!
我說我的環境信息以及代碼示例中移動MainHandler這樣的路徑可以參考它 – Erds 2011-06-06 12:17:53
加我從尼克·約翰遜的回答 – Erds 2011-06-06 12:36:39