I have a simple Django project with a PostgreSQL backend:
version: '3'
services:
db:
image: postgres:12
ports:
- '5432:5432'
volumes:
- postgres_data:/var/lib/postgresql/data/
environment:
POSTGRES_USER: pycharm
POSTGRES_PASSWORD: pw123
POSTGRES_DB: pycharm
app:
build: .
command: python manage.py runserver 0.0.0.0:8000
ports:
- '8000:8000'
volumes:
- .:/app
depends_on:
- db
volumes:
postgres_data:
With the following database settings in settings.py
:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "pycharm",
"USER": "pycharm",
"PASSWORD": "pw123",
"HOST": "db",
}
}
And a simple test:
from django.test import TestCase
class MyTestCase(TestCase):
def test_example(self):
assert 1 == 1
Everything works fine when I run the project with docker-compose:
docker-compose up
I can exec into the container running the django app and successfully execute the test:
docker-compose run app bash
$ python manage.py test demo.tests.MyTestCase
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
Destroying test database for alias 'default'...
I want to run the test in PyCharm, instead of having to exec into the container every time. I've setup the remote interpreter using Docker. However, when I run the test in PyCharm I get the following error:
django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
It appears the app container can't find the database container when I run the test in PyCharm. This brings about two questions:
Is there anyway to fix this so the app container can find the database container? I know docker networking on localhost is tricky.
Is there anyway to setup the tests so they don't need to connect to the database container? I feel like
Django
orpsycopg2
should be able to spin up a mock PostgreSQL service for the tests.
One way I've fixed this in the past is to use sqlite3 for my test database; however, I'm using fields that are not compatible with sqlite (such as ArrayField) so that's not an option.
hostname: db
to the db container spec? – richyenlink
indocker-compose
? – richyen