Properly handle unexisting or malformed IDs

get_object returns a 404 if the pk doesn't exist (or isn't an integer)
This commit is contained in:
Roland Geider
2026-05-20 20:09:37 +02:00
parent 650676f6ee
commit 3c82b0ec71
4 changed files with 35 additions and 7 deletions

View File

@@ -326,10 +326,7 @@ class ExerciseImageViewSet(ModelViewSet):
"""
Return a list of the image's thumbnails
"""
try:
image = ExerciseImage.objects.get(pk=pk)
except ExerciseImage.DoesNotExist:
return Response([])
image = self.get_object()
thumbnails = {}
for alias in aliases.all():

View File

@@ -15,6 +15,7 @@
# Django
from django.core.files import File
from django.test import SimpleTestCase
from django.urls import reverse
# wger
from wger.core.tests import api_base_test
@@ -205,6 +206,20 @@ class ExerciseImageFromJsonSimpleTests(SimpleTestCase):
self.assertFalse(img.is_main)
class ExerciseImageThumbnailsApiTestCase(WgerTestCase):
"""
Tests the thumbnails action of the exercise image API endpoint
"""
def test_thumbnails_non_numeric_pk(self):
"""A non-numeric pk yields a 404 instead of raising a 500"""
response = self.client.get(
reverse('exerciseimage-thumbnails', kwargs={'pk': 'not-a-number'})
)
self.assertEqual(response.status_code, 404)
# TODO: add POST and DELETE tests
class ExerciseImagesApiTestCase(
ActstreamUpdateMixin,

View File

@@ -385,6 +385,4 @@ class LogItemViewSet(WgerOwnerObjectModelViewSet):
"""
Return an overview of the nutritional plan's values
"""
return Response(
LogItem.objects.get(pk=pk, plan__user=self.request.user).get_nutritional_values()
)
return Response(self.get_object().get_nutritional_values())

View File

@@ -17,6 +17,9 @@
import logging
from decimal import Decimal
# Django
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.nutrition import models
@@ -231,3 +234,18 @@ class NutritionalValuesCalculationsTestCase(WgerTestCase):
self.assertAlmostEqual(values['per_kg']['carbohydrates'], Decimal(4.96), 2)
self.assertAlmostEqual(values['per_kg']['fat'], Decimal(1.51), 2)
self.assertAlmostEqual(values['per_kg']['protein'], Decimal(4.33), 2)
class NutritionalValuesApiTestCase(WgerTestCase):
"""
Tests the nutritional_values action of the nutrition diary API endpoint
"""
def test_nutritional_values_non_numeric_pk(self):
"""A non-numeric pk yields a 404 instead of raising a 500"""
self.user_login('test')
response = self.client.get(
reverse('nutritiondiary-nutritional-values', kwargs={'pk': 'not-a-number'})
)
self.assertEqual(response.status_code, 404)