@json_view and @post_required decorators

This commit is contained in:
Jeff Balogh 2010-06-28 15:59:49 -07:00
Родитель 9f754c926a
Коммит 48e722729a
2 изменённых файлов: 77 добавлений и 0 удалений

33
apps/amo/decorators.py Normal file
Просмотреть файл

@ -0,0 +1,33 @@
import functools
import json
from django import http
def post_required(f):
@functools.wraps(f)
def wrapper(request, *args, **kw):
if request.method != 'POST':
return http.HttpResponseNotAllowed(['POST'])
else:
return f(request, *args, **kw)
return wrapper
def json_view(f):
@functools.wraps(f)
def wrapper(*args, **kw):
response = f(*args, **kw)
if isinstance(response, http.HttpResponse):
return response
else:
return http.HttpResponse(json.dumps(response),
content_type='application/json')
return wrapper
def _error(s):
return http.HttpResponseBadRequest(json.dumps(s),
content_type='application/json')
json_view.error = _error

Просмотреть файл

@ -0,0 +1,44 @@
from django import http
import mock
from nose.tools import eq_
from amo import decorators
def test_post_required():
f = lambda r: mock.sentinel.response
g = decorators.post_required(f)
request = mock.Mock()
request.method = 'GET'
assert isinstance(g(request), http.HttpResponseNotAllowed)
request.method = 'POST'
eq_(g(request), mock.sentinel.response)
def test_json_view():
"""Turns a Python object into a response."""
f = lambda r: {'x': 1}
response = decorators.json_view(f)(mock.Mock())
assert isinstance(response, http.HttpResponse)
eq_(response.content, '{"x": 1}')
eq_(response['Content-Type'], 'application/json')
def test_json_view_normal_response():
"""Normal responses get passed through."""
expected = http.HttpResponseForbidden()
f = lambda r: expected
response = decorators.json_view(f)(mock.Mock())
assert expected is response
eq_(response['Content-Type'], 'text/html; charset=utf-8')
def test_json_view_error():
"""json_view.error returns 400 responses."""
response = decorators.json_view.error({'msg': 'error'})
assert isinstance(response, http.HttpResponseBadRequest)
eq_(response.content, '{"msg": "error"}')
eq_(response['Content-Type'], 'application/json')