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 task is in the queue, but the task does not execute.
How do I get the task to execute during a unit test?
The main objective of unit testing is to isolate written code to test and determine if it works as intended. Unit testing is an important step in the development process, because if done correctly, it can help detect early flaws in code which may be more difficult to find in later testing stages.
unittest has been built into the Python standard library since version 2.1. You'll probably see it in commercial Python applications and open-source projects. unittest contains both a testing framework and a test runner. unittest has some important requirements for writing and executing tests.
unittest provides a base class, TestCase , which may be used to create new test cases. test suite. A test suite is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together. test runner.
Using Saxon's excellent answer, I was able to do the same thing using testbed instead of gaetestbed. Here is what I did.
Added this to my setUp()
:
self.taskqueue_stub = apiproxy_stub_map.apiproxy.GetStub('taskqueue')
Then, in my test, I used the following:
# Execute the task in the taskqueue
tasks = self.taskqueue_stub.GetTasks("default")
self.assertEqual(len(tasks), 1)
task = tasks[0]
params = base64.b64decode(task["body"])
response = self.app.post(task["url"], params)
Somewhere along the line, the POST parameters get base64 encoded so had to undo that to get it to work.
I like this better than Saxon's answer since I can use the official testbed package and I can do it all within my own test code.
EDIT: I later wanted to do the same thing with tasks submitted using the deferred library, and it took a bit of headbanging to figure it, so I'm sharing here to ease other people's pain.
If your taskqueue contains only tasks submitted with deferred, then this will run all of the tasks and any tasks queued by those tasks:
def submit_deferred(taskq):
tasks = taskq.GetTasks("default")
taskq.FlushQueue("default")
while tasks:
for task in tasks:
(func, args, opts) = pickle.loads(base64.b64decode(task["body"]))
func(*args)
tasks = taskq.GetTasks("default")
taskq.FlushQueue("default")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With