1

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:

  1. What is a solution for this? Could I ignore certain parts of the HTML?
  2. Is testing the contents of the HTML a good practice when testing Django applications? Should I instead be testing in a different way?
pavlos163
  • 2,730
  • 4
  • 38
  • 82
  • Check out [Django's Rest Framework main test page](https://www.django-rest-framework.org/api-guide/testing/#setting-the-available-formats). It has some examples concerning authentication and adding support for using html format in test requests that may help you. – Aurora Wang Nov 18 '18 at 19:41

1 Answers1

1

You can use self.assertContains(result, "abcd") to assert a page contains a given string, as for example shown here

I don't see anything wrong with testing the content of the HTML. Your views contain logic which alter html. Your .html files can also contain templating logic. This needs to be tested, along with other part of your code.

Diane M
  • 1,503
  • 1
  • 12
  • 23