如何使用动态参数(Django Rest Framework)通过 url 测试 "POST" 方法?

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

我需要在我的应用程序中测试一些 API 端点

即我想使用 Django Rest Framework 使用“toggle_bookmark/”url

创建“书签”

如何在我的 test_boomark.py 文件中替换 的值?

这是我的 urls.py 文件:

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"),
]

这是我的 test_bookmark.py 文件:

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='test@gmail.com', 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

您计算 URL 的倒数,所以:

from django.urls import <strong>reverse</strong>

# …

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

这里的api:toggle_like是路径的名称api应该作为前缀的app_name),以及kwargs=… 包含带有参数名称值的字典。