Как удалить литерал 'b' из ответа на ошибку валидации Raised в сериализаторе python

Когда я поднимаю ошибку валидации в моем сериализаторе, вывод имеет префикс 'b' (который, как я полагаю, является типом байта), и все способы, которыми я пытался удалить его, потерпели неудачу.

Мой класс сериализатора: class AppInputTypeSerializer(serializers.Serializer): #value = serializers.CharField(required=True, max_length = 100, min_length = 1)

def validate_value(self, data):
    length = len(data['value'])
    if length < 1 or length > 100:
        message = "We are sorry, your reply should be between 1 and 100 characters. Please try again."
        data['error'] = message
        raise serializers.ValidationError(message)
    return data

мое представление: class PresentationLayerView(generics.GenericAPIView): permission_classes = (permissions.AllowAny,)

def post(self, request, *args, **kwargs):

    body = request.data
    cardType = body['cardType']
    if cardType == "TERMS_CONDITIONS":
        serializer = AppTandCTypeSerializer(body)
    elif cardType == "CHOICE":
        serializer = AppChoiceTypeSerializer(body)
    elif cardType == "TEXT" or cardType == "INPUT": 
        serializer = AppTextTypeSerializer(body)
    serializer.validate_value(body)
    #print(response.text)
    return Response({}, status=status.HTTP_200_OK,)

Тест_просмотров:

class StartAssessmentViewTests(APITestCase): # Возвращает ошибку валидации, если пользователь вводит > 100 символов для ввода cardType

def test_input_type(self):
    #response = self.client.get(
    #    reverse("app-start-assessment")
    #)
    response = self.client.post(reverse("app-start-assessment"),
        json.dumps({"message":"Please type in the symptom that is troubling you, only one symptom at a time. Reply back to go to the previous question or abort to end the assessment",
            "step":4,
            "value": "This is some rubbish text to see what happens when a user submits an input with a length that is greater than 100",
            "optionId":8,
            "path":"/assessments/assessment-id/dialog/next",
            "cardType":"INPUT"}),
        content_type='application/json')
    self.assertEqual(
        response.content,
                {
                    "message":"Please type in the symptom that is troubling you, only one symptom at a time. Reply back to go to the previous question or abort to end the assessment",
                    "step":"4",
                    "value":"This is some rubbish text to see what happens when a user submits an input with a length that is greater than 100",
                    "optionId":"8",
                    "path":"/assessments/assessment-id/dialog/next",
                    "cardType":"INPUT",
                    "error":"We are sorry, your reply should be between 1 and 100 characters. Please try again."
                }, response.json,
    )

Выходом является ошибка assert из-за префикса ниже:

b'{"message":"Please type in the symptom that is troubling you, only one symptom at a time. Reply back to go to the previous question or abort to end the assessment","step":"4","value":"This is some rubbish text to see what happens when a user submits an input with a length that is greater than 100","optionId":"8","path":"/assessments/assessment-id/dialog/next","cardType":"INPUT","error":"We are sorry, your reply should be between 1 and 100 characters. Please try again."}'

Вместо этого:

{"message":"Please type in the symptom that is troubling you, only one symptom at a time. Reply back to go to the previous question or abort to end the assessment","step":"4","value":"This is some rubbish text to see what happens when a user submits an input with a length that is greater than 100","optionId":"8","path":"/assessments/assessment-id/dialog/next","cardType":"INPUT","error":"We are sorry, your reply should be between 1 and 100 characters. Please try again."}

Пожалуйста, помогите. Спасибо

Выходом является отказ утверждения из-за префикса ниже.

Нет, причина не в этом. Причина в том, что вы сравниваете двоичную строку со словарем. Но даже если бы это была простая строка, это было бы невозможно, потому что строка - это не словарь, даже если они выглядят одинаково.

response.content - это двоичная строка, а не словарь, поскольку в конечном итоге она должна привести к двоичному потоку, отправленному в качестве HTTP-ответа.

Лучше декодировать объект в JSON, а затем проверить, эквивалентен ли он словарю. Вы можете сделать это с помощью response.json():

self.assertEqual(
    {
        "message":"Please type in the symptom that is troubling you, only one symptom at a time. Reply back to go to the previous question or abort to end the assessment",
        "step":"4",
        "value":"This is some rubbish text to see what happens when a user submits an input with a length that is greater than 100",
        "optionId":"8",
        "path":"/assessments/assessment-id/dialog/next",
        "cardType":"INPUT",
        "error":"We are sorry, your reply should be between 1 and 100 characters. Please try again."
    },
    response.json()
)
Вернуться на верх