Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: unit testing html tags from response and sessions

Is there a way to test the html from the response of:

response = self.client.get('/user/login/')

I want a detailed check like input ids, and other attributes. Also, how about sessions that has been set? is it possible to check their values in the test?

like image 263
Marconi Avatar asked May 17 '10 13:05

Marconi


2 Answers

Careful.

Also, how about sessions that has been set? is it possible to check their values in the test?

TDD is about externally visible behavior. To see if the user has a session, you would provide a link that only works when the user is logged in and has a session.

The usual drill is something like the following.

class When_NoLogin( TestCase ):
    def test_should_not_get_some_resource( self ):
        response= self.client.get( "/path/that/requires/login" )
        self.assertEquals( 301, response.status_code )

That is, when not logged in, some (or all) URI's redirect to the login page.

class When_Login( TestCase ):
    def setUp( self ):
        self.client.login( username='this', password='that' )
    def test_should_get_some_resource( self ):
        response= self.client.get( "/path/that/requires/login" )
        self.assertContains( response, '<input attr="this"', status_code=200 )
        self.assertContains( response, '<tr class="that"', count=5 )

https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.SimpleTestCase.assertContains

That is, when logged in, some (or all) URI's work as expected.

Further, the URI response contains the tags you require.

You don't test Django to see if it creates a session. Django already has unit tests for this. You test your application's externally visible behavior -- does it behave like there's a session? Are pages properly visible? Are they properly customized with session-specific information?

like image 72
S.Lott Avatar answered Sep 29 '22 18:09

S.Lott


Not sure, but take a look at https://docs.djangoproject.com/en/dev/topics/testing/tools/#testing-responses.

response.context is maybe a way to check your values.

like image 27
dzen Avatar answered Sep 29 '22 18:09

dzen