本文整理汇总了Python中djangorestframework.compat.RequestFactory.post方法的典型用法代码示例。如果您正苦于以下问题:Python RequestFactory.post方法的具体用法?Python RequestFactory.post怎么用?Python RequestFactory.post使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类djangorestframework.compat.RequestFactory
的用法示例。
在下文中一共展示了RequestFactory.post方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestMethodOverloading
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestMethodOverloading(TestCase):
def setUp(self):
self.req = RequestFactory()
def test_standard_behaviour_determines_GET(self):
"""GET requests identified"""
view = RequestMixin()
view.request = self.req.get('/')
self.assertEqual(view.method, 'GET')
def test_standard_behaviour_determines_POST(self):
"""POST requests identified"""
view = RequestMixin()
view.request = self.req.post('/')
self.assertEqual(view.method, 'POST')
def test_overloaded_POST_behaviour_determines_overloaded_method(self):
"""POST requests can be overloaded to another method by setting a reserved form field"""
view = RequestMixin()
view.request = self.req.post('/', {view._METHOD_PARAM: 'DELETE'})
self.assertEqual(view.method, 'DELETE')
def test_HEAD_is_a_valid_method(self):
"""HEAD requests identified"""
view = RequestMixin()
view.request = self.req.head('/')
self.assertEqual(view.method, 'HEAD')
示例2: UploadFilesTests
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class UploadFilesTests(TestCase):
"""Check uploading of files"""
def setUp(self):
self.factory = RequestFactory()
def test_upload_file(self):
class FileForm(forms.Form):
file = forms.FileField()
class MockView(View):
permissions = ()
form = FileForm
def post(self, request, *args, **kwargs):
return {'FILE_NAME': self.CONTENT['file'].name,
'FILE_CONTENT': self.CONTENT['file'].read()}
file = StringIO('stuff')
file.name = 'stuff.txt'
request = self.factory.post('/', {'file': file})
view = MockView.as_view()
response = view(request)
self.assertEquals(
json.loads(response.content),
json.loads('{"FILE_CONTENT": "stuff", "FILE_NAME": "stuff.txt"}')
)
示例3: TestRotation
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestRotation(TestCase):
"""For the example the maximum amount of Blogposts is capped off at views.MAX_POSTS.
Whenever a new Blogpost is posted the oldest one should be popped."""
def setUp(self):
self.factory = RequestFactory()
models.BlogPost.objects.all().delete()
def test_get_to_root(self):
'''Simple get to the *root* url of blogposts'''
request = self.factory.get('/blog-post')
view = ListOrCreateModelView.as_view(resource=urls.BlogPostResource)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_blogposts_not_exceed_MAX_POSTS(self):
'''Posting blog-posts should not result in more than MAX_POSTS items stored.'''
for post in range(models.MAX_POSTS + 5):
form_data = {'title': 'This is post #%s' % post, 'content': 'This is the content of post #%s' % post}
request = self.factory.post('/blog-post', data=form_data)
view = ListOrCreateModelView.as_view(resource=urls.BlogPostResource)
view(request)
self.assertEquals(len(models.BlogPost.objects.all()),models.MAX_POSTS)
def test_fifo_behaviour(self):
'''It's fine that the Blogposts are capped off at MAX_POSTS. But we want to make sure we see FIFO behaviour.'''
for post in range(15):
form_data = {'title': '%s' % post, 'content': 'This is the content of post #%s' % post}
request = self.factory.post('/blog-post', data=form_data)
view = ListOrCreateModelView.as_view(resource=urls.BlogPostResource)
view(request)
request = self.factory.get('/blog-post')
view = ListOrCreateModelView.as_view(resource=urls.BlogPostResource)
response = view(request)
response_posts = json.loads(response.content)
response_titles = [d['title'] for d in response_posts]
response_titles.reverse()
self.assertEquals(response_titles, ['%s' % i for i in range(models.MAX_POSTS - 5, models.MAX_POSTS + 5)])
示例4: TestPygmentsExample
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestPygmentsExample(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.temp_dir = tempfile.mkdtemp()
views.HIGHLIGHTED_CODE_DIR = self.temp_dir
def tearDown(self):
try:
shutil.rmtree(self.temp_dir)
except:
pass
def test_get_to_root(self):
'''Just do a get on the base url'''
request = self.factory.get('/pygments')
view = views.PygmentsRoot.as_view()
response = view(request)
self.assertEqual(response.status_code, 200)
def test_snippets_datetime_sorted(self):
'''Pygments examples should be datetime sorted'''
locations = []
for snippet in 'abcdefghij': # String length must not exceed views.MAX_FILES, otherwise test fails
form_data = {'code': '%s' % snippet, 'style':'friendly', 'lexer':'python'}
request = self.factory.post('/pygments', data=form_data)
view = views.PygmentsRoot.as_view()
response = view(request)
locations.append(response.items()[2][1])
import time
time.sleep(.1)
request = self.factory.get('/pygments')
view = views.PygmentsRoot.as_view()
response = view(request)
response_locations = json.loads(response.content)
self.assertEquals(locations, response_locations)
示例5: TestContentParsing
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestContentParsing(TestCase):
def setUp(self):
self.req = RequestFactory()
def ensure_determines_no_content_GET(self, view):
"""Ensure view.DATA returns None for GET request with no content."""
view.request = self.req.get('/')
self.assertEqual(view.DATA, None)
def ensure_determines_form_content_POST(self, view):
"""Ensure view.DATA returns content for POST request with form content."""
form_data = {'qwerty': 'uiop'}
view.parsers = (FormParser, MultiPartParser)
view.request = self.req.post('/', data=form_data)
self.assertEqual(view.DATA.items(), form_data.items())
def ensure_determines_non_form_content_POST(self, view):
"""Ensure view.RAW_CONTENT returns content for POST request with non-form content."""
content = 'qwerty'
content_type = 'text/plain'
view.parsers = (PlainTextParser,)
view.request = self.req.post('/', content, content_type=content_type)
self.assertEqual(view.DATA, content)
def ensure_determines_form_content_PUT(self, view):
"""Ensure view.RAW_CONTENT returns content for PUT request with form content."""
form_data = {'qwerty': 'uiop'}
view.parsers = (FormParser, MultiPartParser)
view.request = self.req.put('/', data=form_data)
self.assertEqual(view.DATA.items(), form_data.items())
def ensure_determines_non_form_content_PUT(self, view):
"""Ensure view.RAW_CONTENT returns content for PUT request with non-form content."""
content = 'qwerty'
content_type = 'text/plain'
view.parsers = (PlainTextParser,)
view.request = self.req.post('/', content, content_type=content_type)
self.assertEqual(view.DATA, content)
def test_standard_behaviour_determines_no_content_GET(self):
"""Ensure view.DATA returns None for GET request with no content."""
self.ensure_determines_no_content_GET(RequestMixin())
def test_standard_behaviour_determines_form_content_POST(self):
"""Ensure view.DATA returns content for POST request with form content."""
self.ensure_determines_form_content_POST(RequestMixin())
def test_standard_behaviour_determines_non_form_content_POST(self):
"""Ensure view.DATA returns content for POST request with non-form content."""
self.ensure_determines_non_form_content_POST(RequestMixin())
def test_standard_behaviour_determines_form_content_PUT(self):
"""Ensure view.DATA returns content for PUT request with form content."""
self.ensure_determines_form_content_PUT(RequestMixin())
def test_standard_behaviour_determines_non_form_content_PUT(self):
"""Ensure view.DATA returns content for PUT request with non-form content."""
self.ensure_determines_non_form_content_PUT(RequestMixin())
def test_overloaded_behaviour_allows_content_tunnelling(self):
"""Ensure request.DATA returns content for overloaded POST request"""
content = 'qwerty'
content_type = 'text/plain'
view = RequestMixin()
form_data = {view._CONTENT_PARAM: content,
view._CONTENTTYPE_PARAM: content_type}
view.request = self.req.post('/', form_data)
view.parsers = (PlainTextParser,)
self.assertEqual(view.DATA, content)
示例6: TestContentParsing
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestContentParsing(TestCase):
def setUp(self):
self.req = RequestFactory()
def ensure_determines_no_content_GET(self, view):
"""Ensure view.DATA returns None for GET request with no content."""
view.request = self.req.get("/")
self.assertEqual(view.DATA, None)
def ensure_determines_no_content_HEAD(self, view):
"""Ensure view.DATA returns None for HEAD request."""
view.request = self.req.head("/")
self.assertEqual(view.DATA, None)
def ensure_determines_form_content_POST(self, view):
"""Ensure view.DATA returns content for POST request with form content."""
form_data = {"qwerty": "uiop"}
view.parsers = (FormParser, MultiPartParser)
view.request = self.req.post("/", data=form_data)
self.assertEqual(view.DATA.items(), form_data.items())
def ensure_determines_non_form_content_POST(self, view):
"""Ensure view.RAW_CONTENT returns content for POST request with non-form content."""
content = "qwerty"
content_type = "text/plain"
view.parsers = (PlainTextParser,)
view.request = self.req.post("/", content, content_type=content_type)
self.assertEqual(view.DATA, content)
def ensure_determines_form_content_PUT(self, view):
"""Ensure view.RAW_CONTENT returns content for PUT request with form content."""
form_data = {"qwerty": "uiop"}
view.parsers = (FormParser, MultiPartParser)
view.request = self.req.put("/", data=form_data)
self.assertEqual(view.DATA.items(), form_data.items())
def ensure_determines_non_form_content_PUT(self, view):
"""Ensure view.RAW_CONTENT returns content for PUT request with non-form content."""
content = "qwerty"
content_type = "text/plain"
view.parsers = (PlainTextParser,)
view.request = self.req.post("/", content, content_type=content_type)
self.assertEqual(view.DATA, content)
def test_standard_behaviour_determines_no_content_GET(self):
"""Ensure view.DATA returns None for GET request with no content."""
self.ensure_determines_no_content_GET(RequestMixin())
def test_standard_behaviour_determines_no_content_HEAD(self):
"""Ensure view.DATA returns None for HEAD request."""
self.ensure_determines_no_content_HEAD(RequestMixin())
def test_standard_behaviour_determines_form_content_POST(self):
"""Ensure view.DATA returns content for POST request with form content."""
self.ensure_determines_form_content_POST(RequestMixin())
def test_standard_behaviour_determines_non_form_content_POST(self):
"""Ensure view.DATA returns content for POST request with non-form content."""
self.ensure_determines_non_form_content_POST(RequestMixin())
def test_standard_behaviour_determines_form_content_PUT(self):
"""Ensure view.DATA returns content for PUT request with form content."""
self.ensure_determines_form_content_PUT(RequestMixin())
def test_standard_behaviour_determines_non_form_content_PUT(self):
"""Ensure view.DATA returns content for PUT request with non-form content."""
self.ensure_determines_non_form_content_PUT(RequestMixin())
def test_overloaded_behaviour_allows_content_tunnelling(self):
"""Ensure request.DATA returns content for overloaded POST request"""
content = "qwerty"
content_type = "text/plain"
view = RequestMixin()
form_data = {view._CONTENT_PARAM: content, view._CONTENTTYPE_PARAM: content_type}
view.request = self.req.post("/", form_data)
view.parsers = (PlainTextParser,)
self.assertEqual(view.DATA, content)
def test_accessing_post_after_data_form(self):
"""Ensures request.POST can be accessed after request.DATA in form request"""
form_data = {"qwerty": "uiop"}
view = RequestMixin()
view.parsers = (FormParser, MultiPartParser)
view.request = self.req.post("/", data=form_data)
self.assertEqual(view.DATA.items(), form_data.items())
self.assertEqual(view.request.POST.items(), form_data.items())
def test_accessing_post_after_data_for_json(self):
"""Ensures request.POST can be accessed after request.DATA in json request"""
from django.utils import simplejson as json
data = {"qwerty": "uiop"}
content = json.dumps(data)
content_type = "application/json"
view = RequestMixin()
view.parsers = (JSONParser,)
view.request = self.req.post("/", content, content_type=content_type)
#.........这里部分代码省略.........
示例7: TestModelCreation
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestModelCreation(TestModelsTestCase):
"""Tests on CreateModelMixin"""
def setUp(self):
super(TestModelsTestCase, self).setUp()
self.req = RequestFactory()
def test_creation(self):
self.assertEquals(0, Group.objects.count())
class GroupResource(ModelResource):
model = Group
form_data = {'name': 'foo'}
request = self.req.post('/groups', data=form_data)
mixin = CreateModelMixin()
mixin.resource = GroupResource
mixin.CONTENT = form_data
response = mixin.post(request)
self.assertEquals(1, Group.objects.count())
self.assertEquals('foo', response.cleaned_content.name)
def test_creation_with_m2m_relation(self):
class UserResource(ModelResource):
model = User
def url(self, instance):
return "/users/%i" % instance.id
group = Group(name='foo')
group.save()
form_data = {
'username': 'bar',
'password': 'baz',
'groups': [group.id]
}
request = self.req.post('/groups', data=form_data)
cleaned_data = dict(form_data)
cleaned_data['groups'] = [group]
mixin = CreateModelMixin()
mixin.resource = UserResource
mixin.CONTENT = cleaned_data
response = mixin.post(request)
self.assertEquals(1, User.objects.count())
self.assertEquals(1, response.cleaned_content.groups.count())
self.assertEquals('foo', response.cleaned_content.groups.all()[0].name)
def test_creation_with_m2m_relation_through(self):
"""
Tests creation where the m2m relation uses a through table
"""
class UserResource(ModelResource):
model = CustomUser
def url(self, instance):
return "/customusers/%i" % instance.id
form_data = {'username': 'bar0', 'groups': []}
request = self.req.post('/groups', data=form_data)
cleaned_data = dict(form_data)
cleaned_data['groups'] = []
mixin = CreateModelMixin()
mixin.resource = UserResource
mixin.CONTENT = cleaned_data
response = mixin.post(request)
self.assertEquals(1, CustomUser.objects.count())
self.assertEquals(0, response.cleaned_content.groups.count())
group = Group(name='foo1')
group.save()
form_data = {'username': 'bar1', 'groups': [group.id]}
request = self.req.post('/groups', data=form_data)
cleaned_data = dict(form_data)
cleaned_data['groups'] = [group]
mixin = CreateModelMixin()
mixin.resource = UserResource
mixin.CONTENT = cleaned_data
response = mixin.post(request)
self.assertEquals(2, CustomUser.objects.count())
self.assertEquals(1, response.cleaned_content.groups.count())
self.assertEquals('foo1', response.cleaned_content.groups.all()[0].name)
group2 = Group(name='foo2')
group2.save()
form_data = {'username': 'bar2', 'groups': [group.id, group2.id]}
request = self.req.post('/groups', data=form_data)
cleaned_data = dict(form_data)
cleaned_data['groups'] = [group, group2]
mixin = CreateModelMixin()
mixin.resource = UserResource
mixin.CONTENT = cleaned_data
response = mixin.post(request)
#.........这里部分代码省略.........
示例8: TestPagination
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestPagination(TestCase):
def setUp(self):
self.req = RequestFactory()
def test_default_limit(self):
""" Tests if pagination works without overwriting the limit """
request = self.req.get('/paginator')
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(MockPaginatorView.total, content['total'])
self.assertEqual(MockPaginatorView.limit, content['per_page'])
self.assertEqual(list(range(0, MockPaginatorView.limit)), content['results'])
def test_overwriting_limit(self):
""" Tests if the limit can be overwritten """
limit = 10
request = self.req.get('/paginator')
response = MockPaginatorView.as_view(limit=limit)(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(content['per_page'], limit)
self.assertEqual(list(range(0, limit)), content['results'])
def test_limit_param(self):
""" Tests if the client can set the limit """
from math import ceil
limit = 5
num_pages = int(ceil(MockPaginatorView.total / float(limit)))
request = self.req.get('/paginator/?limit=%d' % limit)
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(MockPaginatorView.total, content['total'])
self.assertEqual(limit, content['per_page'])
self.assertEqual(num_pages, content['pages'])
def test_exceeding_limit(self):
""" Makes sure the client cannot exceed the default limit """
from math import ceil
limit = MockPaginatorView.limit + 10
num_pages = int(ceil(MockPaginatorView.total / float(limit)))
request = self.req.get('/paginator/?limit=%d' % limit)
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(MockPaginatorView.total, content['total'])
self.assertNotEqual(limit, content['per_page'])
self.assertNotEqual(num_pages, content['pages'])
self.assertEqual(MockPaginatorView.limit, content['per_page'])
def test_only_works_for_get(self):
""" Pagination should only work for GET requests """
request = self.req.post('/paginator', data={'content': 'spam'})
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(None, content.get('per_page'))
self.assertEqual('OK', content['status'])
def test_non_int_page(self):
""" Tests that it can handle invalid values """
request = self.req.get('/paginator/?page=spam')
response = MockPaginatorView.as_view()(request)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_page_range(self):
""" Tests that the page range is handle correctly """
request = self.req.get('/paginator/?page=0')
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
request = self.req.get('/paginator/')
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(list(range(0, MockPaginatorView.limit)), content['results'])
num_pages = content['pages']
request = self.req.get('/paginator/?page=%d' % num_pages)
#.........这里部分代码省略.........
示例9: TestPagination
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestPagination(TestCase):
def setUp(self):
self.req = RequestFactory()
def test_default_limit(self):
""" Tests if pagination works without overwriting the limit """
request = self.req.get('/paginator')
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.OK)
self.assertEqual(MockPaginatorView.total, content['total'])
self.assertEqual(MockPaginatorView.limit, content['per_page'])
self.assertEqual(range(0, MockPaginatorView.limit), content['results'])
def test_overwriting_limit(self):
""" Tests if the limit can be overwritten """
limit = 10
request = self.req.get('/paginator')
response = MockPaginatorView.as_view(limit=limit)(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.OK)
self.assertEqual(content['per_page'], limit)
self.assertEqual(range(0, limit), content['results'])
def test_limit_param(self):
""" Tests if the client can set the limit """
from math import ceil
limit = 5
num_pages = int(ceil(MockPaginatorView.total / float(limit)))
request = self.req.get('/paginator/?limit=%d' % limit)
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.OK)
self.assertEqual(MockPaginatorView.total, content['total'])
self.assertEqual(limit, content['per_page'])
self.assertEqual(num_pages, content['pages'])
def test_exceeding_limit(self):
""" Makes sure the client cannot exceed the default limit """
from math import ceil
limit = MockPaginatorView.limit + 10
num_pages = int(ceil(MockPaginatorView.total / float(limit)))
request = self.req.get('/paginator/?limit=%d' % limit)
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.OK)
self.assertEqual(MockPaginatorView.total, content['total'])
self.assertNotEqual(limit, content['per_page'])
self.assertNotEqual(num_pages, content['pages'])
self.assertEqual(MockPaginatorView.limit, content['per_page'])
def test_only_works_for_get(self):
""" Pagination should only work for GET requests """
request = self.req.post('/paginator', data={'content': 'spam'})
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.CREATED)
self.assertEqual(None, content.get('per_page'))
self.assertEqual('OK', content['status'])
def test_non_int_page(self):
""" Tests that it can handle invalid values """
request = self.req.get('/paginator/?page=spam')
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.NOT_FOUND)
def test_page_range(self):
""" Tests that the page range is handle correctly """
request = self.req.get('/paginator/?page=0')
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.NOT_FOUND)
request = self.req.get('/paginator/')
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.OK)
self.assertEqual(range(0, MockPaginatorView.limit), content['results'])
num_pages = content['pages']
#.........这里部分代码省略.........
示例10: TestContentParsing
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestContentParsing(TestCase):
def setUp(self):
self.req = RequestFactory()
def ensure_determines_no_content_GET(self, view):
"""Ensure view.DATA returns None for GET request with no content."""
view.request = self.req.get("/")
self.assertEqual(view.DATA, None)
def ensure_determines_no_content_HEAD(self, view):
"""Ensure view.DATA returns None for HEAD request."""
view.request = self.req.head("/")
self.assertEqual(view.DATA, None)
def ensure_determines_form_content_POST(self, view):
"""Ensure view.DATA returns content for POST request with form content."""
form_data = {"qwerty": "uiop"}
view.parsers = (FormParser, MultiPartParser)
view.request = self.req.post("/", data=form_data)
self.assertEqual(list(view.DATA.items()), list(form_data.items()))
def ensure_determines_non_form_content_POST(self, view):
"""Ensure view.RAW_CONTENT returns content for POST request with non-form content."""
content = "qwerty"
content_type = "text/plain"
view.parsers = (PlainTextParser,)
view.request = self.req.post("/", content, content_type=content_type)
self.assertEqual(view.DATA, content)
def ensure_determines_form_content_PUT(self, view):
"""Ensure view.RAW_CONTENT returns content for PUT request with form content."""
form_data = {"qwerty": "uiop"}
view.parsers = (FormParser, MultiPartParser)
view.request = self.req.put("/", data=urlencode(form_data), content_type="application/x-www-form-urlencoded")
self.assertEqual(view.DATA, {"qwerty": ["uiop"]})
def ensure_determines_non_form_content_PUT(self, view):
"""Ensure view.RAW_CONTENT returns content for PUT request with non-form content."""
content = "qwerty"
content_type = "text/plain"
view.parsers = (PlainTextParser,)
view.request = self.req.post("/", content, content_type=content_type)
self.assertEqual(view.DATA, content)
def test_standard_behaviour_determines_no_content_GET(self):
"""Ensure view.DATA returns None for GET request with no content."""
self.ensure_determines_no_content_GET(RequestMixin())
def test_standard_behaviour_determines_no_content_HEAD(self):
"""Ensure view.DATA returns None for HEAD request."""
self.ensure_determines_no_content_HEAD(RequestMixin())
def test_standard_behaviour_determines_form_content_POST(self):
"""Ensure view.DATA returns content for POST request with form content."""
self.ensure_determines_form_content_POST(RequestMixin())
def test_standard_behaviour_determines_non_form_content_POST(self):
"""Ensure view.DATA returns content for POST request with non-form content."""
self.ensure_determines_non_form_content_POST(RequestMixin())
# def test_standard_behaviour_determines_form_content_PUT(self):
# """Ensure view.DATA returns content for PUT request with form content."""
# self.ensure_determines_form_content_PUT(RequestMixin())
def test_standard_behaviour_determines_non_form_content_PUT(self):
"""Ensure view.DATA returns content for PUT request with non-form content."""
self.ensure_determines_non_form_content_PUT(RequestMixin())
def test_overloaded_behaviour_allows_content_tunnelling(self):
"""Ensure request.DATA returns content for overloaded POST request"""
content = "qwerty"
content_type = "text/plain"
view = RequestMixin()
form_data = {view._CONTENT_PARAM: content, view._CONTENTTYPE_PARAM: content_type}
view.request = self.req.post("/", form_data)
view.parsers = (PlainTextParser,)
self.assertEqual(view.DATA, content)
def test_accessing_post_after_data_form(self):
"""Ensures request.POST can be accessed after request.DATA in form request"""
form_data = {"qwerty": "uiop"}
view = RequestMixin()
view.parsers = (FormParser, MultiPartParser)
view.request = self.req.post("/", data=form_data)
self.assertEqual(list(view.DATA.items()), list(form_data.items()))
self.assertEqual(list(view.request.POST.items()), list(form_data.items()))
@unittest.skip("This test was disabled some time ago for some reason")
def test_accessing_post_after_data_for_json(self):
"""Ensures request.POST can be accessed after request.DATA in json request"""
import json
data = {"qwerty": "uiop"}
content = json.dumps(data)
content_type = "application/json"
view = RequestMixin()
view.parsers = (JSONParser,)
#.........这里部分代码省略.........
示例11: TestPagination
# 需要导入模块: from djangorestframework.compat import RequestFactory [as 别名]
# 或者: from djangorestframework.compat.RequestFactory import post [as 别名]
class TestPagination(TestCase):
def setUp(self):
self.req = RequestFactory()
def test_default_limit(self):
""" Tests if pagination works without overwriting the limit """
request = self.req.get("/paginator")
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(MockPaginatorView.total, content["total"])
self.assertEqual(MockPaginatorView.limit, content["per_page"])
self.assertEqual(range(0, MockPaginatorView.limit), content["results"])
def test_overwriting_limit(self):
""" Tests if the limit can be overwritten """
limit = 10
request = self.req.get("/paginator")
response = MockPaginatorView.as_view(limit=limit)(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(content["per_page"], limit)
self.assertEqual(range(0, limit), content["results"])
def test_limit_param(self):
""" Tests if the client can set the limit """
from math import ceil
limit = 5
num_pages = int(ceil(MockPaginatorView.total / float(limit)))
request = self.req.get("/paginator/?limit=%d" % limit)
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(MockPaginatorView.total, content["total"])
self.assertEqual(limit, content["per_page"])
self.assertEqual(num_pages, content["pages"])
def test_exceeding_limit(self):
""" Makes sure the client cannot exceed the default limit """
from math import ceil
limit = MockPaginatorView.limit + 10
num_pages = int(ceil(MockPaginatorView.total / float(limit)))
request = self.req.get("/paginator/?limit=%d" % limit)
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(MockPaginatorView.total, content["total"])
self.assertNotEqual(limit, content["per_page"])
self.assertNotEqual(num_pages, content["pages"])
self.assertEqual(MockPaginatorView.limit, content["per_page"])
def test_only_works_for_get(self):
""" Pagination should only work for GET requests """
request = self.req.post("/paginator", data={"content": "spam"})
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(None, content.get("per_page"))
self.assertEqual("OK", content["status"])
def test_non_int_page(self):
""" Tests that it can handle invalid values """
request = self.req.get("/paginator/?page=spam")
response = MockPaginatorView.as_view()(request)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_page_range(self):
""" Tests that the page range is handle correctly """
request = self.req.get("/paginator/?page=0")
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
request = self.req.get("/paginator/")
response = MockPaginatorView.as_view()(request)
content = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(range(0, MockPaginatorView.limit), content["results"])
num_pages = content["pages"]
request = self.req.get("/paginator/?page=%d" % num_pages)
#.........这里部分代码省略.........