GAE: unit testing taskqueue with testbed

后端 未结 4 1741
醉梦人生
醉梦人生 2020-12-24 14:36

I\'m using testbed to unit test my google app engine app, and my app uses a taskqueue.

When I submit a task to a taskqueue during a unit test, it appears that the ta

4条回答
  •  孤独总比滥情好
    2020-12-24 14:52

    The dev app server is single-threaded, so it can't run tasks in the background while the foreground thread is running the tests.

    I modified TaskQueueTestCase in taskqueue.py in gaetestbed to add the following function:

    def execute_tasks(self, application):
        """
        Executes all currently queued tasks, and also removes them from the 
        queue.
        The tasks are execute against the provided web application.
        """
    
        # Set up the application for webtest to use (resetting _app in case a
        # different one has been used before). 
        self._app = None
        self.APPLICATION = application
    
        # Get all of the tasks, and then clear them.
        tasks = self.get_tasks()
        self.clear_task_queue()
    
        # Run each of the tasks, checking that they succeeded.
        for task in tasks:
            response = self.post(task['url'], task['params'])
            self.assertOK(response)
    

    For this to work, I also had to change the base class of TaskQueueTestCase from BaseTestCase to WebTestCase.

    My tests then do something like this:

    # Do something which enqueues a task.
    
    # Check that a task was enqueued, then execute it.
    self.assertTrue(len(self.get_tasks()), 1)
    self.execute_tasks(some_module.application)
    
    # Now test that the task did what was expected.
    

    This therefore executes the task directly from the foreground unit test. This is not quite the same as in production (ie, the task will get executed 'some time later' on a separate request), but it works well enough for me.

提交回复
热议问题