Like mock ndb.get_context (). Urlfetch?

In my tests, I would like to mock the urlfetch

provided by the NDB package, so no real HTTP requests are made during the tests.


returns Future

, so I feel like I need to know the internals of the NDB in order to mock it properly ... Also I thought I could mock it somehow google.appengine.api.urlfetch.create_rpc()

... But I haven't made any progress far ...

How can i do this?



source to share

1 answer

I will answer my own question. In the code below, I am using the Michael Foord mock library.

import unittest
from google.appengine.ext import testbed, ndb
from mock import patch, Mock

class MyTestCase(unittest.TestCase):

    def setUp(self):
        self.testbed = testbed.Testbed()

        # mock urlrfetch service
        uf = self.testbed.get_stub('urlfetch')
        uf._Dynamic_Fetch = Mock()

    def test_make_request(self, URLFetchResponse):
        # mocking rpc response object
        response = URLFetchResponse.return_value
        response.contentwastruncated.return_value = False
        response.statuscode.return_value = 200
        response.content.return_value = 'Hello world!'        

        ctx = ndb.get_context()
        fut = ctx.urlfetch('')
        result = fut.get_result()

        self.assertEquals(result.content, 'Hello world!')

    def tearDown(self):




All Articles