|
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 |
|
| 6 | +from graphene import ObjectType, String, Schema |
5 | 7 | from graphene_django.tests.models import Film, FilmDetails, Pet
|
6 | 8 |
|
7 | 9 | from ...settings import graphene_settings
|
|
11 | 13 | class MyForm(forms.Form):
|
12 | 14 | text = forms.CharField()
|
13 | 15 |
|
| 16 | + def clean_text(self): |
| 17 | + text = self.cleaned_data["text"] |
| 18 | + if text == "INVALID_INPUT": |
| 19 | + raise ValidationError("Invalid input") |
| 20 | + return text |
| 21 | + |
| 22 | + def save(self): |
| 23 | + pass |
| 24 | + |
14 | 25 |
|
15 | 26 | class PetForm(forms.ModelForm):
|
16 | 27 | class Meta:
|
@@ -59,6 +70,68 @@ class Meta:
|
59 | 70 | graphene_settings.CAMELCASE_ERRORS = False
|
60 | 71 |
|
61 | 72 |
|
| 73 | +class MockQuery(ObjectType): |
| 74 | + a = String() |
| 75 | + |
| 76 | + |
| 77 | +class FormMutationTests(TestCase): |
| 78 | + def test_form_invalid_form(self): |
| 79 | + class MyMutation(DjangoFormMutation): |
| 80 | + class Meta: |
| 81 | + form_class = MyForm |
| 82 | + |
| 83 | + class Mutation(ObjectType): |
| 84 | + my_mutation = MyMutation.Field() |
| 85 | + |
| 86 | + schema = Schema(query=MockQuery, mutation=Mutation) |
| 87 | + |
| 88 | + result = schema.execute( |
| 89 | + """ mutation MyMutation { |
| 90 | + myMutation(input: { text: "INVALID_INPUT" }) { |
| 91 | + errors { |
| 92 | + field |
| 93 | + messages |
| 94 | + } |
| 95 | + text |
| 96 | + } |
| 97 | + } |
| 98 | + """ |
| 99 | + ) |
| 100 | + |
| 101 | + self.assertIs(result.errors, None) |
| 102 | + self.assertEqual( |
| 103 | + result.data["myMutation"]["errors"], |
| 104 | + [{"field": "text", "messages": ["Invalid input"]}], |
| 105 | + ) |
| 106 | + |
| 107 | + def test_form_valid_input(self): |
| 108 | + class MyMutation(DjangoFormMutation): |
| 109 | + class Meta: |
| 110 | + form_class = MyForm |
| 111 | + |
| 112 | + class Mutation(ObjectType): |
| 113 | + my_mutation = MyMutation.Field() |
| 114 | + |
| 115 | + schema = Schema(query=MockQuery, mutation=Mutation) |
| 116 | + |
| 117 | + result = schema.execute( |
| 118 | + """ mutation MyMutation { |
| 119 | + myMutation(input: { text: "VALID_INPUT" }) { |
| 120 | + errors { |
| 121 | + field |
| 122 | + messages |
| 123 | + } |
| 124 | + text |
| 125 | + } |
| 126 | + } |
| 127 | + """ |
| 128 | + ) |
| 129 | + |
| 130 | + self.assertIs(result.errors, None) |
| 131 | + self.assertEqual(result.data["myMutation"]["errors"], []) |
| 132 | + self.assertEqual(result.data["myMutation"]["text"], "VALID_INPUT") |
| 133 | + |
| 134 | + |
62 | 135 | class ModelFormMutationTests(TestCase):
|
63 | 136 | def test_default_meta_fields(self):
|
64 | 137 | class PetMutation(DjangoModelFormMutation):
|
|
0 commit comments