Search code examples
djangodjango-tests

how to init database for testcase in django


In the testcase, there are many test functions and all the test functions use the same data.

class Mytest(TestCase):
    def init_data(self):
        insert data1
        insert data2
        .....
    def test1:
        do something
    def test2:
        do something
    ....

where should I call the init_data function. If I call the function in all the test functions, it will insert data many times and it will influence result. And i think i can call the init_data in the first test function. But when I write many test function, I find the first test function the djang call is not the first test function i write. So how should i call the init_data() function or Is there other method to do this. thanks in advance


Solution

  • 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.