Python rest_framework.test.APIRequestFactory() Examples
The following are 30
code examples of rest_framework.test.APIRequestFactory().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.test
, or try the search function
.
Example #1
Source File: test_permissions.py From figures with MIT License | 6 votes |
def test_multiple_user_orgs(self, monkeypatch, settings, username, allow): """ We updated `figures.permissions` so that a user can belong to multiple organizations """ def test_site(request): return self.site request = APIRequestFactory().get('/') request.META['HTTP_HOST'] = self.site.domain request.user = get_user_model().objects.get(username=username) monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', test_site) settings.FEATURES['FIGURES_IS_MULTISITE'] = True assert figures.helpers.is_multisite() org2 = OrganizationFactory(sites=[self.site]) UserOrganizationMappingFactory(user=request.user, organization=org2) permission = figures.permissions.IsSiteAdminUser().has_permission(request, None) assert permission == allow, 'User "{username}" should have access'.format( username=username)
Example #2
Source File: test_site_monthly_metrics_viewset.py From figures with MIT License | 6 votes |
def test_course_enrollments(self, monkeypatch, user_reg_test_data): endpoint = 'course_enrollments' request_method = 'get' site = user_reg_test_data['site'] users = user_reg_test_data['users'] dates = user_reg_test_data['dates'] months_back = user_reg_test_data['months_back'] if organizations_support_sites(): caller = UserFactory(is_staff=True) map_users_to_org_site(caller=caller, site=site, users=users) else: caller = UserFactory(is_staff=True) request = APIRequestFactory().get(self.request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({request_method: endpoint}) response = view(request) assert self.check_response(response=response, endpoint=endpoint)
Example #3
Source File: test_site_monthly_metrics_viewset.py From figures with MIT License | 6 votes |
def test_active_users(self, monkeypatch, user_reg_test_data): endpoint = 'active_users' request_method = 'get' site = user_reg_test_data['site'] if organizations_support_sites(): caller = UserFactory(is_staff=True) map_users_to_org_site(caller=caller, site=site, users=[]) else: caller = UserFactory(is_staff=True) expected_response = 'active_users history metric data' monkeypatch.setattr('figures.views.metrics.get_site_mau_history_metrics', lambda **_kwargs: expected_response) request = APIRequestFactory().get(self.request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({request_method: endpoint}) response = view(request) assert response.data['active_users'] == expected_response
Example #4
Source File: test_mau_views.py From figures with MIT License | 6 votes |
def test_list(self, monkeypatch, sm_test_data): site = sm_test_data['site'] org = sm_test_data['organization'] if organizations_support_sites(): caller = UserFactory() UserOrganizationMappingFactory(user=caller, organization=org, is_amc_admin=True) else: caller = UserFactory(is_staff=True) request = APIRequestFactory().get(self.request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({'get': 'list'}) response = view(request) assert response.status_code == status.HTTP_200_OK
Example #5
Source File: test_mau_views.py From figures with MIT License | 6 votes |
def test_list(self, monkeypatch, sm_test_data): monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) site = sm_test_data['site'] org = sm_test_data['organization'] co = sm_test_data['course_overviews'][0] if organizations_support_sites(): caller = UserFactory() UserOrganizationMappingFactory(user=caller, organization=org, is_amc_admin=True) else: caller = UserFactory(is_staff=True) request_path = self.request_path request = APIRequestFactory().get(request_path) request.META['HTTP_HOST'] = site.domain force_authenticate(request, user=caller) view = self.view_class.as_view({'get': 'list'}) response = view(request) assert response.status_code == status.HTTP_200_OK # TODO: Assert data are correct
Example #6
Source File: test_mau_views.py From figures with MIT License | 6 votes |
def test_site_metrics_list(self, monkeypatch, sm_test_data): site = sm_test_data['site'] org = sm_test_data['organization'] if organizations_support_sites(): caller = UserFactory() UserOrganizationMappingFactory(user=caller, organization=org, is_amc_admin=True) else: caller = UserFactory(is_staff=True) request = APIRequestFactory().get(self.request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({'get': 'list'}) response = view(request) assert response.status_code == status.HTTP_200_OK
Example #7
Source File: test_site_monthly_metrics_viewset.py From figures with MIT License | 6 votes |
def test_site_courses(self, monkeypatch, user_reg_test_data): endpoint = 'site_courses' request_method = 'get' site = user_reg_test_data['site'] users = user_reg_test_data['users'] dates = user_reg_test_data['dates'] months_back = user_reg_test_data['months_back'] if organizations_support_sites(): caller = UserFactory(is_staff=True) map_users_to_org_site(caller=caller, site=site, users=users) else: caller = UserFactory(is_staff=True) request = APIRequestFactory().get(self.request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({request_method: endpoint}) response = view(request) assert self.check_response(response=response, endpoint=endpoint)
Example #8
Source File: test_course_monthly_metrics_viewset.py From figures with MIT License | 6 votes |
def test_list_method(self, monkeypatch, course_test_data): """ We need to add pagination to the list method and add that to the test """ site = course_test_data['site'] users = course_test_data['users'] course_overview = course_test_data['course_overview'] if organizations_support_sites(): caller = UserFactory(is_staff=True) map_users_to_org_site(caller=caller, site=site, users=users) else: caller = UserFactory(is_staff=True) request = APIRequestFactory().get(self.base_request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({'get': 'list'}) response = view(request) assert response.status_code == status.HTTP_200_OK
Example #9
Source File: test_site_monthly_metrics_viewset.py From figures with MIT License | 6 votes |
def test_course_completions(self, monkeypatch, user_reg_test_data): endpoint = 'course_completions' request_method = 'get' site = user_reg_test_data['site'] users = user_reg_test_data['users'] dates = user_reg_test_data['dates'] months_back = user_reg_test_data['months_back'] if organizations_support_sites(): caller = UserFactory(is_staff=True) map_users_to_org_site(caller=caller, site=site, users=users) else: caller = UserFactory(is_staff=True) request = APIRequestFactory().get(self.request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({request_method: endpoint}) response = view(request) assert self.check_response(response=response, endpoint=endpoint)
Example #10
Source File: test_serializers.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def test_password_contains_username_case_insensitive(self): user = UserFactory.create( password=BASIC_TEST_DATA['password'], username='imagine71', ) request = APIRequestFactory().patch('/user/imagine71', {}) force_authenticate(request, user=user) data = { 'username': 'imagine71', 'current_password': BASIC_TEST_DATA['password'], 'new_password': 'LetsIMAGINE71!12345', 're_new_password': 'LetsIMAGINE71!12345', } serializer = serializers.ChangePasswordSerializer( user, data=data, context={'request': Request(request)}) assert serializer.is_valid() is False assert (_("The password is too similar to the username.") in serializer._errors['new_password'])
Example #11
Source File: test_serializers.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def test_user_can_not_change_pw(self): user = UserFactory.create(password='beatles4Lyfe!', update_profile=False) request = APIRequestFactory().patch('/user/imagine71', {}) force_authenticate(request, user=user) data = { 'current_password': 'beatles4Lyfe!', 'new_password': 'iloveyoko79!', 're_new_password': 'iloveyoko79!' } serializer = serializers.ChangePasswordSerializer( user, data=data, context={'request': Request(request)} ) assert serializer.is_valid() is False assert ("The password for this user can not be changed." in serializer.errors['non_field_errors'])
Example #12
Source File: test_course_monthly_metrics_viewset.py From figures with MIT License | 6 votes |
def test_retrieve_method(self, monkeypatch, course_test_data): site = course_test_data['site'] users = course_test_data['users'] course_overview = course_test_data['course_overview'] if organizations_support_sites(): caller = UserFactory(is_staff=True) map_users_to_org_site(caller=caller, site=site, users=users) else: caller = UserFactory(is_staff=True) request_path = self.base_request_path request = APIRequestFactory().get(request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({'get': 'retrieve'}) response = view(request, pk=str(course_overview.id)) assert response.status_code == status.HTTP_200_OK
Example #13
Source File: test_course_monthly_metrics_viewset.py From figures with MIT License | 6 votes |
def test_retrieve_invalid_course_id(self, monkeypatch, course_test_data, invalid_course_id): """Tests that invalid course ids return '404 NOT FOUND' """ site = course_test_data['site'] users = course_test_data['users'] if organizations_support_sites(): caller = UserFactory(is_staff=True) map_users_to_org_site(caller=caller, site=site, users=users) else: caller = UserFactory(is_staff=True) request_path = self.base_request_path request = APIRequestFactory().get(request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({'get': 'retrieve'}) response = view(request, pk=invalid_course_id) assert response.status_code == status.HTTP_404_NOT_FOUND
Example #14
Source File: test_mau_views.py From figures with MIT License | 6 votes |
def test_site_metrics_list(self, monkeypatch, sm_test_data): site = sm_test_data['site'] org = sm_test_data['organization'] if organizations_support_sites(): caller = UserFactory() UserOrganizationMappingFactory(user=caller, organization=org, is_amc_admin=True) else: caller = UserFactory(is_staff=True) request = APIRequestFactory().get(self.request_path) request.META['HTTP_HOST'] = site.domain monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', lambda req: site) force_authenticate(request, user=caller) view = self.view_class.as_view({'get': 'list'}) response = view(request) assert response.status_code == status.HTTP_200_OK
Example #15
Source File: test_serializers.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def test_update_insensitive_email_check(self): UserFactory.create(email='sherlock.holmes@bbc.uk') user = UserFactory.create(username='sherlock', email='test@example.com', password='221B@bakerstreet') data = { 'username': 'sherlock', 'email': 'SHERLOCK.HOLMES@BBC.UK', 'password': '221B@bakerstreet', 'full_name': 'John Lennon', 'last_login': '2016-01-01 23:00:00', 'language': 'en', 'measurement': 'metric', } request = APIRequestFactory().patch('/user/sherlock', data) force_authenticate(request, user=user) serializer = serializers.UserSerializer( user, data=data, context={'request': Request(request)}) assert serializer.is_valid() is False assert (_("User with this Email address already exists.") in serializer.errors['email'])
Example #16
Source File: test_sites_view.py From figures with MIT License | 6 votes |
def test_get(self, query_params, filter_args): qp_msg = 'query_params={query_params}' expected_data = Site.objects.filter(**filter_args) request = APIRequestFactory().get(self.request_path + query_params) request.user = self.staff_user view = self.view_class.as_view({'get': 'list'}) response = view(request) assert response.status_code == 200, qp_msg.format(query_params=query_params) assert set(response.data.keys()) == set( ['count', 'next', 'previous', 'results']) assert len(response.data['results']) == len(expected_data), qp_msg.format( query_params=query_params) results = response.data['results'] # Validate just the first object's structure for field_name in self.expected_result_keys: assert field_name in results[0] # Validate the ids match up expected_ids = expected_data.values_list('id', flat=True) actual_ids = [o['id'] for o in results] assert set(actual_ids) == set(expected_ids)
Example #17
Source File: test_serializers.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def test_update_phone_fails(self): data = BASIC_TEST_DATA.copy() del data['email'] data['phone'] = '+12345678990' serializer = serializers.UserSerializer(data=data) assert serializer.is_valid() is True user = serializer.save() other_user = UserFactory.create() update_data = {'phone': '+919067439937'} request = APIRequestFactory().patch('/user/imagine71', update_data) force_authenticate(request, user=other_user) serializer2 = serializers.UserSerializer( user, update_data, context={'request': Request(request)} ) assert serializer2.is_valid() is False assert (_("Cannot update phone") in serializer2.errors['phone'])
Example #18
Source File: test_api_view_serializer_class_getter.py From django-rest-registration with MIT License | 6 votes |
def test_browsable_renderer_put_render(input_put_view, decorator): """ Test, that PUT method works with BrowsableAPIRenderer This was not working in the past, because of `_get_serializer` didn't allow `instance parameter. """ data = {'blah': 'blah'} method = 'PUT' request = rest_request.Request(APIRequestFactory().get('blah')) output_view = decorator(input_put_view) wrapper_cls = _get_view_class(output_view) test_view_instance = wrapper_cls() renderer = renderers.BrowsableAPIRenderer() renderer.accepted_media_type = None renderer.renderer_context = {} response = renderer.get_raw_data_form( data, test_view_instance, method, request, ) assert response.data == {}
Example #19
Source File: test_serializers.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def test_update_email_fails(self): serializer = serializers.UserSerializer(data=BASIC_TEST_DATA) assert serializer.is_valid() is True user = serializer.save() other_user = UserFactory.create() update_data = {'email': 'sherlock.holmes@bbc.uk'} request = APIRequestFactory().patch('/user/imagine71', update_data) force_authenticate(request, user=other_user) serializer2 = serializers.UserSerializer( user, update_data, context={'request': Request(request)} ) assert serializer2.is_valid() is False assert (_("Cannot update email") in serializer2.errors['email'])
Example #20
Source File: test_serializers.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def test_update_with_blank_phone_and_email(self): user = UserFactory.create(username='sherlock', email='sherlock.holmes@bbc.uk', password='221B@bakerstreet', full_name='Sherlock Holmes') data = { 'username': 'sherlock', 'email': '', 'phone': '', 'language': 'en', 'measurement': 'metric', 'password': '221B@bakerstreet', 'full_name': 'Sherlock Holmes' } request = APIRequestFactory().patch('/user/sherlock', data) force_authenticate(request, user=user) serializer = serializers.UserSerializer( user, data=data, context={'request': Request(request)}, partial=True ) assert serializer.is_valid() is False assert (_("You cannot leave both phone and email empty.") in serializer.errors['non_field_errors'])
Example #21
Source File: test_serializers.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def test_update_with_restricted_username(self): serializer = serializers.UserSerializer(data=BASIC_TEST_DATA) assert serializer.is_valid() is True user = serializer.save() invalid_usernames = ('add', 'ADD', 'Add', 'new', 'NEW', 'New') data = { 'username': random.choice(invalid_usernames), 'email': 'john@beatles.uk', 'full_name': 'John Lennon', } request = APIRequestFactory().patch('/user/imagine71', data) force_authenticate(request, user=user) serializer2 = serializers.UserSerializer( user, data=data, context={'request': Request(request)} ) assert serializer2.is_valid() is False assert serializer2.errors['username'] == [ _("Username cannot be “add” or “new”.")]
Example #22
Source File: test_serializers.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def test_case_insensitive_username(self): data = { 'username': 'USERtwO', 'email': 'john@beatles.uk', 'phone': '+919327768250', 'password': 'iloveyoko79', 'full_name': 'John Lennon' } usernames = ['UsErOne', 'useRtWo', 'uSERthReE'] users = [ UserFactory.create(username=username) for username in usernames] request = APIRequestFactory().patch( '/user/userone', data) force_authenticate(request, user=users[0]) serializer = serializers.UserSerializer( users[0], data, context={'request': Request(request)}) assert serializer.is_valid() is False assert serializer.errors['username'] == [ _("A user with that username already exists") ]
Example #23
Source File: test_serializers.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def test_update_not_allowed(self): user = UserFactory.create(username='imagine71', update_profile=False, password='sgt-pepper', phone=None, phone_verified=False) data = { 'username': 'imagine72', 'password': 'sgt-pepper', } request = APIRequestFactory().patch('/user/imagine71', data) force_authenticate(request, user=user) serializer = serializers.UserSerializer( user, data, context={'request': Request(request)}) assert serializer.is_valid() is False assert (serializer.errors['non_field_errors'] == ['The profile for this user can not be updated.'])
Example #24
Source File: test_backend.py From drf-mongo-filters with GNU General Public License v2.0 | 6 votes |
def test_model_mismatch(self): """ cannot apply filters for one model to queryset from another """ class FooDoc(Document): foo = fields.StringField() class BarDoc(Document): bar = fields.StringField() class FooFilter(ModelFilterset): class Meta: model = FooDoc class BarView(ListAPIView): filter_backends = (MongoFilterBackend,) filter_class = FooFilter serializer_class = mock.Mock() queryset = BarDoc.objects with self.assertRaises(TypeError): BarView.as_view()(APIRequestFactory().get("/?foo=Foo"))
Example #25
Source File: test_backend.py From drf-mongo-filters with GNU General Public License v2.0 | 6 votes |
def test_model_subclassed(self): """ can apply filters for base model to queryset of derived """ class FooDoc(Document): meta = { 'allow_inheritance': True} foo = fields.StringField() class BarDoc(FooDoc): bar = fields.StringField() class FooFilter(ModelFilterset): class Meta: model = FooDoc class BarView(ListAPIView): filter_backends = (MongoFilterBackend,) filter_class = FooFilter serializer_class = mock.Mock() queryset = BarDoc.objects BarView.as_view()(APIRequestFactory().get("/?foo=Foo"))
Example #26
Source File: test_serializers.py From resolwe with Apache License 2.0 | 6 votes |
def setUp(self): super().setUp() self.process = Process.objects.create( slug="test-process", contributor=self.contributor, ) assign_perm("view_process", self.user, self.process) self.descriptor_schema1 = DescriptorSchema.objects.create( slug="test-schema", contributor=self.contributor, version="1.0.0", ) assign_perm("view_descriptorschema", self.user, self.descriptor_schema1) self.descriptor_schema2 = DescriptorSchema.objects.create( slug="test-schema", contributor=self.contributor, version="2.0.0", ) assign_perm("view_descriptorschema", self.user, self.descriptor_schema2) self.descriptor_schema3 = DescriptorSchema.objects.create( slug="test-schema", contributor=self.contributor, version="3.0.0", ) self.factory = APIRequestFactory()
Example #27
Source File: test_base.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def _make_submission_w_attachment(self, path, attachment_path): with open(path) as f: a = open(attachment_path) post_data = {'xml_submission_file': f, 'media_file': a} url = '/%s/submission' % self.user.username auth = DigestAuth('bob', 'bob') self.factory = APIRequestFactory() request = self.factory.post(url, post_data) request.user = authenticate(username='bob', password='bob') self.response = submission(request, username=self.user.username) if auth and self.response.status_code == 401: request.META.update(auth(request.META, self.response)) self.response = submission(request, username=self.user.username)
Example #28
Source File: test_briefcase_api.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def setUp(self): super(test_abstract_viewset.TestAbstractViewSet, self).setUp() self.factory = APIRequestFactory() self._login_user_and_profile() self.login_username = 'bob' self.login_password = 'bobbob' self.maxDiff = None self.form_def_path = os.path.join( self.main_directory, 'fixtures', 'transportation', 'transportation.xml') self._submission_list_url = reverse( 'view-submission-list', kwargs={'username': self.user.username}) self._submission_url = reverse( 'submissions', kwargs={'username': self.user.username}) self._download_submission_url = reverse( 'view-download-submission', kwargs={'username': self.user.username}) self._form_upload_url = reverse( 'form-upload', kwargs={'username': self.user.username})
Example #29
Source File: test_briefcase_api.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def setUp(self): super(TestBase, self).setUp() self.factory = APIRequestFactory() self._create_user_and_login() self._logout() self.form_def_path = os.path.join( self.this_directory, 'fixtures', 'transportation', 'transportation.xml') self._submission_list_url = reverse( 'view-submission-list', kwargs={'username': self.user.username}) self._submission_url = reverse( 'submissions', kwargs={'username': self.user.username}) self._download_submission_url = reverse( 'view-download-submission', kwargs={'username': self.user.username}) self._form_upload_url = reverse( 'form-upload', kwargs={'username': self.user.username})
Example #30
Source File: test_base.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def _make_submission_w_attachment(self, path, attachment_path): with open(path) as f: a = open(attachment_path) post_data = {'xml_submission_file': f, 'media_file': a} url = '/%s/submission' % self.user.username auth = DigestAuth('bob', 'bob') self.factory = APIRequestFactory() request = self.factory.post(url, post_data) request.user = authenticate(username='bob', password='bob') self.response = submission(request, username=self.user.username) if auth and self.response.status_code == 401: request.META.update(auth(request.META, self.response)) self.response = submission(request, username=self.user.username)