Skip to content

Parsing comma separated integers fails. #13

@Elagoht

Description

@Elagoht

Thanks for course. But I noticed a problem with your approach to parse query parameters. currently this code will produce an error on this test

    def test_filter_by_invalid_tags_query(self):
        """Test filtering recipes by non integer tag queries."""

        params = {"tags": "noninteger,noninteger2"}
        res = self.client.get(RECIPES_URL, params)
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_filter_by_invalid_ingredients_query(self):
        """Test filtering recipes by non integer ingredient queries."""

        params = {"ingredients": "invalid,invalid2"}
        res = self.client.get(RECIPES_URL, params)
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

can be fixed by simply:

    def _params_to_ints(self, qs):
        """Convert a list of strings to integers."""

        from rest_framework.exceptions import ValidationError

        try:
            return [int(str_id) for str_id in qs.split(",")]
        except ValueError:
            raise ValidationError("Invalid parameter. Must be comma-separated integers.")

of course, using Django-Filter will be better.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions