Ticket #5333: 5333.diff

File 5333.diff, 11.9 KB (added by Gary Wilson, 17 years ago)
  • django/test/testcases.py

    === modified file 'django/test/testcases.py'
     
    149149                                (form, i, err, list(context[form].non_field_errors())))
    150150        if not found_form:
    151151            self.fail("The form '%s' was not used to render the response" % form)
    152            
     152
     153    def assertContext(self, response, variable_name, value):
     154        """
     155        Asserts that one of the contexts used to render the response
     156        contains the context variable variable_name equal to value.
     157        """
     158        # Put context(s) into a list to simplify processing.
     159        contexts = to_list(response.context)
     160        if not contexts:
     161            self.fail('Response did not use any contexts to render the'
     162                      ' response')
     163        test_passed = False
     164        for context in contexts:
     165            if context.get(variable_name) == value:
     166                test_passed = True
     167                break
     168        if not test_passed:
     169            self.fail("The context variable '%s' with value '%s' was not"
     170                      " found in the context(s) used to render the"
     171                      " response" % (variable_name, value))
     172
    153173    def assertTemplateUsed(self, response, template_name):
    154174        "Assert that the template with the provided name was used in rendering the response"
    155175        template_names = [t.name for t in to_list(response.template)]
  • tests/regressiontests/test_client_regress/models.py

    === modified file 'tests/regressiontests/test_client_regress/models.py'
     
    3131            self.assertContains(response, 'once', 2)
    3232        except AssertionError, e:
    3333            self.assertEquals(str(e), "Found 1 instances of 'once' in response (expected 2)")
    34        
     34
    3535        try:
    3636            self.assertContains(response, 'twice', 1)
    3737        except AssertionError, e:
    3838            self.assertEquals(str(e), "Found 2 instances of 'twice' in response (expected 1)")
    39        
     39
    4040        try:
    4141            self.assertContains(response, 'thrice')
    4242        except AssertionError, e:
     
    4646            self.assertContains(response, 'thrice', 3)
    4747        except AssertionError, e:
    4848            self.assertEquals(str(e), "Found 0 instances of 'thrice' in response (expected 3)")
    49        
     49
    5050class AssertTemplateUsedTests(TestCase):
    5151    fixtures = ['testdata.json']
    52    
     52
    5353    def test_no_context(self):
    5454        "Template usage assertions work then templates aren't in use"
    5555        response = self.client.get('/test_client_regress/no_template_view/')
    5656
    5757        # Check that the no template case doesn't mess with the template assertions
    5858        self.assertTemplateNotUsed(response, 'GET Template')
    59        
     59
    6060        try:
    6161            self.assertTemplateUsed(response, 'GET Template')
    6262        except AssertionError, e:
    6363            self.assertEquals(str(e), "No templates used to render the response")
    6464
    65     def test_single_context(self):       
     65    def test_single_context(self):
    6666        "Template assertions work when there is a single context"
    6767        response = self.client.get('/test_client/post_view/', {})
    6868
    69         # 
     69        #
    7070        try:
    7171            self.assertTemplateNotUsed(response, 'Empty GET Template')
    7272        except AssertionError, e:
    7373            self.assertEquals(str(e), "Template 'Empty GET Template' was used unexpectedly in rendering the response")
    74            
     74
    7575        try:
    76             self.assertTemplateUsed(response, 'Empty POST Template')       
     76            self.assertTemplateUsed(response, 'Empty POST Template')
    7777        except AssertionError, e:
    7878            self.assertEquals(str(e), "Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template")
    79    
     79
    8080    def test_multiple_context(self):
    8181        "Template assertions work when there are multiple contexts"
    8282        post_data = {
     
    9999            self.assertEquals(str(e), "Template 'base.html' was used unexpectedly in rendering the response")
    100100
    101101        try:
    102             self.assertTemplateUsed(response, "Valid POST Template")       
     102            self.assertTemplateUsed(response, "Valid POST Template")
    103103        except AssertionError, e:
    104104            self.assertEquals(str(e), "Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html")
    105105
    106106class AssertRedirectsTests(TestCase):
    107107    def test_redirect_page(self):
    108         "An assertion is raised if the original page couldn't be retrieved as expected"       
     108        "An assertion is raised if the original page couldn't be retrieved as expected"
    109109        # This page will redirect with code 301, not 302
    110         response = self.client.get('/test_client/permanent_redirect_view/')       
     110        response = self.client.get('/test_client/permanent_redirect_view/')
    111111        try:
    112112            self.assertRedirects(response, '/test_client/get_view/')
    113113        except AssertionError, e:
    114114            self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 301 (expected 302)")
    115    
     115
    116116    def test_lost_query(self):
    117117        "An assertion is raised if the redirect location doesn't preserve GET parameters"
    118118        response = self.client.get('/test_client/redirect_view/', {'var': 'value'})
     
    123123
    124124    def test_incorrect_target(self):
    125125        "An assertion is raised if the response redirects to another target"
    126         response = self.client.get('/test_client/permanent_redirect_view/')       
     126        response = self.client.get('/test_client/permanent_redirect_view/')
    127127        try:
    128128            # Should redirect to get_view
    129129            self.assertRedirects(response, '/test_client/some_view/')
    130130        except AssertionError, e:
    131131            self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 301 (expected 302)")
    132        
     132
    133133    def test_target_page(self):
    134134        "An assertion is raised if the response redirect target cannot be retrieved as expected"
    135135        response = self.client.get('/test_client/double_redirect_view/')
     
    138138            self.assertRedirects(response, '/test_client/permanent_redirect_view/')
    139139        except AssertionError, e:
    140140            self.assertEquals(str(e), "Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)")
    141            
     141
    142142class AssertFormErrorTests(TestCase):
    143143    def test_unknown_form(self):
    144144        "An assertion is raised if the form name is unknown"
     
    157157            self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.')
    158158        except AssertionError, e:
    159159            self.assertEqual(str(e), "The form 'wrong_form' was not used to render the response")
    160        
     160
    161161    def test_unknown_field(self):
    162162        "An assertion is raised if the field name is unknown"
    163163        post_data = {
     
    175175            self.assertFormError(response, 'form', 'some_field', 'Some error.')
    176176        except AssertionError, e:
    177177            self.assertEqual(str(e), "The form 'form' in context 0 does not contain the field 'some_field'")
    178        
     178
    179179    def test_noerror_field(self):
    180180        "An assertion is raised if the field doesn't have any errors"
    181181        post_data = {
     
    193193            self.assertFormError(response, 'form', 'value', 'Some error.')
    194194        except AssertionError, e:
    195195            self.assertEqual(str(e), "The field 'value' on form 'form' in context 0 contains no errors")
    196        
     196
    197197    def test_unknown_error(self):
    198198        "An assertion is raised if the field doesn't contain the provided error"
    199199        post_data = {
     
    212212        except AssertionError, e:
    213213            self.assertEqual(str(e), "The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])")
    214214
     215class AssertContextTests(TestCase):
     216    """Tests for the assertContext method."""
     217
     218    def setUp(self):
     219        self.response = self.client.get(
     220            '/test_client_regress/context_variable_view/')
     221        self.assertEqual(self.response.status_code, 200)
     222        self.assertTemplateUsed(self.response, "Context Variable Template")
     223
     224    def test_unknown_variable(self):
     225        """
     226        Checks that an assertion is raised if the variable does not exist.
     227        """
     228        try:
     229            self.assertContext(self.response, 'editor', 'A Knight')
     230        except AssertionError, e:
     231            self.assertEqual(str(e), "The context variable 'editor' with value 'A Knight' was not found in the context(s) used to render the response")
     232
     233    def test_wrong_value(self):
     234        """
     235        Checks that an assertion is raised if the context variable's value
     236        does not equal the specified value.
     237        """
     238        try:
     239            self.assertContext(self.response, 'author', 'Real McCoy')
     240        except AssertionError, e:
     241            self.assertEqual(str(e), "The context variable 'author' with value 'Real McCoy' was not found in the context(s) used to render the response")
     242
     243    def test_correct_value(self):
     244        """
     245        Checks that no assertion is raised if the context variable's value
     246        matches the specified value.
     247        """
     248        self.assertContext(self.response, 'title', 'Run Away')
     249
    215250class FileUploadTests(TestCase):
    216251    def test_simple_upload(self):
    217252        fd = open(os.path.join(os.path.dirname(__file__), "views.py"))
     
    235270
    236271        # Get a redirection page with the second client.
    237272        response = c.get("/test_client_regress/login_protected_redirect_view/")
    238        
    239         # At this points, the self.client isn't logged in. 
    240         # Check that assertRedirects uses the original client, not the 
     273
     274        # At this points, the self.client isn't logged in.
     275        # Check that assertRedirects uses the original client, not the
    241276        # default client.
    242277        self.assertRedirects(response, "/test_client_regress/get_view/")
  • tests/regressiontests/test_client_regress/urls.py

    === modified file 'tests/regressiontests/test_client_regress/urls.py'
     
    55    (r'^no_template_view/$', views.no_template_view),
    66    (r'^file_upload/$', views.file_upload_view),
    77    (r'^get_view/$', views.get_view),
    8     (r'^login_protected_redirect_view/$', views.login_protected_redirect_view)
     8    (r'^login_protected_redirect_view/$', views.login_protected_redirect_view),
     9    (r'^context_variable_view/$', views.context_variable_view),
    910)
  • tests/regressiontests/test_client_regress/views.py

    === modified file 'tests/regressiontests/test_client_regress/views.py'
     
    22from django.core.mail import EmailMessage, SMTPConnection
    33from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
    44from django.shortcuts import render_to_response
     5from django.template import Context, Template
    56
    67def no_template_view(request):
    78    "A simple view that expects a GET request, and returns a rendered template"
     
    2728def login_protected_redirect_view(request):
    2829    "A view that redirects all requests to the GET view"
    2930    return HttpResponseRedirect('/test_client_regress/get_view/')
    30 login_protected_redirect_view = login_required(login_protected_redirect_view)
    31  No newline at end of file
     31login_protected_redirect_view = login_required(login_protected_redirect_view)
     32
     33def context_variable_view(request):
     34    "A view that uses context variables."
     35    t = Template('{{ title }} by {{ author }}',
     36                 name='Context Variable Template')
     37    c = Context({'title': 'Run Away',
     38                 'author': 'Brave Sir Robin'})
     39    return HttpResponse(t.render(c))
Back to Top