DEV Community

Reishi Mitani
Reishi Mitani

Posted on

Testing in a Docker + MySQL + Django Environment

First, add the database for testing by adding the following to your local settings.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DB',
        'USER': 'DB_USER',
        'PASSWORD': 'password',
        'HOST': '172.20.0.3',
        'PORT': '3306',
        # ADD BELOW!
        'TEST': {
            'NAME': 'test_database',
        },
    }
}
Enter fullscreen mode Exit fullscreen mode

Then go to your mysql docker container. Inside the container, access mysql, and type in the GRANT ALL... command. Make sure to change the DB_USER according to the user name of your database.

$ docker exec -it CONTAINER_NAME_MYSQL /bin/bash
# mysql -u root -p

> GRANT ALL PRIVILEGES ON test_database.* TO 'DB_USER'@'%';
Query OK, 0 rows affected (0.01 sec)
Enter fullscreen mode Exit fullscreen mode

You are ready to test now!
Enter your django container, and run the tests.

Here is a sample of my test code in my app folder.

from django.test import TestCase

# Create your tests here.
class EqualTests(TestCase):

    def test_1_equals_1(self):
        self.assertIs(1, 1)

    def test_1_equals_to_0(self):
        self.assertIs(1, 0)
Enter fullscreen mode Exit fullscreen mode

Open up your django container, and run your tests in the directory where manage.py and app are placed. You may need to change the directory names if these two have different locations.

docker exec -it CONTAINER_NAME_DJANGO /bin/bash
# python manage.py test app
Enter fullscreen mode Exit fullscreen mode

You should get an error similar to this.

.F
======================================================================
FAIL: test_1_equals_to_0 (app.tests.EqualTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/code/project/app/tests.py", line 10, in test_1_equals_to_0
    self.assertIs(1, 0)
AssertionError: 1 is not 0

----------------------------------------------------------------------
Ran 2 tests in 0.022s

FAILED (failures=1)
Destroying test database for alias 'default'...

Enter fullscreen mode Exit fullscreen mode

Hope this helps!

Top comments (0)