-2

I Think the two csrf value is not same that is why my test case is failing. How do i test the template is working good?


FAIL: test_home_page_can_save_a_POST_request (lists.tests.HomePageTest)

Traceback (most recent call last): File "G:\dj_proj\ObeyTheTestingGoat\superlists\lists\tests.py", line 46, in te st_home_page_can_save_a_POST_request

    self.assertEqual(response.content.decode(), expect_html)
AssertionError: '<!DO[178 chars]lue="mksJcHsmmhRKsu96jGJaqz7sh593cCLcG8AEkK5CC[2
13 chars]tml>' != '<!DO[178 chars]lue="kGamofdgnvgVD2MfLaIZKrLQ99WOYjzlEuihwiQwD
[213 chars]tml>'

Ran 4 tests in 0.015s

FAILED (failures=1) Destroying test database for alias 'default'...


    def test_home_page_can_save_a_POST_request(self):
        request = HttpRequest()
        request.method = 'POST'
        request.POST['item_text'] = 'A new list item'

        response = views.home_page(request)

        self.assertIn('A new list item', response.content.decode())
        
        expect_html = render_to_string('home.html', context={'new_item_text':'A new list item'}, request=request)
        self.assertEqual(response.content.decode(), expect_html)
raghav
  • 1
  • 6

1 Answers1

0

For testing purposes, you can use Client class from django.test to make request. It is also present as an object in your test class, if you inherit from TestCase. This will help you get rid of the csrf issue.

from django.test import TestCase

class TestView(TestCase):
     def test_home_page_can_save_a_POST_request(self):
        url = '<url-to-your-view>'
        response = self.client.post((url, data=['item_text'])

        # perform your assertions then
        self.assertIn('A new list item', response.content.decode())
        
        expect_html = render_to_string('home.html', context={'new_item_text':'A new list item'}, request=request)
        self.assertEqual(response.content.decode(), expect_html)

You may read the documentation regarding testing for csrf and unit-testing in django for more details.

Abhyudai
  • 826
  • 7
  • 16
  • tryt to set `msxDiff=0` inside your test `class` to see the complete difference, if it is due to the `csrf` value, see you see the relevant documentation links in the answer to figure out your issue in more detail. – Abhyudai Jul 21 '21 at 06:48
  • it is showing that value of csrf token is changed. i used assertMultiLineEqual with maxdiff statement. – raghav Jul 21 '21 at 07:41