A way to load custom SQL fixture for test database

Hello.

How do you load custom database SQL for test in Django?

I’m looking at the problem from the point of pytest-django, but it starts from Django itself, so I think it’s better to start discussion here.

There’s some open issues in pytest-django repo, and some ideas in the docs:

But, I’d really like to have some level of support for this in Django itself.


For now, I drafted a solution with subclassing DatabaseCreation and overriding _create_test_db method, but it’s using protected methods, and I’d like to avoid that in the future.

Maybe Django should make create_test_db public method? Or maybe add a signal like test_db_created, so we can load fixtures when needed.

Or, maybe we should add a setting like “INIT_SCRIPT": "dev/test.sq", in the ”TEST” section, and each database backend can load it during db creation. But there’s a lot to consider here:

I tried using cursor.execute()to load this SQL at first, but turns out mysqldump generates a lot of comments like /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; and they seems to be intended for loading with mysql < directly. mysqlclient handles this fine, but pymysql cannot load this dump. So I ended up using subprocess.run(("mysql", ...))

Is there a point in implementing generic solution on Django level? What do you think? How do you solve this problem in your projects?

One of the techniques I use is to keep an “empty” database as a PostgreSQL template database. I then create a test database using that empty model as the template. (I typically do this with databases having a significant amount of “preloaded” data.)