Unit testing REST endpoints in Django












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?










share|improve this question























  • Check out Django's Rest Framework main test page. 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















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?










share|improve this question























  • Check out Django's Rest Framework main test page. 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












1








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?










share|improve this question














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?







python django testing






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 18 '18 at 19:14









pavlos163pavlos163

509844




509844













  • Check out Django's Rest Framework main test page. 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



















  • Check out Django's Rest Framework main test page. 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

















Check out Django's Rest Framework main test page. 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





Check out Django's Rest Framework main test page. 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 Answer
1






active

oldest

votes


















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.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53364546%2funit-testing-rest-endpoints-in-django%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    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.






    share|improve this answer




























      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.






      share|improve this answer


























        1












        1








        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 18 '18 at 20:07









        Arthur HavlicekArthur Havlicek

        777411




        777411
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53364546%2funit-testing-rest-endpoints-in-django%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings