我希望通过以下测试,但总是收到 404 错误。但我希望“获取全部”请求返回所有用户。
import json
from django.test.utils import override_settings
from django.urls import path, include
from rest_framework import routers
from frontend.tests.mocks import views
from django.test import TestCase
app_name = 'frontend'
router = routers.SimpleRouter()
router.register('api/', views.UserModelViewSet)
urlpatterns = [
path('', include(router.urls)),
]
@override_settings(ROOT_URLCONF=__name__)
class TestJsonSchemaSerializer(TestCase): # APITest doesn't work either
def test_custom_serializer(self):
resp = self.client.get('/frontend/api/')
self.assertEquals(resp.status_code, 200)
print(resp.status_code, json.dumps(resp.json()))
有几点需要注意:
如果您希望路由仅在运行测试时存在/注册,您可以有条件地添加它。这样做的一个好方法是:
IS_TEST=True
的变量
urls.py
文件中,使用此设置有条件地注册视图
/api/ 并将视图集注册为子路径,例如 /api/users/
# Create router
router = routers.SimpleRouter()
# Register views
router.register("users", views.UserModelViewSet, "users")
# Conditionally register views
if settings.IS_TEST:
router.register("others", views.OtherViewSet, "others")
# Expose the API
app_urls = [
path("api/", include(router.urls)),
]
然后您可以更新:
override_settings
python manage.py tests settings=[project].settings.test
class TestJsonSchemaSerializer(TestCase):
def test_custom_serializer(self):
resp = self.client.get('/api/others/') # Assuming the `list` endpoint exists in this viewset
self.assertEquals(resp.status_code, 200)