unit-testing.rst 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. ================
  2. Unit Testing
  3. ================
  4. Testing with Django
  5. -------------------
  6. The first problem you'll run in to when trying to write a test that runs a
  7. task is that Django's test runner doesn't use the same database as your celery
  8. daemon is using. If you're using the database backend, this means that your
  9. tombstones won't show up in your test database and you won't be able to
  10. get the return value or check the status of your tasks.
  11. There are two ways to get around this. You can either take advantage of
  12. ``CELERY_ALWAYS_EAGER = True`` to skip the daemon, or you can avoid testing
  13. anything that needs to check the status or result of a task.
  14. Using a custom test runner to test with celery
  15. ----------------------------------------------
  16. If you're going the ``CELERY_ALWAYS_EAGER`` route, which is probably better than
  17. just never testing some parts of your app, a custom Django test runner does the
  18. trick. Celery provides a simple test runner, but it's easy enough to roll your
  19. own if you have other things that need to be done.
  20. http://docs.djangoproject.com/en/dev/topics/testing/#defining-a-test-runner
  21. For this example, we'll use the ``djcelery.contrib.test_runner`` to test the
  22. ``add`` task from the :ref:`guide-task` examples in the Celery
  23. documentation.
  24. To enable the test runner, set the following settings:
  25. .. code-block:: python
  26. TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'
  27. Then we can put the tests in a ``tests.py`` somewhere:
  28. .. code-block:: python
  29. from django.test import TestCase
  30. from myapp.tasks import add
  31. class AddTestCase(TestCase):
  32. def testNoError(self):
  33. """Test that the ``add`` task runs with no errors,
  34. and returns the correct result."""
  35. result = add.delay(8, 8)
  36. self.assertEquals(result.get(), 16)
  37. self.assertTrue(result.successful())
  38. This test assumes that you put your example ``add`` task in ``maypp.tasks``
  39. so adjust the import for wherever you put the class.