diff --git a/api/tests.py b/api/tests.py index 3a876ab2..57101256 100644 --- a/api/tests.py +++ b/api/tests.py @@ -397,6 +397,34 @@ class TimerAPITestCase(TestBase.BabyBuddyAPITestCaseBase): }) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, entry) + + def test_start_stop_timer(self): + endpoint = '{}{}/'.format(self.endpoint, 1) + response = self.client.get(endpoint) + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertFalse(response.data["active"]) + + response = self.client.post(f"{endpoint}restart/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.get(endpoint) + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertTrue(response.data["active"]) + + # Restart twice fails + response = self.client.post(f"{endpoint}restart/") + self.assertEqual(response.status_code, status.HTTP_412_PRECONDITION_FAILED) + + response = self.client.post(f"{endpoint}stop/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.get(endpoint) + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertFalse(response.data["active"]) + + # Stopping twice fails + response = self.client.post(f"{endpoint}stop/") + self.assertEqual(response.status_code, status.HTTP_412_PRECONDITION_FAILED) class TummyTimeAPITestCase(TestBase.BabyBuddyAPITestCaseBase): diff --git a/api/views.py b/api/views.py index 3f2329d5..a12da8ad 100644 --- a/api/views.py +++ b/api/views.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- -from rest_framework import viewsets +from rest_framework import viewsets, status +from rest_framework.decorators import action +from rest_framework.response import Response from core import models @@ -49,6 +51,40 @@ class TimerViewSet(viewsets.ModelViewSet): serializer_class = serializers.TimerSerializer filterset_class = filters.TimerFilter + def __timer_operation(self, pk, func): + try: + timer = models.Timer.objects.get(pk=pk) + return func(timer) + except models.Timer.DoesNotExist: + return Response( + {"detail": "timer does not exist"}, + status=status.HTTP_404_NOT_FOUND + ) + + @action(detail=True, methods=['post']) + def stop(self, request, pk=None): + def do_stop(timer): + if not timer.active: + return Response( + {"detail": "timer already stopped"}, + status=status.HTTP_412_PRECONDITION_FAILED + ) + timer.stop() + return Response({"detail": "timer stopped"}) + return self.__timer_operation(pk, do_stop) + + @action(detail=True, methods=['post']) + def restart(self, request, pk=None): + def do_restart(timer): + if timer.active: + return Response( + {"detail": "timer already active"}, + status=status.HTTP_412_PRECONDITION_FAILED + ) + timer.restart() + return Response({"detail": "timer restarted"}) + return self.__timer_operation(pk, do_restart) + class TummyTimeViewSet(TimerFieldSupportMixin, viewsets.ModelViewSet): queryset = models.TummyTime.objects.all()