When I try to test any app with command (I noticed it when I tried to deploy myproject using fabric, which uses this command):
python manage.py test appname
If database is mysql then these two changes will get the things done.
1.Open mysite/mysite/settings.py
Your database settings should have an additional TEST block as shown with projectname_test.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myproject',
'USER': 'chandan',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
'TEST': {
'NAME': 'myproject_test',
},
}
}
2.Type the below command using mysql command prompt or mysql workbench to give all privilages to the user specified in settings.py
GRANT ALL PRIVILEGES ON myproject_test.* TO 'chandan'@'localhost';
Now you can run python manage.py test polls
.
If you are using docker-compose
what worked for me was the following:
ALTER ROLE username CREATEDB;
GRANT ALL PRIVILEGES ON test_database_name.* TO 'username';
or
ALTER ROLE username CREATEDB;
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%';
My settings looks like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database_name',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'db',
'PORT': '3306',
}
}
and my docker-compose.yml
looks as follows:
version: '3'
services:
web:
build: .
command: './wait_for_db_and_start_server.sh'
env_file: env_web
working_dir: /project_name
links:
- db
volumes:
- .:/volume_name
ports:
- "8000:8000"
depends_on:
- db
db:
image: mysql:5.7
restart: always
env_file: env_db
working_dir: /db
volumes:
- ./Dump.sql:/db/Dump.sql
ports:
- "3306:3306"
In my case, GRANT PRIVILEGES solutions didn't work with Python 3.7.2, Django 2.1.7 and MySQL 5.6.23... I don't know why.
So I decided to use SQLite as a TEST database...
DATABASES = {
'default': {
'NAME': 'productiondb',
'ENGINE': 'mysql.connector.django', # 'django.db.backends.mysql'
'USER': '<user>',
'PASSWORD': '<pass>',
'HOST': 'localhost',
'PORT': 3306,
'OPTIONS': {
'autocommit': True,
},
'TEST': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
}
}
After that, TESTS car run without troubles:
$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
Destroying test database for alias 'default'...
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Process finished with exit code 0