[Answered ]-How to init database for testcase in django

2๐Ÿ‘

โœ…

If your tests all use the same data, you can pre-populate the TestCase using fixtures (i.e. a bunch of โ€˜fakeโ€™ database entries you use for testing). Have a look at the Django testing docs on
Providing initial data for models and the Test Case documentation.

Basically, what you have is a JSON/XML/YAML file in your app with initial data for testing:

[
  {
    "model": "app.somemodel",
    "pk": 1,
    "fields": {
      "somefield": 'data',
      "otherfield": 'otherdata',
    }
  },
  # more test model instances to follow.
]

If you are using JSON a(s in the above example) and name the file initial_data.json it will be automatically loaded every time you run your tests. Otherwise, to specify which fixtures to load for a specific TestCase, name the file: special_data.json and tell the TestCase to load it:

class MyTest(TestCase):
    fixtures = ['special_data',]

    def test1:
        do something
    # etc

Hope this helps!

I should also mention that although fixtures are a great and easy way to provide initial data for testing purposes, they have some drawbacks. You might wint to have a look at ModelFactores and why Carl Meyer thinks you should be using them.

๐Ÿ‘คMarc Gouw

Leave a comment