usage.rst 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. Usage
  2. =====
  3. The day-to-day use of django-nose is mostly transparent; just run ``./manage.py
  4. test`` as usual.
  5. See ``./manage.py help test`` for all the options nose provides, and look to
  6. the `nose docs`_ for more help with nose.
  7. .. _nose docs: https://nose.readthedocs.io/en/latest/
  8. Enabling Database Reuse
  9. -----------------------
  10. .. warning:: There are several
  11. `open issues <https://github.com/django-nose/django-nose/milestones/Fix%20REUSE_DB=1>`_
  12. with this feature, including
  13. `reports of data loss <https://github.com/django-nose/django-nose/issues/76>`_.
  14. You can save several seconds at the beginning and end of your test suite by
  15. reusing the test database from the last run. To do this, set the environment
  16. variable ``REUSE_DB`` to 1::
  17. REUSE_DB=1 ./manage.py test
  18. The one new wrinkle is that, whenever your DB schema changes, you should leave
  19. the flag off the next time you run tests. This will cue the test runner to
  20. reinitialize the test database.
  21. Also, REUSE_DB is not compatible with TransactionTestCases that leave junk in
  22. the DB, so be sure to make your TransactionTestCases hygienic (see below) if
  23. you want to use it.
  24. Enabling Fast Fixtures
  25. ----------------------
  26. .. warning:: There are several
  27. `known issues <https://github.com/django-nose/django-nose/milestones/Fix%20FastFixtureTestCase>`_
  28. with this feature.
  29. django-nose includes a fixture bundler which drastically speeds up your tests
  30. by eliminating redundant setup of Django test fixtures. To use it...
  31. 1. Subclass ``django_nose.FastFixtureTestCase`` instead of
  32. ``django.test.TestCase``. (I like to import it ``as TestCase`` in my
  33. project's ``tests/__init__.py`` and then import it from there into my actual
  34. tests. Then it's easy to sub the base class in and out.) This alone will
  35. cause fixtures to load once per class rather than once per test.
  36. 2. Activate fixture bundling by passing the ``--with-fixture-bundling`` option
  37. to ``./manage.py test``. This loads each unique set of fixtures only once,
  38. even across class, module, and app boundaries.
  39. How Fixture Bundling Works
  40. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  41. The fixture bundler reorders your test classes so that ones with identical sets
  42. of fixtures run adjacently. It then advises the first of each series to load
  43. the fixtures once for all of them (and the remaining ones not to bother). It
  44. also advises the last to tear them down. Depending on the size and repetition
  45. of your fixtures, you can expect a 25% to 50% speed increase.
  46. Incidentally, the author prefers to avoid Django fixtures, as they encourage
  47. irrelevant coupling between tests and make tests harder to comprehend and
  48. modify. For future tests, it is better to use the "model maker" pattern,
  49. creating DB objects programmatically. This way, tests avoid setup they don't
  50. need, and there is a clearer tie between a test and the exact state it
  51. requires. The fixture bundler is intended to make existing tests, which have
  52. already committed to fixtures, more tolerable.
  53. Troubleshooting
  54. ~~~~~~~~~~~~~~~
  55. If using ``--with-fixture-bundling`` causes test failures, it likely indicates
  56. an order dependency between some of your tests. Here are the most frequent
  57. sources of state leakage we have encountered:
  58. * Locale activation, which is maintained in a threadlocal variable. Be sure to
  59. reset your locale selection between tests.
  60. * memcached contents. Be sure to flush between tests. Many test superclasses do
  61. this automatically.
  62. It's also possible that you have ``post_save`` signal handlers which create
  63. additional database rows while loading the fixtures. ``FastFixtureTestCase``
  64. isn't yet smart enough to notice this and clean up after it, so you'll have to
  65. go back to plain old ``TestCase`` for now.
  66. Exempting A Class From Bundling
  67. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  68. In some unusual cases, it is desirable to exempt a test class from fixture
  69. bundling, forcing it to set up and tear down its fixtures at the class
  70. boundaries. For example, we might have a ``TestCase`` subclass which sets up
  71. some state outside the DB in ``setUpClass`` and tears it down in
  72. ``tearDownClass``, and it might not be possible to adapt those routines to heed
  73. the advice of the fixture bundler. In such a case, simply set the
  74. ``exempt_from_fixture_bundling`` attribute of the test class to ``True``.
  75. Speedy Hygienic TransactionTestCases
  76. ------------------------------------
  77. Unlike the stock Django test runner, django-nose lets you write custom
  78. TransactionTestCase subclasses which expect to start with an unmarred DB,
  79. saving an entire DB flush per test.
  80. Background
  81. ~~~~~~~~~~
  82. The default Django TransactionTestCase class `can leave the DB in an unclean
  83. state`_ when it's done. To compensate, TransactionTestCase does a
  84. time-consuming flush of the DB *before* each test to ensure it begins with a
  85. clean slate. Django's stock test runner then runs TransactionTestCases last so
  86. they don't wreck the environment for better-behaved tests. django-nose
  87. replicates this behavior.
  88. Escaping the Grime
  89. ~~~~~~~~~~~~~~~~~~
  90. Some people, however, have made subclasses of TransactionTestCase that clean up
  91. after themselves (and can do so efficiently, since they know what they've
  92. changed). Like TestCase, these may assume they start with a clean DB. However,
  93. any TransactionTestCases that run before them and leave a mess could cause them
  94. to fail spuriously.
  95. django-nose offers to fix this. If you include a special attribute on your
  96. well-behaved TransactionTestCase... ::
  97. class MyNiceTestCase(TransactionTestCase):
  98. cleans_up_after_itself = True
  99. ...django-nose will run it before any of those nasty, trash-spewing test cases.
  100. You can thus enjoy a big speed boost any time you make a TransactionTestCase
  101. clean up after itself: skipping a whole DB flush before every test. With a
  102. large schema, this can save minutes of IO.
  103. django-nose's own FastFixtureTestCase uses this feature, even though it
  104. ultimately acts more like a TestCase than a TransactionTestCase.
  105. .. _can leave the DB in an unclean state: https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.TransactionTestCase
  106. Test-Only Models
  107. ----------------
  108. If you have a model that is used only by tests (for example, to test an
  109. abstract model base class), you can put it in any file that's imported in the
  110. course of loading tests. For example, if the tests that need it are in
  111. ``test_models.py``, you can put the model in there, too. django-nose will make
  112. sure its DB table gets created.
  113. Assertions
  114. ----------
  115. ``django-nose.tools`` provides pep8 versions of Django's TestCase asserts
  116. and some of its own as functions. ::
  117. assert_redirects(response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix='')
  118. assert_contains(response, text, count=None, status_code=200, msg_prefix='')
  119. assert_not_contains(response, text, count=None, status_code=200, msg_prefix='')
  120. assert_form_error(response, form, field, errors, msg_prefix='')
  121. assert_template_used(response, template_name, msg_prefix='')
  122. assert_template_not_used(response, template_name, msg_prefix='')
  123. assert_queryset_equal(qs, values, transform=repr)
  124. assert_num_queries(num, func=None, *args, **kwargs)
  125. assert_code(response, status_code, msg_prefix='')
  126. assert_ok(response, msg_prefix='')
  127. assert_mail_count(count, msg=None)
  128. Always Passing The Same Options
  129. -------------------------------
  130. To always set the same command line options you can use a `nose.cfg or
  131. setup.cfg`_ (as usual) or you can specify them in settings.py like this::
  132. NOSE_ARGS = ['--failed', '--stop']
  133. .. _nose.cfg or setup.cfg: https://nose.readthedocs.io/en/latest/usage.html#configuration
  134. Custom Plugins
  135. --------------
  136. If you need to `make custom plugins`_, you can define each plugin class
  137. somewhere within your app and load them from settings.py like this::
  138. NOSE_PLUGINS = [
  139. 'yourapp.tests.plugins.SystematicDysfunctioner',
  140. # ...
  141. ]
  142. Just like middleware or anything else, each string must be a dot-separated,
  143. importable path to an actual class. Each plugin class will be instantiated and
  144. added to the Nose test runner.
  145. .. _make custom plugins: https://nose.readthedocs.io/en/latest/plugins.html#writing-plugins