Django Unified Testing with Instrument Loading for Multiple Dependent Applications

Now I am doing unit tests for existing code. I ran into the following problem:

After running syncdb to create a test database, Django automatically populates several tables, such as django_content_type or auth_permissions.

Then imagine that I need to perform a complex test, for example, check user registration, which will require a table of data and the relationships between them.

If I try to use my entire existing database to create fixtures (this would be quite convenient for me) - I will get an error, for example here . This is because Django has already populated tables like django_content_type.

The next possible way is to use the django dumpdata --exclude option for syncdb tables already populated. But this is also not very good, because if I take the User and User Group objects from the db and User Permissions table, which was automatically created by syncdb, I can get errors, because the primary keys connecting them now indicate incorrectly. This is better described here in the fixture hell part, but the solution shown there doesn't look good)

The next possible diagram that I see is as follows:

  • I am doing my tests; Django creates a test database, creates syncdb, and creates all of these tables.
  • In my test setup, I delete this database by creating a new empty database.
  • Loading a data dump from an existing database into test setup as well
+1
source share
2 answers

How the problem was resolved:

After syncdb created the test database, in the partUp part of the tests, I use os.system to access the shell from my code. Then I just load the database dump that I want to use for tests.

So this works as follows: syncdb populates the contenttype and some other tables with data. Then, in the setUp part of the tests, loading the sql dump clears all previously created data, and I get a good database.

Maybe this is not the best solution, but it works =)

0
source

My approach was to first use the South to facilitate database transfer (which doesn't help at all, but good), and then use the module for creating the model methods.

At startup

  $ manage.py test my_proj 

Django with the south installed with the test database creation and run all your migrations to give you a completely updated db test.

To write tests, first create a python calle module, test_model_factory.py. Here, create functions that create your objects.

 def mk_user(): User.objects.create(...) 

Then, in your tests, you can import your test_model_factory module and create objects for each test.

  def test_something(self): test_user = test_model_factory.mk_user() self.assert(test_user ...) 
0
source

Source: https://habr.com/ru/post/952265/


All Articles