diff --git a/graphene_django/forms/tests/test_mutation.py b/graphene_django/forms/tests/test_mutation.py index 2de5113..6025784 100644 --- a/graphene_django/forms/tests/test_mutation.py +++ b/graphene_django/forms/tests/test_mutation.py @@ -1,7 +1,9 @@ from django import forms from django.test import TestCase +from django.core.exceptions import ValidationError from py.test import raises +from graphene import ObjectType, String, Schema from graphene_django.tests.models import Film, FilmDetails, Pet from ...settings import graphene_settings @@ -11,6 +13,15 @@ from ..mutation import DjangoFormMutation, DjangoModelFormMutation class MyForm(forms.Form): text = forms.CharField() + def clean_text(self): + text = self.cleaned_data["text"] + if text == "INVALID_INPUT": + raise ValidationError("Invalid input") + return text + + def save(self): + pass + class PetForm(forms.ModelForm): class Meta: @@ -59,6 +70,68 @@ def test_mutation_error_camelcased(): graphene_settings.CAMELCASE_ERRORS = False +class MockQuery(ObjectType): + a = String() + + +class FormMutationTests(TestCase): + def test_form_invalid_form(self): + class MyMutation(DjangoFormMutation): + class Meta: + form_class = MyForm + + class Mutation(ObjectType): + my_mutation = MyMutation.Field() + + schema = Schema(query=MockQuery, mutation=Mutation) + + result = schema.execute( + """ mutation MyMutation { + myMutation(input: { text: "INVALID_INPUT" }) { + errors { + field + messages + } + text + } + } + """ + ) + + self.assertIs(result.errors, None) + self.assertEqual( + result.data["myMutation"]["errors"], + [{"field": "text", "messages": ["Invalid input"]}], + ) + + def test_form_valid_input(self): + class MyMutation(DjangoFormMutation): + class Meta: + form_class = MyForm + + class Mutation(ObjectType): + my_mutation = MyMutation.Field() + + schema = Schema(query=MockQuery, mutation=Mutation) + + result = schema.execute( + """ mutation MyMutation { + myMutation(input: { text: "VALID_INPUT" }) { + errors { + field + messages + } + text + } + } + """ + ) + + self.assertIs(result.errors, None) + self.assertEqual(result.data["myMutation"]["errors"], []) + self.assertEqual(result.data["myMutation"]["text"], "VALID_INPUT") + + class ModelFormMutationTests(TestCase): def test_default_meta_fields(self): class PetMutation(DjangoModelFormMutation):