我正在为端点构建一个测试用例.使用浏览器访问本地开发中的端点工作得很好--我得到了预期的响应.然而,在测试期间,我得到了一个HttpResponseNotFound,其中在服务器上找不到端点.

#views.py
class ExampleView(APIView):
    permission_classes = (permissions.AllowAny,)

    def get(self, request):
        print('GOT HERE')
        qs = Example.objects.last()
        
        if self.request.user.is_authenticated:
            if self.request.user.is_subscribed:
                message = {
                    'info': 'User can download template.',
                    'template': qs.file.url
                }
                return Response(message, status.HTTP_200_OK)

        message = {
            'info': 'User cannot download template.',
            'template': None
        }
        return Response(message, status.HTTP_400_BAD_REQUEST)

在我的urls.py中

#urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('request/download_template', ExampleView.as_view()),
]

我的测试版本

class TestExample(APITestCase):
    fixtures = ['fixtures/initial', 'fixtures/auth', 'fixtures/example']

    def test_forecast_template_authenticated(self):
        response = self.client.get(
            '/request/download_template/')
        
        print('result', response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

他们的回应

<HttpResponseNotFound Status_Code=404,"Text/html;Charset=utf-8">

我正在try 调试,但我甚至没有达到我所看到的打印语句.我一直在想我的错误在哪里,但都过了几个小时了.为什么我会得到这样的回应?我的错误在哪里呢?

推荐答案

在您的测试中,您使用的是不同的URL:

def test_forecast_template_authenticated(self):
    response = self.client.get(
        '/request/download_template/')

比您在URL中设置的更多:

path('request/download_template', ExampleView.as_view()),

注意末尾的斜杠.

Django相关问答推荐

如果密码在Django中未被散列,则对其进行散列

Django modelform在包含在另一个模板中时不呈现

在Django ORM中引用非主外键

如何在Django模板中有条件地传递值给with变量?

Django授权判断具有通配符模式的URL

Django 在模型中存储用户图像

在 Django 的 TextField 中禁用 HTML 转义

恢复 Django 1.7 RemoveField 迁移

如何在 django 中处理这种竞争条件?

Python / Django 中的 Unicode 与 UTF-8 混淆?

如何在终端中切换 Python 版本?

Django聚合:仅求和返回值?

如何在 Django 和 django-jsonfield 中将 JSONField 的默认值设置为空列表?

UnicodeEncodeError:ascii编解码器无法编码字符

Django unique=True 不工作

Django:如何过滤属于特定组的用户

如何获取经过身份验证的用户列表?

具有 2 种语言的 Django 站点

如何将本地文件分配给 Django 中的 FileField?

Django 在 css 文件中使用背景图像的方法