Django测试客户端获得返回404,但可在Shell和Web浏览器中使用

时间:2018-07-19 16:37:37

标签: python django

能帮我吗?我正在遍历Django初学者课程(https://github.com/sibtc/django-beginners-guide),无法弄清楚为什么示例中的测试用例总是返回错误404,即使在Shell或Web浏览器中也能正常工作。

我正在运行Python 3.5.3,Django版本:2.0.7

代码: url.py:

from django.contrib import admin
from django.urls import path
from boards import views as boards_views

urlpatterns = [
    path('', boards_views.home, name='home'),
    path('boards/<int:pk>/', boards_views.board_topics, name='board_topics'),
    path('admin/', admin.site.urls),
]

views.py:

from django.shortcuts import render, get_object_or_404
from .models import Board
# Create your views here.
def home(request):
    boards = Board.objects.all()
    return render(request, 'home.html', {'boards': boards})
def board_topics(request, pk):
    board = get_object_or_404(Board, pk=pk)
    return render(request, 'topics.html', {'board': board})

Tests.py:

from django.test import TestCase
from django.urls import resolve, reverse
from django.test.client import Client
from .views import home, board_topics
from .models import Board

# Create your tests here.
class BoardTopicsTests(TestCase):
    def setUp(self):
        Board.objects.create(name='Django', description='Django board.')

    def test_board_topics_view_success_status_code(self):
        url = reverse('board_topics', kwargs={'pk': 1})
        print('url = ' + str(url))
        response = self.client.get(url)
        self.assertEquals(response.status_code, 200)

此测试始终返回404错误,即使我可以在此测试中通过打印语句看到该数据库条目存在且url正确。

谢谢!

2 个答案:

答案 0 :(得分:0)

您确定创建的面板的主键是1吗?

class BoardTopicsTests(TestCase):
    def setUp(self):
        self.board = Board.objects.create(name='Django', description='Django board.')

    def test_board_topics_view_success_status_code(self):
        url = reverse('board_topics', kwargs={'pk': self.board.pk})
        response = self.client.get(url)
        self.assertEquals(response.status_code, 200)

答案 1 :(得分:0)

该测试不一定会创建一个pk = 1的木板。您不应该硬编码任何特定的值。而是保存创建的实例并使用它。

def setUp(self):
    self.board = Board.objects.create(name='Django', description='Django board.')

def test_board_topics_view_success_status_code(self):
    url = reverse('board_topics', kwargs={'pk': self.board.pk})