FAIL: test_post (ecapp.tests.test_api.ProductApiTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\lion-\Desktop\portfolio\ecapp\tests\test_api.py", line 82, in test_post
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
AssertionError: 400 != 201
Я получаю эту ошибку, когда запускаю тест ниже
test_api.py
from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, Client
from django.test.client import encode_multipart
from django.urls import reverse
from django.utils.timezone import localtime
from faker import Faker
from rest_framework import status
from rest_framework.test import APIRequestFactory, force_authenticate, APIClient, APITestCase
from ..models import Product
from ..views import ProductViewSet
from .factories import ProductFactory, UserFactory
class ProductApiTest(APITestCase):
def test_post(self):
user = UserFactory()
view = ProductViewSet.as_view({'post': 'create'})
filename = 'test_img'
file = File(open('static/default_icon.jpg', 'rb'))
uploaded_file = SimpleUploadedFile(
filename, file.read(), content_type='multipart/form-data')
client = APIClient()
client.force_authenticate(user=user)
data = {
'name': 'test',
'description': 'test',
'price': 1,
'amount': 1,
'image': uploaded_file,
'owner': 1
}
url = reverse('product-list')
response = client.post(url, data, format='multipart')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Product.objects.count(), 1)
factories.py
import factory.fuzzy
import random
import datetime
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = get_user_model()
django_get_or_create = ('username',)
email = factory.Sequence(lambda n: f'person{n}@example.com')
username = factory.Faker('name')
address = factory.Faker('address')
icon = factory.Faker('image_url')
message = factory.Faker('word')
last_login_date = datetime.date.today()
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
price = models.PositiveIntegerField(default=0)
amount = models.PositiveIntegerField(default=1)
image = models.ImageField(upload_to='product')
owner = models.ForeignKey('users.User', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
views.py
from rest_framework import viewsets
from rest_framework import permissions, authentication
from .models import Product, Sale
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
"""API endpoint"""
queryset = Product.objects.all().order_by('-created_at')
serializer_class = ProductSerializer
permission_classes = [permissions.IsAuthenticated]
serializers.py
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name', 'description', 'price',
'amount', 'image', 'owner', 'created_at')
Тестирование с помощью метода get прошло нормально. Кроме того, когда я запустил сообщение в браузере, это сработало. Где мне нужно изменить, чтобы пройти этот тест?
Ссылки
Как сгенерировать запрос загрузки файла (тестовый) с помощью Django REST Framework's APIRequestFactory?
Официальная документация