Search code examples
pythongoogle-app-engineunit-testingwebapp2

How do you unit test a file post with webapp2?


I am unit testing a webapp2 application and would like to write a test that simulates a file post. How can I create a request object in my unit test that contains the simulated contents of a file?

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)

Solution

  • Looks to me like the blank method includes a named POST parameter. It says in the docs http://webapp-improved.appspot.com/guide/testing.html#request-blank that by using it, the request method is automatically set to POST and the CONTENT_TYPE is set to ‘application/x-www-form-urlencoded’.

    So in the above it could just be:

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