pytest

作者: manbug | 来源:发表于2018-05-11 16:50 被阅读0次

测试也是一个项目开发过程中不可避免的话题,此处项目框架为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会自动创建测试数据库test_project(project为项目数据库名称),但是通常来说,不会赋予使用者帐号这么高的权限
我的做法是:

  1. 手动创建test_db,赋予权限
  2. 手动指定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

相关文章

网友评论

      本文标题:pytest

      本文链接:https://www.haomeiwen.com/subject/opafdftx.html