【发布时间】:2020-05-15 12:58:09
【问题描述】:
我正在测试一种需要我在模型中创建虚假记录的方法。该模型有 40 多个字段。是否可以创建仅包含测试相关模型字段的记录,这样我就不必填充其他字段?如果是这样,我将如何将其应用于此测试用例示例。
models.py
class Contract():
company = models.CharField(max_length=255),
commission_rate = models.DecimalField(max_digits=100, decimal_places=2)
type = models.CharField(max_length=255)
offer = models.ForeignKey('Offer', on_delete=models.PROTECT)
notary = models.ForeignKey('Notary', on_delete=models.PROTECT)
jurisdiction = models.ForeignKey('Jurisdiction', on_delete=models.PROTECT)
active = models.BooleanField()
...
test.py
import pytest
from app.models import Contract
def calculate_commission(company, value):
contract = Contract.objects.get(company='Apple')
return value * contract.commission_rate
@pytest.mark.django_db
def test_calculate_commission():
#The only two model fields I need for the test
Contract.objects.create(company='Apple', commission_rate=0.2)
assert calculate_commission('Apple', 100) == 20
【问题讨论】:
标签: django python-3.x unit-testing django-models