使用pytest测试Django Rest Framework序列化程序

时间:2017-03-26 16:56:25

标签: django django-rest-framework pytest

我可以使用pytest来测试我的django项目中的模型和视图。是否可以将pytest用于DRF序列化程序,并了解指向样本的指针。

2 个答案:

答案 0 :(得分:2)

以下作品:

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'

答案 1 :(得分:0)

有没有办法从序列化程序中捕获错误?

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

得到这样的东西:

  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')]} =='{}'