Skip to main content

Venkatraman Dhamodaran

Venkatraman Dhamodaran's Public Library

  • The most straightforward way of creating a fixture is to use the dumpdata command. This assumes you already have some data in your database. See the dumpdata documentation for more details.
  • Once you’ve created a fixture and placed it in a fixtures directory in one of your INSTALLED_APPS, you can use it in your unit tests by specifying a fixtures class attribute on your django.test.TestCase subclass:
    • Here’s specifically what will happen:

      • At the start of each test case, before setUp() is run, Django will flush the database, returning the database to the state it was in directly after migrate was called.
      • Then, all the named fixtures are installed. In this example, Django will install any JSON fixture named mammals, followed by any fixture named birds. See the loaddata documentation for more details on defining and installing fixtures.

  • Finally, you’ll need to remember to create user accounts before you can use this method. As we explained above, the test runner is executed using a test database, which contains no users by default. As a result, user accounts that are valid on your production site will not work under test conditions. You’ll need to create users as part of the test suite – either manually (using the Django model API) or with a test fixture. Remember that if you want your test user to have a password, you can’t set the user’s password by setting the password attribute directly – you must use the set_password() function to store a correctly hashed password. Alternatively, you can use the create_user() helper method to create a new user with a correctly hashed password.

  • If your tests rely on database access such as creating or querying models, be sure to create your test classes as subclasses of django.test.TestCase rather than unittest.TestCase.
  • Using unittest.TestCase avoids the cost of running each test in a transaction and flushing the database
  • his will discover tests in any file named “test*.py” under the current working directory.
1 - 20 of 1348 Next › Last »
20 items/page

Diigo is about better ways to research, share and collaborate on information. Learn more »

Join Diigo