測試也是一個項目開發(fā)過程中不可避免的話題,此處項目框架為django,測試庫為pytest-django
1. install
pip install -i https://pypi.doubanio.com/simple pytest-django==3.2.1
2. pytest.ini
和manage.py同級
[pytest]
DJANGO_SETTINGS_MODULE = mshan.settings
python_files = tests.py test_*.py *_tests.py
3. 基礎測試
import pytest
@pytest.mark.parametrize('test_input,expected', [
('1+1', 2),
('2*10', 20),
# ('1==1', False),
])
def test_eval(test_input, expected):
assert eval(test_input) == expected
4. 關聯數據庫
可以使用@pytest.mark.django_db,正常操作的話,pytest會自動創(chuàng)建測試數據庫test_project(project為項目數據庫名稱),但是通常來說,不會賦予使用者帳號這么高的權限
我的做法是:
- 手動創(chuàng)建
test_db,賦予權限 - 手動指定pytest使用的數據庫
可以加一個conftest.py
import pytest
from django.conf import settings
@pytest.fixture(scope='session')
@pytest.mark.django_db()
def django_db_setup():
settings.DATABASES['default'] = {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test_db',
'USER': 'xx',
'PASSWORD': 'xxx',
'HOST': 'xxx',
'PORT': 'xxx',
}
之后的測試代碼可以正常使用
@pytest.mark.django_db
def test_user():
from django.contrib.auth import get_user_model
User = get_user_model()
manbug = User.objects.get(username="manbug")
assert manbug.is_superuser == True