unit-testing.rst 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. ================
  2. Unit Testing
  3. ================
  4. Testing with Django
  5. -------------------
  6. The problem that you'll first run in to when trying to write a test that runs a
  7. task is that Django's testrunner doesn't use the same database that 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 check
  10. on your tasks to get the return value or check the status.
  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 testrunner 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 testrunner does the
  18. trick. Celery provides a simple testrunner, 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 ``celery.contrib.test_runner`` to test the
  22. ``FeedImporter`` from the ``Writing Tasks`` example.
  23. To enable the testrunner, set the following settings:
  24. .. code-block:: python
  25. TEST_RUNNER = 'celery.contrib.test_runner.run_tests'
  26. Then we can write our actually test in a ``tests.py`` somewhere:
  27. .. code-block:: python
  28. from django.test import TestCase
  29. from feeds.tasks import FeedImporter
  30. class FeedImporterTestCase(TestCase):
  31. def testNoError(self):
  32. """
  33. Test that the ``FeedImporter`` task runs with no errors.
  34. """
  35. feed_url = 'http://github.com/feeds/ask/commits/celery/master'
  36. feed_importer = FeedImporter()
  37. task_result = feed_importer.delay(feed_url)
  38. self.assertEqual(task_result.status, 'DONE')
  39. self.assertEqual(task_result.result, feed_url)
  40. This test assumes that you put your example FeedImporter task in ``feeds.tasks``
  41. so of course adjust the import for wherever you actually put the class.