【问题标题】:How to only create relevant model fields during a django test?如何在 django 测试期间只创建相关的模型字段?
【发布时间】: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


    【解决方案1】:

    尝试使用model_bakery进行对象记录。只需填写您想要的字段并将另一个空白,model_bakery 将处理它。详情可以查看model_bakery

    【讨论】:

      猜你喜欢
      • 2017-12-28
      • 2012-07-28
      • 1970-01-01
      • 2021-12-18
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      相关资源
      最近更新 更多