mercredi 20 janvier 2021

Django API test not working for post request.with payload

I am writing some tests for an API that I am working on. I am quite new to Django Rest-framework. This is the code for my POST test. Need to be logged in and authenticated to do a post request.

The strange thing is that my test is failing (BAD request 400) but my published 'live-api' is working, at least via the Django api-web-browser. I can't find the mistake.

The VACANCY_URL is correct, I checked that by printing it in code. The GET request doesn't have any problems. So I can conclude that my client is working. Then I thought it must the payload that I am sending. I tried to all possible variants I could think of. Here I show you my test-script and my model,view and URLs. I am using Default router for this.

Can anyone see what I am doing wrong?

TESTSCRIPT:

from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Vacancy
from vacancy.serializers import VacancySerializer


VACANCY_URL = reverse('vacancy:vacancy-list')

class PrivateVacanciesApiTests(TestCase):
        """ Test the Private vacancy API"""

        def setUp(self):
            self.client = APIClient()
            self.user = get_user_model().objects.create_user(
            email='test@uxstudio.nl',
            password='testpass')
            self.client.force_authenticate(self.user)


       def test_create_vacancy_successful(self):
            """Test create a new vacancy"""
            payload = {
                        "title": "titel",
                        "description": "wat tekst om te testen",
                        "is_active": True,
            }
            self.client.post(VACANCY_URL, payload)

            exists = Vacancy.objects.filter(
                company_id=self.user,
                title=payload['title']
            ).exists()

            self.assertTrue(exists)

MODEL

class Vacancy(models.Model):
    """Vacancy to be created by company"""
    company_id = models.ForeignKey(settings.AUTH_USER_MODEL,
                                   on_delete=models.CASCADE,
                                   related_name='company_user')
    title = models.CharField(max_length=255)
    publication_date = models.DateTimeField(default=timezone.now, blank=True,
                                            null=True)
    start_date = models.DateField(null=True, blank=True)
    description = models.CharField(max_length=1000)
    work_location = models.CharField(max_length=255, blank=True)
    hours_per_week = models.IntegerField(blank=True, null=True)
    contact_email = models.CharField(max_length=255, blank=True)
    contact_tel = models.CharField(max_length=255, blank=True)
    ideal_testscore = ArrayField(models.IntegerField(blank=True), blank=True,
                                 default=list)
    is_active = models.BooleanField(default=False)

    def __str__(self):
        return self.title

VIEW

class VacancyViewSet(viewsets.GenericViewSet,
                     mixins.ListModelMixin,
                     mixins.CreateModelMixin):
    """Manage vacancies in the database"""
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    queryset = Vacancy.objects.all()
    serializer_class = serializers.VacancySerializer

    def get_queryset(self):
        """Return only objects that are active"""
        return self.queryset.filter(is_active=True).order_by(
            '-publication_date')

    def perform_create(self, serializer):
        """Create a new vacancy"""
        serializer.save(company_id=self.request.user)

URLS

from django.urls import path, include
from rest_framework.routers import DefaultRouter

from vacancy import views

router = DefaultRouter()
router.register('', views.VacancyViewSet)

app_name = 'vacancy'

urlpatterns = [
    path('', include(router.urls))
]

SERIALIZER

from rest_framework import serializers
from core.models import Vacancy


class VacancySerializer(serializers.ModelSerializer):
    """Serializer for vacancies"""

    class Meta:
        model = Vacancy
        exclude = ('id',)
        read_only_fields = ['id']

I just can't see why this is not working.

Aucun commentaire:

Enregistrer un commentaire