I am pretty new to Django and web development in general. I decided to learn by creating a simple web app for posting and displaying college reviews. I have a number of GET and POST endpoints that I want to test.
In the past, I have developed APIs where endpoints returned JSON objects that I could assert on when doing my API endpoint testing. However, in this case, my Django app returns HTML.
The first issue I encountered was that my HTML sometimes contains dynamic values that I cannot assert on. For example, the csrf_token
which is located in my forms. Here is part of the HTML file for the university details page:
...
<form action="{% url 'university_add_review' university.id %}" method="post">
{% csrf_token %}
<p>Date:</p><input type="date" name="date" id="date"/>
<p>Summary:</p><textarea name="summary" id="summary">Enter your summary here.</textarea>
<input type="submit" value="Submit"/>
</form>
...
In my unit tests, I want to check that a GET
request to that page is getting the correct contents:
def test_get_university_details(self):
response = Client().get('/%s/overview/' % self.university.id)
self.assertEqual(response.content, expected)
Where expected
is the expected HTML. However, that fails because the csrf_token
is different in every GET
request so I can't have an expected value for it. As a result this test fails:
Traceback (most recent call last):
File ".../tests.py", line 47, in test_get_university_details
self.assertEqual(response.content, expected)
AssertionError: b'\n\[384 chars]ue=\'wrG24VMcdpYYOMECnibQrElP1km9YU0WeOMedGJ2C[488 chars]orm>' != b'\n\[384 chars]ue=\'QWCWACcNQwbfOx9M3iLFt77nSIKhUMiK5i1I4a5mD[530 chars]on> '
So my two questions are:
- What is a solution for this? Could I ignore certain parts of the HTML?
- Is testing the contents of the HTML a good practice when testing Django applications? Should I instead be testing in a different way?