Faster Testing with RAM Drives

➫ sudo chown -R postgres /media/pg_ram_drive/ ➫ sudo -u postgres psql postgres=# CREATE DATABASE django; postgres=# CREATE TABLESPACE ram_disk LOCATION '/media/pg_ram_drive'; postgres=# CREATE USER django WITH SUPERUSER PASSWORD 'django'; There should be a folder on the RAM drive now with a PG_ prefix that looks something like the following: ➫ sudo find /media/pg_ram_drive /media/pg_ram_drive /media/pg_ram_drive/PG_9.4_201409291 # This folder should be empty Testing a Django project on the RAM drive Ill install all the packages needed to test an example Django project: ➫ sudo apt-get install python-virtualenv python-pip python-dev git-core In a previous blog post I created a project where a Django model is tested, Ill run these tests on the RAM drive..➫ git clone https://github.com/marklit/meetup-testing.git ➫ virtualenv venv ➫ source venv/bin/activate ➫ pip install -r meetup-testing/requirements.txt ➫ pip install psycopg2 ➫ cd meetup-testing This code base has a convention that settings that need to be overridden are done so in a base/local_settings.py file which is not kept in the git repo..In this file Ill set both the regular and test database settings..The most important setting is the DEFAULT_TABLESPACE attribute which should be the name of the RAM disk tablespace that was created in PostgreSQL..➫ vi base/local_settings.py import sys DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'localhost', 'PORT': 5432, 'NAME': 'django', 'USER': 'django', 'PASSWORD': 'django', 'TEST': { 'NAME': 'django_test', }, }, } if 'test' in sys.argv: DEFAULT_TABLESPACE = 'ram_disk' SECRET_KEY = 'a' * 21 Now when the tests run theyre using the RAM drive..➫ python manage.py test Creating test database for alias 'default'….———————————————————————- Ran 1 test in 0.027s OK Destroying test database for alias 'default'….This code base only has one test but on projects with a lot of tests there should be a significant decrease in the amount of time it takes to run the test suite..Make the RAM drive permanent To make sure the RAM drive is available if the system restarts add the following line to your /etc/fstab file: tmpfs /media/pg_ram_drive tmpfs defaults,noatime,mode=1777 0 0 After a reboot the drive will be mounted and empty..When you run Djangos test runner itll create a test database from scratch on the drive again..➫ sudo reboot ….➫ python manage.py test Creating test database for alias 'default'…. More details

Leave a Reply