|
1 | 1 | from django import forms
|
2 | 2 | from django.test import TestCase
|
| 3 | +from django.core.exceptions import ValidationError |
3 | 4 | from py.test import raises
|
4 | 5 |
|
5 | 6 | from graphene import ObjectType, Schema, String, Field
|
|
13 | 14 | class MyForm(forms.Form):
|
14 | 15 | text = forms.CharField()
|
15 | 16 |
|
| 17 | + def clean_text(self): |
| 18 | + text = self.cleaned_data["text"] |
| 19 | + if text == "INVALID_INPUT": |
| 20 | + raise ValidationError("Invalid input") |
| 21 | + return text |
| 22 | + |
| 23 | + def save(self): |
| 24 | + pass |
| 25 | + |
16 | 26 |
|
17 | 27 | class PetForm(forms.ModelForm):
|
18 | 28 | class Meta:
|
@@ -83,6 +93,64 @@ class MockQuery(ObjectType):
|
83 | 93 | a = String()
|
84 | 94 |
|
85 | 95 |
|
| 96 | +class FormMutationTests(TestCase): |
| 97 | + def test_form_invalid_form(self): |
| 98 | + class MyMutation(DjangoFormMutation): |
| 99 | + class Meta: |
| 100 | + form_class = MyForm |
| 101 | + |
| 102 | + class Mutation(ObjectType): |
| 103 | + my_mutation = MyMutation.Field() |
| 104 | + |
| 105 | + schema = Schema(query=MockQuery, mutation=Mutation) |
| 106 | + |
| 107 | + result = schema.execute( |
| 108 | + """ mutation MyMutation { |
| 109 | + myMutation(input: { text: "INVALID_INPUT" }) { |
| 110 | + errors { |
| 111 | + field |
| 112 | + messages |
| 113 | + } |
| 114 | + text |
| 115 | + } |
| 116 | + } |
| 117 | + """ |
| 118 | + ) |
| 119 | + |
| 120 | + self.assertIs(result.errors, None) |
| 121 | + self.assertEqual( |
| 122 | + result.data["myMutation"]["errors"], |
| 123 | + [{"field": "text", "messages": ["Invalid input"]}], |
| 124 | + ) |
| 125 | + |
| 126 | + def test_form_valid_input(self): |
| 127 | + class MyMutation(DjangoFormMutation): |
| 128 | + class Meta: |
| 129 | + form_class = MyForm |
| 130 | + |
| 131 | + class Mutation(ObjectType): |
| 132 | + my_mutation = MyMutation.Field() |
| 133 | + |
| 134 | + schema = Schema(query=MockQuery, mutation=Mutation) |
| 135 | + |
| 136 | + result = schema.execute( |
| 137 | + """ mutation MyMutation { |
| 138 | + myMutation(input: { text: "VALID_INPUT" }) { |
| 139 | + errors { |
| 140 | + field |
| 141 | + messages |
| 142 | + } |
| 143 | + text |
| 144 | + } |
| 145 | + } |
| 146 | + """ |
| 147 | + ) |
| 148 | + |
| 149 | + self.assertIs(result.errors, None) |
| 150 | + self.assertEqual(result.data["myMutation"]["errors"], []) |
| 151 | + self.assertEqual(result.data["myMutation"]["text"], "VALID_INPUT") |
| 152 | + |
| 153 | + |
86 | 154 | class ModelFormMutationTests(TestCase):
|
87 | 155 | def test_default_meta_fields(self):
|
88 | 156 | class PetMutation(DjangoModelFormMutation):
|
|
0 commit comments