模型约束不适用于 Faker ( Django )

Model constraints are not working with Faker ( Django )

我刚开始使用pytest和faker进行测试

在尝试为测试数据库中的字段创建 文本时,约束被忽略,我不知道如何修复它。

models.py

from django.db import models

# Create your models here.


class Note(models.Model):
    body = models.TextField(null=True, blank=True, max_length=5)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.body[0:50]

factories.py

import factory
from faker import Faker
fake = Faker()
from mynotes_api.models import Note


class NoteFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Note

    body = fake.text()

conftest.py

import pytest
from django.contrib.auth.models import User
from pytest_factoryboy import register
from tests.factories import NoteFactory

register(NoteFactory)

@pytest.fixture
def new_user1(db, note_factory):
    note = note_factory.create()
    return note

test_ex1.py

import pytest

def test_product(new_user1):
    note = new_user1
    print(note.body)
    assert True

测试输出

输出中可见的问题是生成并存储在测试数据库中的文本长度超过 5。

请多多指教。

Iain Shelvington 使用 CharField 的建议是这里的主要问题。它将强制执行数据库约束。

Django 提供了更多类型的无法由数据库强制执行的验证。这些将不会在 model.save 调用中被检查:

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.

How validators are run