【问题标题】:Testing for links in a page content in Django在 Django 中测试页面内容中的链接
【发布时间】:2015-06-17 21:29:45
【问题描述】:

美好的一天!

那么我的问题,

我有一个带有一些链接的模板,我想断言它们确实存在于我的页面中。

我的 html 部分,

<section>
    <p>Welcome to open radio. We help you get on air!</p>
    <p><a href="{% url 'userlogin' %}">Login</a></p>
    <p><a href="{% url 'liststations' %}">View all our stations</a></p>
    <p><a href="{% url 'userregistration' %}">SignUp!</a></p>      
</section>

我现在的测试,

response = self.client.get(reverse("home"))
assert reverse("userlogin") in response.content
assert reverse("liststations") in response.content
assert reverse("userregistration") in response.content

我的测试通过了,我知道我并不是真的在断言这里的链接,而是断言 URL 的字符串。我如何专门测试链接?

【问题讨论】:

    标签: django python-2.7 django-testing


    【解决方案1】:

    Django 自己的测试套件使用它来断言某个 url 在响应中:

    response = self.client.get(reverse("home"))
    self.assertContains(response, '<a href="%s">Login</a>' % reverse("userlogin"), html=True)
    ...
    

    self.assertContains 处理response 是一个响应对象,以及双方都是 html 并且只需要等价,不一定等价。

    这是假设您正在使用django.test.SimpleTestCase(的子类)。

    【讨论】:

    • 不出所料,事情很简单,但我想不通。非常感谢。非常感激!我确实在使用 TestCase 的子类,但我已经使用 assert '&lt;a href="%s"&gt;Login&lt;/a&gt;' % reverse("userlogin") in response.content :)
    • 如果您需要更多测试灵感,请查看github.com/django/django/tree/master/tests
    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多