使用py.test在django中测试`CharField(unique = True)`

时间:2018-01-21 22:26:20

标签: python django pytest pytest-django

我正在努力将django应用程序的所有测试移到py.test。

我无法克服的一个案例是测试强制模型字段的唯一性约束。

示例测试:

# requirements.txt
pytest
pytest-django
...


# myapp/models.py
from django.db import models

class UniqueModel(models.Model):
    unique_field = models.CharField(max_length=100, unique=True)


# myapp/tests/test_unique_model.py
from django.db import IntegrityError
import pytest
from myapp.models import UniqueModel

def test_unique(self, db):
    unique_1 = UnqiueModel(unique_field='not-unique')
    unique_1.save()
    unique_2 = UniqueModel(unique_field='not-unique')

    with pytest.raises(IntegrityError):
       unique_2.save()

此测试失败:

...
        with pytest.raises(IntegrityError):
>           unique_2.save()
E           Failed: DID NOT RAISE <class 'django.db.utils.IntegrityError'>
...

任何指导?

谢谢!

0 个答案:

没有答案