如何使用webapp2对文件帖子进行单元测试?

时间:2014-01-05 11:01:36

标签: python google-app-engine unit-testing webapp2

我正在对webapp2应用程序进行单元测试,并希望编写一个模拟文件帖子的测试。如何在单元测试中创建包含文件模拟内容的请求对象?

import unittest
import webapp2

import main

file_contents = """id, first, last
1, Bruce, Banner
2, Tony, Stark
"""

class TestHandlers(unittest.TestCase):
    def test_hello(self):

        request = webapp2.Request.blank('/')
        request.method = 'POST'

        # Magic needed here. 
        #Put file_contents into a form parameter

        response = request.get_response(main.app)
        #Test that the returned text contains something from the posted file
        self.assertEqual(True, "Bruce" in response.body)

1 个答案:

答案 0 :(得分:3)

在我看来,空白方法包含一个命名的POST参数。它在文档http://webapp-improved.appspot.com/guide/testing.html#request-blank中说,通过使用它,请求方法自动设置为POST,CONTENT_TYPE设置为'application / x-www-form-urlencoded'。

所以在上面它可能只是:

post_contents = {'someVar':file_contents}
request = webapp2.Request.blank('/', POST=post_contents)
response = request.get_response(main.app)