dimanche 19 novembre 2017

Django and Rest Framework: How can I test a model write view without coupling the test to the model structure

I want to test a Django view that takes a JSON, deserializes it using the is_valid method of DRF serializers (which might alter some of the data e.g. by making string values lowercase), and then saves the validated data into a new model instance. Example:

from .models import Foo
from .serializers import FooSerializer

@api_view(['POST'])
def save_foo(request):
    foo_data = request.data
    s = FooSerializer(data=foo_data)
    if s.is_valid():
       validated_foo_data  = s.validated_data
       foo_instance = Foo.objects.create(**validated_foo_data)

How can I test that this view saved all the data appropriately, what's an efficient, DRY way to test this view without coupling my test too much with the schema of the Foo model, or the validation functionality in FooSerializer?

Essentially I want a test that checks that the data passed in the request gets validated and saved to the model, without having the test know about the peculiarities of the validation or the model.

Aucun commentaire:

Enregistrer un commentaire