Atom Login Admin

Seeds of mention

Unit Testing with Google App Engine URLFetch
mentioned on Monday,January 14,2013

This time, introduce Tips for developing an application in Google App Engine.

Gets the content of external communication using urlfetch service in GAE Python
Sometimes want to use static resouce in unit testing,(such data obtained using the communication, To avoid to fail the test by data changed or disconnected),
Using local response (such as a file) without actual communicating.
Google App Engine have RPC various services.
In the development environment, the processing to perform the actual communication using the RPC stub that hook Going.
This time to change the implementation of the stub, and then return to assemble your own response.

class URLFetchServiceMock(apiproxy_stub.APIProxyStub):
  """Mock for google.appengine.api.urlfetch."""
  def __init__(self, service_name="urlfetch"):
    super(URLFetchServiceMock, self).__init__(service_name)

  def set_return_values(self, return_value):
    self.return_values = return_value

  def _Dynamic_Fetch(self, request, response):
    return_values = self.return_values
    response.set_content(return_values.get("content", ""))
    response.set_statuscode(return_values.get("status_code", 200))

    for header_key, header_value in return_values.get("headers", {}).items():
      new_header = response.add_header()

    response.set_finalurl(return_values.get("final_url", request.url))

    self.request = request
    self.response = response

class FetchTestBase(unittest.TestCase):
  """Base class for fetcher."""

  def setUp(self):
    # Regist API Proxy
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    # Regist urlfetch stub
    self._urlfetch_mock = URLFetchServiceMock()

  def setReturnValue(self, **kwargs):
    """ set the return value."""

  def tearDown(self):
class UrlFetcheTest(testutil.FetchTestBase):
  """ test urlfetch for local """

  def testFetch(self):
    self.setReturnValues(content="some content")
    result = urlfetch.fetch(url="")
    self.assertEquals(200, result.status_code)
    self.assertEquals("some content", result.content)

Was created as a base class so that turning your work in the test.
First, set the stub that implements various services on its own, apiproxy_stub_map.
So urlfetch, this time with "urlfetch" service name.
The stub class method called _Dynamic_Fetch set has been implemented,
Dynamic calls APIProxyStub #MakeSyncCall used RPC is executed
It is a method that has been done.
Override this method to return it assembled its own response.
What if you want to test using a mock in this way, also the service
Applied You should work. Have tried.:)


Add Comment

This entry was tagged #GAE #Tips