gpt4 book ai didi

Django 测试不适用于主键

转载 作者:行者123 更新时间:2023-12-05 06:03:55 24 4
gpt4 key购买 nike

测试.py

from django.test import TestCase, Client, SimpleTestCase
from django.urls import reverse, resolve
from .models import BlogappModel
from django.contrib.auth import get_user_model
from .views import Blogapphome, Blogpostview

class TestUrls(SimpleTestCase):

def test_list_view_url(self):
url = reverse('blogapp')
self.assertEqual( resolve(url).func.view_class, Blogapphome)

def test_detail_view_url(self):
url = reverse('blogpost', args=[1,])
self.assertEqual( resolve(url).func.view_class, Blogpostview)

class BlogTest(TestCase):

def setUp(self):

self.user = get_user_model().objects.create(
username='testuser',
email='test@gamil.com',
password='secrete'
)

self.post = BlogappModel(
title='testing',
author=self.user,
post='bla bla bla',
)

def test_post_detail_view(self):

response = self.client.get(reverse('blogpost', args=[self.post.pk]))

self.assertEqual(response.status_code , 200)

print('All tests are successful')

当我运行这段代码时,它返回 django.urls.exceptions.NoReverseMatch: Reverse for 'blogpost' with arguments '(None,)' not found. 1 pattern(s) tried: ['blogapp/post/(?P<pk>[0-9]+)/$']但正如您在我的 urls.py 中看到的那样,当我使用 args=[1] 时,它返回 404!=200

urlpatterns = [
path('', views.Blogapphome.as_view(), name='blogapp'),
path('post/<int:pk>/', views.Blogpostview.as_view(), name='blogpost')
]

第二个路径是指那个 url 但为什么它在 test.py 中不起作用,

最佳答案

您应该首先创建一个Blog 对象,然后使用该对象的主键:

class TestUrls(SimpleTestCase):

# …

def setUp(self):
# …
self.post = BlogappModel.objects<b>.create(</b>
title='testing',
author=self.user,
post='bla bla bla',
<b>)</b>

def test_detail_view_url(self):
url = reverse('blogpost', args=[<b>self.blog.pk</b>,])
self.assertEqual( resolve(url).func.view_class, Blogpostview)

关于Django 测试不适用于主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66519674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com