Home > database >  How to test "POST" method via url with dynamic argument (Django Rest Framework)?
How to test "POST" method via url with dynamic argument (Django Rest Framework)?

Time:03-13

I need to test some API endpoints in my app

I.e. I want to create "Bookmark" using Django Rest Framework using "toggle_bookmark/<exercise_id>" url

How can I substitute a value for <exercise_id> in my test_boomark.py file?

This is my urls.py file:

from django.urls import path, include
from rest_framework import routers
from api import bookmark, daily_exercise, like, upload
from api.exercise import ExerciseViewSet, exercise_user_info, toggle_done
from api.plan import PlanViewSet
from api.practice_session import PracticeSessionViewSet
from api.practice_session_exercise import PracticeSessionExerciseViewSet
app_name = "api"

router = routers.DefaultRouter()
router.register(r"exercise", ExerciseViewSet)
router.register(r"plan", PlanViewSet)
router.register(r"practice-session", PracticeSessionViewSet)
router.register(r"practice-session-exercise", PracticeSessionExerciseViewSet)


urlpatterns = [
    path("", include(router.urls)),
    path("upload-file", upload.upload_file, name="upload_file"),
    path("exercise_user_info/<user_plan_uid>/<practice_session_exercise_uid>", exercise_user_info, name="get_exercise_user_info"),
    path("toggle_bookmark/<exercise_id>", bookmark.toggle_bookmark, name="toggle_bookmark"),
    path("toggle_daily_exercise/<exercise_id>", daily_exercise.toggle_daily_exercise, name="toggle_daily_exercise"),
    path("toggle_like/<exercise_id>", like.toggle_like, name="toggle_like"),
    path("toggle_done/<user_plan_uid>/<practice_session_exercise_uid>", toggle_done, name="toggle_done"),
]

Here is my test_bookmark.py file:

import json
from django.urls import reverse
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase, APIClient
from rest_framework import status
from core.models import User, Bookmark


class BookmarkTests(APITestCase):
    def test_bookmark_api(self):
        """ Bookmark API Test """
        user = User.objects.create_user(email='[email protected]', name='lauren')
        client = APIClient()
        client.force_authenticate(user=user)
        client.post('toggle_bookmark/<exercise_id>',{"exercise_id":"123123","exercise":"exerciese1"},format="json")
        assert response.status_code == 201

CodePudding user response:

You calculate the reverse of the URL, so:

from django.urls import reverse

# …

client.post(
    reverse('api:toggle_like', kwargs={'exercise_id': '123123'}),
    {'exercise': 'exerciese1'},
    format='json'
)

Here api:toggle_like is the name of the path (with api the app_name that should be used as prefix), and kwargs=… contains a dictionary with the values for the parameter names.

  • Related