При использовании Django я использую Model.clean() code> для проверки формы, отправленной пользователем. Во время проверки некоторые поля могут обновляться на основе ответа на HTTP-запрос. Я хочу протестировать Model.clean() с помощью unittest Python и имитировать HTTP-запрос.
Мое приложение/models.py < /p>
Код: Выделить всё
import logging
from django.core.exceptions import ValidationError
from django.db import models
from .aid import GitHosting
logger = logging.getLogger(__name__)
class Resource(models.Model):
code_repository = models.URLField(
help_text="Link to the repository where the un-compiled, human readable code and related code is located."
)
version = models.CharField(
blank=True,
# Git hash contains 40 characters
max_length=50,
default="HEAD",
help_text="The version of the resource in the format of a Git commit ID or Git tag.",
)
def clean(self):
git_host = GitHosting()
self.version = git_host.get_version()
Код: Выделить всё
import logging
from unittest.mock import patch
from django.test import TestCase
from django.urls import reverse
from .models import Resource
logger = logging.getLogger(__name__)
@patch("app.models.GitHosting.get_version")
class ResourceViewTestCase(TestCase):
def test_add_resource(self, mock_get_version):
mock_get_version = "5678"
logger.error("Submitting form ...")
response = self.client.post(reverse("app:index"), {
"code_repository": "http://mygit.com/foo/bar"
})
resource = Resource.objects.get(id=1)
self.assertEqual(resource.version, "5678")
Код: Выделить всё
ValueError: Failed to insert expression "" on app.Resource.version. F() expressions can only be used to update, not to insert.
Подробнее здесь: https://stackoverflow.com/questions/792 ... -to-update