Reputation: 729
When attempting to test data that is passed to a Serializer, I want to test not just for the ValidationError
but the error message itself. The way I have it currently checks for the field name in serializer.errors
, but I'm looking to test for "Reformat your question please."
. What would be a clean way of doing this?
tests.py
class TestQuestionSerializer(TestCase):
'''Verify that when an invalid question is
submitted that a validation error is raised'''
@classmethod
def setUpTestData(cls):
cls.client_data = {
"invalid": {
"title": "Can I post a question?"
},
"valid": {
"title": "How can I post a question?"
}
}
def test_question_serializer_fail(self):
with self.assertRaises(ValidationError) as e:
serializer = QuestionSerializer(data=self.client_data['invalid'])
serializer.is_valid(raise_exception=True)
self.assertIn("title", serializer.errors)
serializers.py
class QuestionSerializer(serializers.Serializer):
title = serializers.CharField(max_length=50)
def validate_title(self, value):
regex = r"^[What|When|Where|How|Why]"
match = re.search(regex, value)
if not match:
raise serializers.ValidationError("Reformat your question please.")
return value
def create(self, validated_data):
return Question.objects.create(**validated_data)
Upvotes: 2
Views: 2483
Reputation: 131
You can use the assertRaisesMessage
. Your test will look like this, then
def test_question_serializer_fail(self):
with self.assertRaisesMessage(ValidationError, "Reformat your question please."):
serializer = QuestionSerializer(data=self.client_data['invalid'])
serializer.is_valid(raise_exception=True).
Upvotes: 1