PageRenderTime 118ms CodeModel.GetById 92ms app.highlight 22ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/modeltests/test_client/views.py

https://code.google.com/p/mango-py/
Python | 214 lines | 200 code | 9 blank | 5 comment | 6 complexity | b0b9cc0a6c81fe62778d93cc1eb5f30a MD5 | raw file
  1from xml.dom.minidom import parseString
  2
  3from django.core import mail
  4from django.template import Context, Template
  5from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound
  6from django.contrib.auth.decorators import login_required, permission_required
  7from django.forms.forms import Form
  8from django.forms import fields
  9from django.shortcuts import render_to_response
 10from django.utils.decorators import method_decorator
 11
 12def get_view(request):
 13    "A simple view that expects a GET request, and returns a rendered template"
 14    t = Template('This is a test. {{ var }} is the value.', name='GET Template')
 15    c = Context({'var': request.GET.get('var', 42)})
 16
 17    return HttpResponse(t.render(c))
 18
 19def post_view(request):
 20    """A view that expects a POST, and returns a different template depending
 21    on whether any POST data is available
 22    """
 23    if request.method == 'POST':
 24        if request.POST:
 25            t = Template('Data received: {{ data }} is the value.', name='POST Template')
 26            c = Context({'data': request.POST['value']})
 27        else:
 28            t = Template('Viewing POST page.', name='Empty POST Template')
 29            c = Context()
 30    else:
 31        t = Template('Viewing GET page.', name='Empty GET Template')
 32        c = Context()
 33
 34    return HttpResponse(t.render(c))
 35
 36def view_with_header(request):
 37    "A view that has a custom header"
 38    response = HttpResponse()
 39    response['X-DJANGO-TEST'] = 'Slartibartfast'
 40    return response
 41
 42def raw_post_view(request):
 43    """A view which expects raw XML to be posted and returns content extracted
 44    from the XML"""
 45    if request.method == 'POST':
 46        root = parseString(request.raw_post_data)
 47        first_book = root.firstChild.firstChild
 48        title, author = [n.firstChild.nodeValue for n in first_book.childNodes]
 49        t = Template("{{ title }} - {{ author }}", name="Book template")
 50        c = Context({"title": title, "author": author})
 51    else:
 52        t = Template("GET request.", name="Book GET template")
 53        c = Context()
 54
 55    return HttpResponse(t.render(c))
 56
 57def redirect_view(request):
 58    "A view that redirects all requests to the GET view"
 59    if request.GET:
 60        from urllib import urlencode
 61        query = '?' + urlencode(request.GET, True)
 62    else:
 63        query = ''
 64    return HttpResponseRedirect('/test_client/get_view/' + query)
 65
 66def view_with_secure(request):
 67    "A view that indicates if the request was secure"
 68    response = HttpResponse()
 69    response.test_was_secure_request = request.is_secure()
 70    return response
 71
 72def double_redirect_view(request):
 73    "A view that redirects all requests to a redirection view"
 74    return HttpResponseRedirect('/test_client/permanent_redirect_view/')
 75
 76def bad_view(request):
 77    "A view that returns a 404 with some error content"
 78    return HttpResponseNotFound('Not found!. This page contains some MAGIC content')
 79
 80TestChoices = (
 81    ('a', 'First Choice'),
 82    ('b', 'Second Choice'),
 83    ('c', 'Third Choice'),
 84    ('d', 'Fourth Choice'),
 85    ('e', 'Fifth Choice')
 86)
 87
 88class TestForm(Form):
 89    text = fields.CharField()
 90    email = fields.EmailField()
 91    value = fields.IntegerField()
 92    single = fields.ChoiceField(choices=TestChoices)
 93    multi = fields.MultipleChoiceField(choices=TestChoices)
 94
 95def form_view(request):
 96    "A view that tests a simple form"
 97    if request.method == 'POST':
 98        form = TestForm(request.POST)
 99        if form.is_valid():
100            t = Template('Valid POST data.', name='Valid POST Template')
101            c = Context()
102        else:
103            t = Template('Invalid POST data. {{ form.errors }}', name='Invalid POST Template')
104            c = Context({'form': form})
105    else:
106        form = TestForm(request.GET)
107        t = Template('Viewing base form. {{ form }}.', name='Form GET Template')
108        c = Context({'form': form})
109
110    return HttpResponse(t.render(c))
111
112def form_view_with_template(request):
113    "A view that tests a simple form"
114    if request.method == 'POST':
115        form = TestForm(request.POST)
116        if form.is_valid():
117            message = 'POST data OK'
118        else:
119            message = 'POST data has errors'
120    else:
121        form = TestForm()
122        message = 'GET form page'
123    return render_to_response('form_view.html',
124        {
125            'form': form,
126            'message': message
127        }
128    )
129
130def login_protected_view(request):
131    "A simple view that is login protected."
132    t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template')
133    c = Context({'user': request.user})
134
135    return HttpResponse(t.render(c))
136login_protected_view = login_required(login_protected_view)
137
138def login_protected_view_changed_redirect(request):
139    "A simple view that is login protected with a custom redirect field set"
140    t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template')
141    c = Context({'user': request.user})
142
143    return HttpResponse(t.render(c))
144login_protected_view_changed_redirect = login_required(redirect_field_name="redirect_to")(login_protected_view_changed_redirect)
145
146def permission_protected_view(request):
147    "A simple view that is permission protected."
148    t = Template('This is a permission protected test. '
149                 'Username is {{ user.username }}. '
150                 'Permissions are {{ user.get_all_permissions }}.' ,
151                 name='Permissions Template')
152    c = Context({'user': request.user})
153    return HttpResponse(t.render(c))
154permission_protected_view = permission_required('modeltests.test_perm')(permission_protected_view)
155
156class _ViewManager(object):
157    @method_decorator(login_required)
158    def login_protected_view(self, request):
159        t = Template('This is a login protected test using a method. '
160                     'Username is {{ user.username }}.',
161                     name='Login Method Template')
162        c = Context({'user': request.user})
163        return HttpResponse(t.render(c))
164
165    @method_decorator(permission_required('modeltests.test_perm'))
166    def permission_protected_view(self, request):
167        t = Template('This is a permission protected test using a method. '
168                     'Username is {{ user.username }}. '
169                     'Permissions are {{ user.get_all_permissions }}.' ,
170                     name='Permissions Template')
171        c = Context({'user': request.user})
172        return HttpResponse(t.render(c))
173
174_view_manager = _ViewManager()
175login_protected_method_view = _view_manager.login_protected_view
176permission_protected_method_view = _view_manager.permission_protected_view
177
178def session_view(request):
179    "A view that modifies the session"
180    request.session['tobacconist'] = 'hovercraft'
181
182    t = Template('This is a view that modifies the session.',
183                 name='Session Modifying View Template')
184    c = Context()
185    return HttpResponse(t.render(c))
186
187def broken_view(request):
188    """A view which just raises an exception, simulating a broken view."""
189    raise KeyError("Oops! Looks like you wrote some bad code.")
190
191def mail_sending_view(request):
192    mail.EmailMessage(
193        "Test message",
194        "This is a test email",
195        "from@example.com",
196        ['first@example.com', 'second@example.com']).send()
197    return HttpResponse("Mail sent")
198
199def mass_mail_sending_view(request):
200    m1 = mail.EmailMessage(
201        'First Test message',
202        'This is the first test email',
203        'from@example.com',
204        ['first@example.com', 'second@example.com'])
205    m2 = mail.EmailMessage(
206        'Second Test message',
207        'This is the second test email',
208        'from@example.com',
209        ['second@example.com', 'third@example.com'])
210
211    c = mail.get_connection()
212    c.send_messages([m1,m2])
213
214    return HttpResponse("Mail sent")