Kalpa Welivitigoda
Kalpa Welivitigoda

Reputation: 262

Testing Django Rest Framework Serializers with pytest

I could use pytest for testing models and views in my django project. Is it possible to use pytest for DRF serializers as well, appreciate pointers to samples.

Upvotes: 6

Views: 3094

Answers (3)

Ayse
Ayse

Reputation: 632

tests.py

import json

from django.contrib.auth.models import User
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
# python manage.py test



class TestUserRegister(APITestCase):
    url = reverse("account:register") 
    # account (urls.py -> app_name:account) , 
    # register (urls.py -> url = [ path("", ...as_view(), name="register")

    def test_user_registration(self):
        """
        @data : input info
        """
        data = {"username": "ayse", "password": "000"}

        response = self.client.post(self.url, data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

Upvotes: 0

user2239318
user2239318

Reputation: 2784

Is there a way to catch the errors from the serializer?

def test_foo_serializer():
    from app.models import Model
    from app.serializers import ModelSerializer

    data = {
            'first':'GIGI',
            'second':'gigi gigi',
     }
    mm = ModelSerializer(data=data)

    assert mm.is_valid() == True # won't show errors
    assert mm.errors == '{}' # will show errors but fail if valid
    assert hasattr(rapp_rif, 'errors') == False # won't show errors

to get something like this:

  assert x.errors == '{}' E       AssertionError: assert {'durata': [ErrorDetail(string='La durata è in un formato errato. Usa

uno dei seguenti formati: [DD] [HH:[MM:]]ss[.uuuuuu].', code='invalid')]} == '{}'

Upvotes: 1

blueyed
blueyed

Reputation: 27858

The following works:

def test_foo_serializer():
    from app.models import Model
    from app.serializers import ModelSerializer

    serializer = ModelSerializer()
    f = serializer.fields['field_name']
    obj = Model()

    assert f.to_representation(obj) == '0.00'
    obj.prop = 123
    assert f.to_representation(obj) == '1.23'

Upvotes: 5

Related Questions