我对Django很陌生,遇到了一个问题。我什至不确定这是否是一个愚蠢的问题。我想测试我的主视图是否包含指向主题视图的链接,但是尽管一切就绪,但测试仍然失败。感谢任何帮助。它显示以下错误
Traceback (most recent call last):
File "/home/abc/Desktop/python-environments/second/tutorial/myproject/boards/tests.py", line 26, in test_home_view_contains_link_to_topics_page
self.assertContains(self.response, 'href="{0}"'.format(board_topics_url))
File "/home/abc/Desktop/python-environments/second/lib/python3.5/site-packages/django/test/testcases.py", line 369, in assertContains
self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr)
AssertionError: False is not true : Couldn't find 'href="/boards/1/"' in response
这是我的文件
urls.py
from django.urls import path
from . import views
app_name = 'boards'
urlpatterns = [
path('', views.home, name='home'),
path('<int:d>/', views.topics, name='topics'),
]
views.py
from django.shortcuts import render, get_object_or_404
from .models import Board, topic
def home(request):
boards = Board.objects.all()
return render(request, 'boards/index.html', {'boards': boards})
def topics(request, d):
board = get_object_or_404(Board, id=d)
return render(request, 'boards/topics.html', {'boards': board})
index.html
{% load static %}<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Boards</title>
<link rel="stylesheet" href="{% static 'boards/css/bootstrap.min.css' %}">
</head>
<body>
<div class="container">
<ol class="breadcrumb my-4">
<li class="breadcrumb-item active">Boards</li>
</ol>
<table class="table">
<thead class="thead-inverse">
<tr>
<th>Board</th>
<th>Posts</th>
<th>Topics</th>
<th>Last Post</th>
</tr>
</thead>
<tbody>
{% for board in boards %}
<tr>
<td>
<a href = "{% url 'boards:topics' board.id %}"> {{board.Name }}</a>
<small class="text-muted d-block">{{ board.description}}</small>
</td>
<td class="align-middle">0</td>
<td class="align-middle">0</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
最后是tests.py
from django.test import TestCase
from django.urls import reverse, resolve
from .models import Board
from .views import topics, home
class HomeTests(TestCase):
def setUp(self):
self.board = Board.objects.create(Name='Python',description='Python discussion board')
self.response = self.client.get(reverse('boards:home'))
def test_home_view_status_code(self):
self.assertEquals(self.response.status_code, 200)
def test_home_url_resolves_to_home_view(self):
view = resolve('/boards/')
self.assertEquals(view.func, home)
def test_home_view_contains_link_to_topics_page(self):
board_topics_url = reverse('boards:topics', kwargs={'d': self.board.id})
self.assertContains(self.response, 'href="{0}"'.format(board_topics_url))
答案 0 :(得分:2)
self.assertContains(self.response, 'href =“ {0}”'。format(board_topics_url))
您是否忘记了=
周围的空格?无论如何,您都可以在浏览器中打开页面并检查其html代码。