def test_post_accessed_in_post_method_with_json_parser(self): django_request = self.factory.post('/', {'foo': 'bar'}) request = Request(django_request, parsers=[JSONParser()]) django_request.POST assert request.POST == {} assert request.data == {}
def retrieve(self, request, pk): album = self.queryset.get(pk=pk) serializer_context = {'request': Request(request._request)} return Response(AlbumByIdSerializer(album, context=serializer_context).data, 200)
def test_views_method_test_3(self): obj = GenericMessagesMessageCreateView() request = Request(HttpRequest()) request.user = self.user self.assertRaises(GenericMessagesService.NoConfiguration, obj.post, request)
def get_fake_request(): django_request = HttpRequest() django_request.META['SERVER_NAME'] = 'localhost.localdomain' django_request.META['SERVER_PORT'] = 80 return Request(django_request)
def get_mock_request(): factory = APIRequestFactory() request = factory.get('/') return Request(request)
def create_request(path): factory = RequestFactory() request = Request(factory.get(path)) return request
def test_get_cache_key_returns_correct_value(self): request = Request(HttpRequest()) cache_key = self.throttle.get_cache_key(request, view={}) assert cache_key == 'throttle_anon_None'
def _mock_get_request(self, url): return Request(self.request_factory.get(url))
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase from rest_framework.request import Request from properties.models import Property from appointments.models import OpenHouse, OpenHouseRSVP, OwnerAvailability, AppointmentRequest from rest_framework.test import APIRequestFactory from django.utils import timezone factory = APIRequestFactory() request = factory.get('/') serializer_context = { 'request': Request(request), } class CreateOpenHouseTest(APITestCase): def setUp(self): self.superuser = User.objects.create_superuser('john', '*****@*****.**', 'johnpassword') self.client.login(username='******', password='******') self.property = Property.objects.create(property_title='test_Property') self.date = timezone.now() self.start_time = timezone.now() self.end_time = timezone.now() self.data = { 'property': reverse('property-detail', args=[self.property.id]),
def test_request_admin(self): self.add_group_user(self.profile, 'Admins') ok_(not self.auth.authenticate(Request(self.call())))
def test_request_has_role(self): self.add_group_user(self.profile, 'App Reviewers') ok_(self.auth.authenticate(Request(self.call())))
def test_accepted(self): req = Request(self.call()) eq_(self.auth.authenticate(req), (self.profile, None))
def test_validate_body_custom_fields(): factory = APIRequestFactory() registry = TemporaryTypeRegistry() registry.register(TemporaryInstanceType1()) registry.register(TemporaryInstanceType2()) request = Request(factory.post( '/some-page/', data=json.dumps({'missing': 'type'}), content_type='application/json' ), parsers=[JSONParser()]) func = MagicMock() with pytest.raises(APIException) as api_exception_1: validate_body_custom_fields( registry, 'serializer_class')(func)(*[object, request]) assert api_exception_1.value.detail['error'] == 'ERROR_REQUEST_BODY_VALIDATION' assert api_exception_1.value.detail['detail']['type'][0]['error'] == \ 'This field is required.' assert api_exception_1.value.detail['detail']['type'][0]['code'] == 'required' assert api_exception_1.value.status_code == status.HTTP_400_BAD_REQUEST request = Request(factory.post( '/some-page/', data=json.dumps({'type': 'NOT_EXISTING'}), content_type='application/json' ), parsers=[JSONParser()]) func = MagicMock() with pytest.raises(APIException) as api_exception_2: validate_body_custom_fields(registry)(func)(*[object, request]) assert api_exception_2.value.detail['error'] == 'ERROR_REQUEST_BODY_VALIDATION' assert api_exception_2.value.detail['detail']['type'][0]['error'] == \ '"NOT_EXISTING" is not a valid choice.' assert api_exception_2.value.detail['detail']['type'][0]['code'] == 'invalid_choice' assert api_exception_2.value.status_code == status.HTTP_400_BAD_REQUEST request = Request(factory.post( '/some-page/', data=json.dumps({'type': 'temporary_2'}), content_type='application/json' ), parsers=[JSONParser()]) func = MagicMock() with pytest.raises(APIException) as api_exception_3: validate_body_custom_fields(registry)(func)(*[object, request]) assert api_exception_3.value.detail['error'] == 'ERROR_REQUEST_BODY_VALIDATION' assert api_exception_3.value.detail['detail']['name'][0]['error'] == \ 'This field is required.' assert api_exception_3.value.detail['detail']['name'][0]['code'] == 'required' assert api_exception_3.value.status_code == status.HTTP_400_BAD_REQUEST request = Request(factory.post( '/some-page/', data=json.dumps({'type': 'temporary_1'}), content_type='application/json' ), parsers=[JSONParser()]) func = MagicMock() with pytest.raises(APIException) as api_exception_4: validate_body_custom_fields( registry, base_serializer_class=TemporaryBaseModelSerializer )(func)(*[object, request]) assert api_exception_4.value.detail['error'] == 'ERROR_REQUEST_BODY_VALIDATION' assert api_exception_4.value.detail['detail']['name'][0]['error'] == \ 'This field is required.' assert api_exception_4.value.detail['detail']['name'][0]['code'] == 'required' assert api_exception_4.value.status_code == status.HTTP_400_BAD_REQUEST request = Request(factory.post( '/some-page/', data=json.dumps({'type': 'temporary_2', 'name': 'test1'}), content_type='application/json' ), parsers=[JSONParser()]) func = MagicMock() with pytest.raises(APIException) as api_exception_5: validate_body_custom_fields(registry)(func)(*[object, request]) assert api_exception_5.value.detail['error'] == 'ERROR_REQUEST_BODY_VALIDATION' assert api_exception_5.value.detail['detail']['name'][0]['error'] == \ 'A valid integer is required.' assert api_exception_5.value.detail['detail']['name'][0]['code'] == 'invalid' assert api_exception_5.value.status_code == status.HTTP_400_BAD_REQUEST request = Request(factory.post( '/some-page/', data=json.dumps({'type': 'temporary_2', 'name': 123}), content_type='application/json' ), parsers=[JSONParser()]) func = MagicMock() validate_body_custom_fields(registry)(func)(*[object, request])
def test_get_request_data(self): data = '{"a":"b"}' post = self.factory.post('/', data, content_type='application/json') request = Request(post, parsers=[JSONParser()]) assert get_request_data(request) == {'a': 'b'}
def test_invalid_cursor(self): request = Request(factory.get('/', {'cursor': '123'})) with pytest.raises(exceptions.NotFound): self.pagination.paginate_queryset(self.queryset, request)
def test_auth_can_be_set(self): request = Request(factory.get('/')) request.auth = 'DUMMY' assert request.auth == 'DUMMY'
def drf_request(api_request) -> Request: """The wrapped WSGI Request as a Django-Rest-Framework request. This is the 'request' object that APIView.dispatch() creates. """ return Request(api_request)
def test_default_secure_false(self): request = Request(factory.get('/', secure=False)) assert request.scheme == 'http'
def test_authenticated_user_not_affected(self): request = Request(HttpRequest()) user = User.objects.create(username='******') force_authenticate(request, user) request.user = user assert self.throttle.get_cache_key(request, view={}) is None
def test_default_secure_true(self): request = Request(factory.get('/', secure=True)) assert request.scheme == 'https'
def _get_view(self, kwargs): factory = APIRequestFactory() request = Request( factory.get("", content_type="application/vnd.api+json")) return AuthorViewSet(request=request, kwargs=kwargs)
def test_repr(self): http_request = factory.get('/path') request = Request(http_request) assert repr(request) == "<rest_framework.request.Request: GET '/path'>"
def test_get_attribute_request_GET(self): request = Request(self.factory.get('/')) mock_serializer = Serializer() mock_serializer.context = {'request': request} field = self.field_class() self._test_expected_dict(field)
def test_standard_behaviour_determines_no_content_HEAD(self): """ Ensure request.data returns empty QueryDict for HEAD request. """ request = Request(factory.head('/')) assert request.data == {}
def get_serializer(self, **kwargs): serializer = JSONWebTokenSerializer(**kwargs) serializer.context['request'] = Request(HttpRequest()), return serializer
def test_invalid_page(self): request = Request(factory.get('/', {'page': 'invalid'})) with pytest.raises(exceptions.NotFound): self.paginate_queryset(request)
def test_schema_for_regular_views(self): """ Ensure that schema generation works for ViewSet classes with method limitation by Django CBV's http_method_names attribute """ generator = SchemaGenerator(title='Example API', patterns=self.patterns) request = factory.get('/example1/') schema = generator.get_schema(Request(request)) expected = coreapi.Document( url='http://testserver/example1/', title='Example API', content={ 'example1': { 'list': coreapi.Link( url='/example1/', action='get', fields=[ coreapi.Field( 'page', required=False, location='query', schema=coreschema.Integer( title='Page', description= 'A page number within the paginated result set.' )), coreapi.Field( 'page_size', required=False, location='query', schema=coreschema.Integer( title='Page size', description= 'Number of results to return per page.')), coreapi.Field( 'ordering', required=False, location='query', schema=coreschema.String( title='Ordering', description= 'Which field to use when ordering the results.' )) ]), 'custom_list_action': coreapi.Link(url='/example1/custom_list_action/', action='get'), 'custom_list_action_multiple_methods': { 'read': coreapi.Link( url= '/example1/custom_list_action_multiple_methods/', action='get') }, 'read': coreapi.Link( url='/example1/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()), coreapi.Field( 'ordering', required=False, location='query', schema=coreschema.String( title='Ordering', description= 'Which field to use when ordering the results.' )) ]) } }) assert schema == expected
def test_erronous_offset(self): request = Request(factory.get('/', {'limit': 5, 'offset': 1000})) queryset = self.paginate_queryset(request) self.get_paginated_content(queryset) self.get_html_context()
def get_user_info(request: Request) -> User: return JSONWebTokenAuthentication().authenticate(Request(request))[0]
def setUp(self): self.request = Request(RequestFactory().get('/'))