如何仅在内存中运行Django的测试数据库? [英] How to run Django's test database only in memory?
问题描述
由于我知道测试数据库总是很小,为什么我不能配置系统来始终保持整个测试数据库在RAM中?切勿碰到磁盘。如何在Django中进行配置?我宁愿继续使用 MySQL ,因为这是我在生产中使用的,但如果 SQLite 3或其他的东西使这很容易,我会这样走。
SQLite或MySQL有一个可以完全在内存中运行的选项吗?应该可以配置一个RAM磁盘,然后配置测试数据库来存储它的数据,但我不知道如何告诉Django / MySQL为某个数据库使用不同的数据目录,特别是因为它不断被擦除并重新创建每个运行。 (我在Mac FWIW上)
如果您在运行测试时将数据库引擎设置为sqlite3,一个href =http://docs.djangoproject.com/en/dev/ref/settings/#test-name =noreferrer> Django将使用内存数据库。
在我的 settings.py
中使用这样的代码在运行测试时将引擎设置为sqlite:
如果sys.argv中的'test':
DATABASE_ENGINE ='sqlite3'
或在Django 1.2中:
'in sys.argv:
DATABASES ['default'] = {'ENGINE':'sqlite3'}
最后在Django 1.3和1.4中:
如果sys.argv中的test:
DATABASES ['default'] = {'ENGINE':'django.db.backends.sqlite3'}
(Django 1.3的完整路径,后端并不是绝对必要的,而是使得这个集合)
您还可以添加以下行,以防您遇到南方迁移问题:
SOUTH_TESTS_MIGRATE = False
My Django unit tests take a long time to run, so I'm looking for ways to speed that up. I'm considering installing an SSD, but I know that has its downsides too. Of course, there are things I could do with my code, but I'm looking for a structural fix. Even running a single test is slow since the database needs to be rebuilt / south migrated every time. So here's my idea...
Since I know the test database will always be quite small, why can't I just configure the system to always keep the entire test database in RAM? Never touch the disk at all. How do I configure this in Django? I'd prefer to keep using MySQL since that's what I use in production, but if SQLite 3 or something else makes this easy, I'd go that way.
Does SQLite or MySQL have an option to run entirely in memory? It should be possible to configure a RAM disk and then configure the test database to store its data there, but I'm not sure how to tell Django / MySQL to use a different data directory for a certain database, especially since it keeps getting erased and recreated each run. (I'm on a Mac FWIW.)
If you set your database engine to sqlite3 when you run your tests, Django will use a in-memory database.
I'm using code like this in my settings.py
to set the engine to sqlite when running my tests:
if 'test' in sys.argv:
DATABASE_ENGINE = 'sqlite3'
Or in Django 1.2:
if 'test' in sys.argv:
DATABASES['default'] = {'ENGINE': 'sqlite3'}
And finally in Django 1.3 and 1.4:
if 'test' in sys.argv:
DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'}
(The full path to the backend isn't strictly necessary with Django 1.3, but makes the setting forward compatible.)
You can also add the following line, in case you are having problems with South migrations:
SOUTH_TESTS_MIGRATE = False
这篇关于如何仅在内存中运行Django的测试数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!