Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for links in a page content in Django

Good day!

So going to my question,

I have a template with some links and I want to assert that they are indeed there in my page.

My html section,

<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>

My test now,

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

My test passes and I understand I am not really asserting for the links here but rather for the strings of URLs. How may I test for links specifically?

like image 770
Afzal S.H. Avatar asked Apr 12 '15 14:04

Afzal S.H.


1 Answers

Django's own test suite uses this to assert a certain url is in the response:

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

self.assertContains handles both the fact that response is a response object, and that both sides are html and only have to be equivalent, not necessarily equal.

This is assuming you're using (a subclass of) django.test.SimpleTestCase.

like image 192
knbk Avatar answered Sep 28 '22 16:09

knbk