Testing Django Rest Framework Serializers with pytest

I could use pytest to test models and views in my django project. Can pytest be used for DRF serializers and also evaluate pointers to samples.

+4


source to share


2 answers


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'

      

+2


source


Is there a way to catch 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 ')]} ==' {} '

0


source







All Articles