Python rest_framework.test 模块,APIRequestFactory() 实例源码
我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用rest_framework.test.APIRequestFactory()。
def test_handle_backend_exception():
rf = APIRequestFactory(enforce_csrf_checks=True)
params = {
'postcode': '3531 WR',
'number': '1',
}
request = rf.post('/', data=params, format='json')
csrf.rotate_token(request)
request.COOKIES['csrftoken'] = request.META['CSRF_COOKIE']
request.META['HTTP_X_CSRFTOKEN'] = request.META['CSRF_COOKIE']
def throw_error(postcode, number):
raise PostcodeLookupException()
views.PostcodeLookupView.backend = stub(lookup=throw_error)
view = views.PostcodeLookupView.as_view()
response = view(request)
assert response.status_code == 400, response.rendered_content
assert response.data == {
'error': 'No valid response received from backend'
}
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)
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})
def test_submission_with_instance_id_on_root_node(self):
self._publish_xml_form()
message = u"Successful submission."
instanceId = u'5b2cc313-fc09-437e-8149-fcd32f695d41'
self.assertRaises(
Instance.DoesNotExist, Instance.objects.get, uuid=instanceId)
submission_path = os.path.join(
self.this_directory,
'view', 'submission.xml')
count = Instance.objects.count()
with codecs.open(submission_path, encoding='utf-8') as f:
post_data = {'xml_submission_file': f}
self.factory = APIRequestFactory()
request = self.factory.post(self._submission_url,
password='bob')
response = submission(request, username=self.user.username)
self.assertContains(response, message, status_code=201)
self.assertContains(response, instanceId, status_code=201)
self.assertEqual(Instance.objects.count(), count + 1)
def _make_submission_w_attachment(self,
username=self.user.username)
def test_site_view_set(self):
request = APIRequestFactory().get("")
view = SiteTypeListViewSet.as_view(actions={'get': 'retrieve'})
site_type = SiteType.objects.create(description="RandomSiteType")
instituion_type = InstitutionType.objects.create(description="RandomInstitution")
ipa = ParticipantInstitution.objects.create(name='UnB', institution_type=instituion_type)
site = Site.objects.create(name='RandomSite',
lattitude=42,
longitude=42,
bandwidth=42,
ipa_code=ipa,
site_type=site_type)
response = view(request, pk=site.pk)
self.assertEqual(response.status_code, 200)
def test_generator_view_set(self):
request = APIRequestFactory().get("")
view = GeneratorListViewSet.as_view(actions={'get': 'retrieve'})
site_type = SiteType.objects.create(description="RandomSiteType")
instituion_type = InstitutionType.objects.create(description="RandomInstitution")
ipa = ParticipantInstitution.objects.create(
name='UnB', institution_type=instituion_type)
site = Site.objects.create(name='RandomSite',
site_type=site_type)
generator = Generator.objects.create(power=123.3,
manufacturer='Fabricante1',
patrimony='Patrimonio1',
site=site)
response = view(request, pk=generator.pk)
self.assertEqual(response.status_code, 200)
def test_no_break_view_set(self):
request = APIRequestFactory().get("")
view = NoBreakViewSet.as_view(actions={'get': 'retrieve'})
site_type = SiteType.objects.create(description="RandomSiteType")
instituion_type = InstitutionType.objects.create(description="RandomInstitution")
ipa = ParticipantInstitution.objects.create(name='UnB',
site_type=site_type)
no_break = NoBreak.objects.create(power=1,
proprietary='john',
patrimony_number='01',
site_id=site)
response = view(request, pk=no_break.pk)
self.assertEqual(response.status_code, 200)
def test_cable_stretch_view_set(self):
request = APIRequestFactory().get("")
cable_stretch_detail = CableStretchListViewSet.as_view(actions={'get':'retrieve'})
cabletype = CableStretchType.objects.create(description="random")
cable_stretch_test = CableStretch.objects.create(cod=1,
length=1,
manufacturing_year=2012,
infrastructure="random",
owner="random",
fabricant='Potato Bread',
cable_stretch_type=cabletype,
access=False,
creation_date="2017-10-12",
updated_date="2017-10-12")
response = cable_stretch_detail(request, pk=cable_stretch_test.pk)
self.assertEqual(response.status_code, 200)
def test_wrong_cable_stretch(self):
request = APIRequestFactory().get("")
cable_stretch_detail = CableStretchListViewSet.as_view(actions={'get':'retrieve'})
cabletype = CableStretchType.objects.create(description="random")
cable_stretch_test = CableStretch.objects.create(cod=1,
updated_date="2017-10-12")
primary_key = cable_stretch_test.pk
cable_stretch_test.delete()
response = cable_stretch_detail(request, pk=primary_key)
self.assertEqual(response.status_code, 404)
def test_tubeloose_view_set(self):
request = APIRequestFactory().get("")
cabletype = CableStretchType.objects.create(description="random")
cable_stretch_test = CableStretch.objects.create(length=1,
cod=1,
updated_date="2017-10-12")
tubeloose_detail = TubelooseListViewSet.as_view(actions={'get':'retrieve'})
tubeloose_test = Tubeloose.objects.create(number=1010,
stretch_id=cable_stretch_test)
response = tubeloose_detail(request, pk=tubeloose_test.pk)
self.assertEqual(response.status_code, 200)
def test_wrong_tubeloose_view_set(self):
request = APIRequestFactory().get("")
cabletype = CableStretchType.objects.create(description="random")
cable_stretch_test = CableStretch.objects.create(length=1,
stretch_id=cable_stretch_test)
primary_key = tubeloose_test.pk
tubeloose_test.delete()
response = tubeloose_detail(request, 404)
def test_get_iso_properties_no_arg(self):
""" Test getting the properties of an isotropic channel"""
# Create request
factory = APIRequestFactory()
request = factory.get('/' + version + '/downsample/col1/exp_iso/channel1/',
content_type='application/json')
# log in user
force_authenticate(request, user=self.user)
# Make request
response = Downsample.as_view()(request, collection='col1', experiment='exp_iso', channel='channel1').render()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data["num_hierarchy_levels"], 8)
self.assertEqual(response.data["status"], "NOT_DOWNSAMPLED")
self.assertEqual(response.data["voxel_size"]['0'], [6.0, 6.0, 6.0])
self.assertEqual(response.data["voxel_size"]['3'], [48.0, 48.0, 48.0])
self.assertEqual(response.data["voxel_size"]['5'], [192.0, 192.0, 192.0])
self.assertEqual(response.data["extent"]['0'], [2000, 5000, 200])
self.assertEqual(response.data["extent"]['3'], [250, 625, 25])
self.assertEqual(response.data["extent"]['5'], [63, 157, 7])
self.assertEqual(response.data["cuboid_size"]['0'], [512, 512, 16])
self.assertEqual(response.data["cuboid_size"]['3'], 16])
self.assertEqual(response.data["cuboid_size"]['5'], 16])
def test_get_iso_properties_iso_false(self):
""" Test getting the properties of an isotropic channel with arg but false"""
# Create request
factory = APIRequestFactory()
request = factory.get('/' + version + '/downsample/col1/exp_iso/channel1/?iso=False', 16])
def test_get_iso_properties_iso(self):
""" Test getting the properties of an isotropic channel with arg but true"""
# Create request
factory = APIRequestFactory()
request = factory.get('/' + version + '/downsample/col1/exp_iso/channel1/?iso=True', 16])
def test_get_aniso_properties_no_arg(self):
""" Test getting the properties of an anisotropic channel"""
# Create request
factory = APIRequestFactory()
request = factory.get('/' + version + '/downsample/col1/exp_aniso/channel1/', experiment='exp_aniso', [4.0, 4.0, 35.0])
self.assertEqual(response.data["voxel_size"]['3'], [32.0, 32.0, 35.0])
self.assertEqual(response.data["voxel_size"]['5'], [128.0, 128.0, 35.0])
self.assertEqual(response.data["extent"]['0'], 200])
self.assertEqual(response.data["extent"]['5'], 200])
self.assertEqual(response.data["cuboid_size"]['0'], 16])
def test_get_aniso_properties_iso_false(self):
""" Test getting the properties of an anisotropic channel with the iso arg false"""
# Create request
factory = APIRequestFactory()
request = factory.get('/' + version + '/downsample/col1/exp_aniso/channel1/?iso=False', 16])
def test_channel_uint8_wrong_data_type(self):
""" Test posting the wrong bitdepth data """
config = bossutils.configuration.BossConfig()
test_mat = np.random.randint(1, 2 ** 16 - 1, (16, 128, 128))
test_mat = test_mat.astype(np.uint16)
h = test_mat.tobytes()
bb = blosc.compress(h, typesize=16)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/channel1/0/0:128/0:128/0:16/', bb,
content_type='application/blosc')
# log in user
force_authenticate(request, user=self.user)
# Make request
response = Cutout.as_view()(request, experiment='exp1', channel='channel1',
resolution='0', x_range='0:128', y_range='0:128', z_range='0:16', t_range=None)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_channel_uint8_wrong_data_type_numpy(self):
""" Test posting the wrong bitdepth data using the blosc-numpy interface"""
test_mat = np.random.randint(1, 128))
test_mat = test_mat.astype(np.uint16)
bb = blosc.pack_array(test_mat)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/channel1/0/0:128/0:128/0:16/',
content_type='application/blosc-python')
# log in user
force_authenticate(request, status.HTTP_400_BAD_REQUEST)
def test_channel_uint8_wrong_dimensions(self):
""" Test posting with the wrong xyz dims"""
test_mat = np.random.randint(1, 128))
test_mat = test_mat.astype(np.uint8)
h = test_mat.tobytes()
bb = blosc.compress(h, typesize=8)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/channel1/0/0:100/0:128/0:16/', x_range='0:100', status.HTTP_400_BAD_REQUEST)
def test_channel_uint8_wrong_dimensions_numpy(self):
""" Test posting with the wrong xyz dims using the numpy interface"""
test_mat = np.random.randint(1, 128))
test_mat = test_mat.astype(np.uint8)
bb = blosc.pack_array(test_mat)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/channel1/0/0:100/0:128/0:16/', channel='channel2', status.HTTP_400_BAD_REQUEST)
def test_channel_uint8_get_too_big(self):
""" Test getting a cutout that is over 1GB uncompressed"""
# Create request
factory = APIRequestFactory()
# Create Request to get data you posted
request = factory.get('/' + version + '/cutout/col1/exp1/channel1/0/0:2048/0:2048/0:131/',
accepts='application/blosc')
# log in user
force_authenticate(request, x_range='0:2048', y_range='0:2048', z_range='0:131', status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
def test_channel_uint64_wrong_data_type(self):
""" Test posting the wrong bitdepth data """
test_mat = np.random.randint(1, typesize=8)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/layer1/0/0:128/0:128/0:16/', channel='layer1', status.HTTP_400_BAD_REQUEST)
def test_channel_uint64_wrong_data_type_numpy(self):
""" Test posting the wrong bitdepth data using the blosc-numpy interface"""
test_mat = np.random.randint(1, 128))
test_mat = test_mat.astype(np.uint8)
bb = blosc.pack_array(test_mat)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/layer1/0/0:128/0:128/0:16/', status.HTTP_400_BAD_REQUEST)
def test_channel_uint64_wrong_dimensions(self):
""" Test posting with the wrong xyz dims"""
test_mat = np.random.randint(1, 128))
test_mat = test_mat.astype(np.uint64)
h = test_mat.tobytes()
bb = blosc.compress(h, typesize=64)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/layer1/0/0:100/0:128/0:16/', status.HTTP_400_BAD_REQUEST)
def test_channel_uint64_wrong_dimensions_numpy(self):
""" Test posting with the wrong xyz dims using the numpy interface"""
test_mat = np.random.randint(1, 128))
test_mat = test_mat.astype(np.uint64)
bb = blosc.pack_array(test_mat)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/layer1/0/0:100/0:128/0:16/', status.HTTP_400_BAD_REQUEST)
def test_channel_uint64_get_too_big(self):
""" Test getting a cutout that is over 1GB uncompressed"""
# Create request
factory = APIRequestFactory()
# Create Request to get data you posted
request = factory.get('/' + version + '/cutout/col1/exp1/layer1/0/0:2048/0:2048/0:66/', z_range='0:66', status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
def test_channel_uint16_wrong_data_type(self):
""" Test posting the wrong bitdepth data """
test_mat = np.random.randint(1, typesize=8)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/channel2/0/0:128/0:128/0:16/', status.HTTP_400_BAD_REQUEST)
def test_channel_uint16_wrong_dimensions(self):
""" Test posting with the wrong xyz dims"""
test_mat = np.random.randint(1, typesize=16)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/channel2/0/0:100/0:128/0:16/', status.HTTP_400_BAD_REQUEST)
def test_channel_uint16_wrong_dimensions_numpy(self):
""" Test posting with the wrong xyz dims using the numpy interface"""
test_mat = np.random.randint(1, 128))
test_mat = test_mat.astype(np.uint16)
bb = blosc.pack_array(test_mat)
# Create request
factory = APIRequestFactory()
request = factory.post('/' + version + '/cutout/col1/exp1/channel2/0/0:100/0:128/0:16/', status.HTTP_400_BAD_REQUEST)
def test_channel_uint16_get_too_big(self):
""" Test getting a cutout that is over 1GB uncompressed"""
# Create request
factory = APIRequestFactory()
# Create Request to get data you posted
request = factory.get('/' + version + '/cutout/col1/exp1/channel2/0/0:100000/0:100000/0:10000/', x_range='0:100000', y_range='0:100000', z_range='0:10000', status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
def test_png_uint8_xz(self):
""" Test a png xz slice"""
# Post data to the database
factory = APIRequestFactory()
# Get an image file
request = factory.get('/' + version + '/image/col1/exp1/channel1/xz/0/0:128/2/0:16/',
Accept='image/png')
force_authenticate(request, user=self.user)
# Make request
response = CutoutTile.as_view()(request,
orientation='xz', resolution='0', x_args='0:128', y_args='2', z_args='0:16')
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Check data is correct (this is pre-renderer)
test_img = np.array(response.data, dtype="uint8")
np.testing.assert_equal(test_img, np.squeeze(self.test_data_8[0:16, 2, 0:128]))
def test_png_uint8_yz(self):
""" Test a png yz slice"""
# Post data to the database
factory = APIRequestFactory()
# Get an image file
request = factory.get('/' + version + '/image/col1/exp1/channel1/yz/0/5/20:400/0:16/',
orientation='yz', x_args='5', y_args='20:400', 20:400, 5]))
def test_png_uint8_xy(self):
""" Test a png xy slice"""
# Post data to the database
factory = APIRequestFactory()
# Get an image file
request = factory.get('/' + version + '/tile/col1/exp1/channel1/xy/512/0/0/0/5/', user=self.user)
# Make request
response = Tile.as_view()(request,
orientation='xy', tile_size='512',
x_idx='0', y_idx='0', z_idx='5')
self.assertEqual(response.status_code, self.test_data_8[5, 0:512, 0:512])
def test_png_uint8_xy_y_offset(self):
""" Test a png xy slice"""
# Post data to the database
factory = APIRequestFactory()
# Get an image file
request = factory.get('/' + version + '/tile/col1/exp1/channel1/xy/512/0/0/1/7/', y_idx='1', z_idx='7')
self.assertEqual(response.status_code, self.test_data_8[7, 512:1024, 0:512])
def test_png_uint8_xy_x_offset(self):
""" Test a png xy slice"""
# Post data to the database
factory = APIRequestFactory()
# Get an image file
request = factory.get('/' + version + '/tile/col1/exp1/channel1/xy/512/0/1/1/3/',
x_idx='1', z_idx='3')
self.assertEqual(response.status_code, self.test_data_8[3, 512:1024])
def test_png_uint8_yz(self):
""" Test a png yz slice"""
# Post data to the database
factory = APIRequestFactory()
# Get an image file
request = factory.get('/' + version + '/tile/col1/exp1/channel1/yz/4/0/0/7/2/',
orientation='yz', tile_size='4', y_idx='7', z_idx='2')
self.assertEqual(response.status_code, np.squeeze(self.test_data_8[8:12, 28:32, 0]))
def makeRequest(self, get=None, post=None, delete=None, data=None):
factory = APIRequestFactory()
prefix = '/' + VERSION
if get is not None:
request = factory.get(prefix + get)
elif post is not None:
request = factory.post(prefix + post, data)
elif delete is not None:
request = factory.delete(prefix + delete)
else:
raise Exception('Unsupported request type')
force_authenticate(request, user=self.user)
return request
def test_service_detail_get_with_distance(self):
Service.objects.all().update(category=Category.objects.first())
serv = Service.objects.first()
factory = APIRequestFactory()
request = factory.get('/api/v1/service/{0}/'.format(serv.uuid))
view = ServiceDetail.as_view()
force_authenticate(request, user=self.user)
response = view(request, uuid=serv.uuid)
self.assertEqual(
response.data['uuid'],
str(serv.uuid)
)
self.assertEqual(
response.data['distance'],
1043.4
)
self.assertEqual(
response.status_code,
200
)
def test_get_paginated_response_correct_query_parameters(self):
"""
Verify get_paginated_response returns correct response.
"""
self.data['next'] = '{discovery_uri}?page=3'.format(discovery_uri=DISCOVERY_URI)
self.data['previous'] = '{discovery_uri}?page=1'.format(discovery_uri=DISCOVERY_URI)
expected_next = '{enterprise_uri}?page=3'.format(enterprise_uri=ENTERPRISE_URI)
expected_previous = '{enterprise_uri}?page=1'.format(enterprise_uri=ENTERPRISE_URI)
request = APIRequestFactory().get(
reverse('catalogs-list') + "?page=2",
SERVER_NAME="testserver.enterprise",
)
# Update authentication parameters based in ddt data.
response = get_paginated_response(self.data, request)
assert response.data.get('next') == expected_next
assert response.data.get('previous') == expected_previous
def setUp(self):
self.factory = APIRequestFactory()
# This fixes a bug when the `test_temp_token_valid` test would fail
TemporaryToken.objects.all().delete()
# General temporary token for tests
self.token = TemporaryToken.objects.create()
self.token.save()
# An expired token for the expiry test
self.expired_token = TemporaryToken.objects.create()
self.expired_token.save()
self.expired_token.created = datetime.datetime(
2010, 10, 10
)
self.expired_token.save()
# A valid token to use later
self.valid_token = TemporaryToken.objects.create()
self.valid_token.save()
# Standard Token data
self.user_ = User.objects.create(cn="test", employee_id=7357)
self.app = App.objects.create(user=self.user_, name="An App")
def setUp(self):
self.factory = APIRequestFactory()
self.client_unprivileged = models.Client.objects.create_client('unprivileged', 'password')
self.viewer_client = models.Client.objects.create_client('viewer', 'password')
client_content_type = ContentType.objects.get_for_model(models.Client)
view_permission = Permission.objects.get(content_type=client_content_type, codename='view_client')
self.viewer_client.role.user_permissions.add(view_permission)
self.detail_view = LegacyClientViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
self.list_view = LegacyClientViewSet.as_view({
'get': 'list',
'post': 'create'
})
self.authenticate_view = LegacyClientViewSet.as_view({
'post': 'authenticate_client'
})
def _make_submission_w_attachment(self,
username=self.user.username)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。