Python rest_framework.test 模块,APIRequestFactory() 实例源码

我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用rest_framework.test.APIRequestFactory()

项目:django-postcode-lookup    作者:LabD    | 项目源码 | 文件源码
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'
    }
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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})
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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, 'fixtures', 'transportation',
            '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, post_data)
            request.user = authenticate(username='bob',
                                        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)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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)
项目:2017.2-SiGI-Op_API    作者:fga-gpp-mds    | 项目源码 | 文件源码
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)
项目:2017.2-SiGI-Op_API    作者:fga-gpp-mds    | 项目源码 | 文件源码
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',
                                   lattitude=42,
                                   longitude=42,
                                   bandwidth=42,
                                   ipa_code=ipa,
                                   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)
项目:2017.2-SiGI-Op_API    作者:fga-gpp-mds    | 项目源码 | 文件源码
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', institution_type=instituion_type)

        site = Site.objects.create(name='RandomSite',
                                   lattitude=42,
                                   longitude=42,
                                   bandwidth=42,
                                   ipa_code=ipa,
                                   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)
项目:2017.2-SiGI-Op_API    作者:fga-gpp-mds    | 项目源码 | 文件源码
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)
项目:2017.2-SiGI-Op_API    作者:fga-gpp-mds    | 项目源码 | 文件源码
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,
                                                         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")
        primary_key = cable_stretch_test.pk
        cable_stretch_test.delete()
        response = cable_stretch_detail(request, pk=primary_key)
        self.assertEqual(response.status_code, 404)
项目:2017.2-SiGI-Op_API    作者:fga-gpp-mds    | 项目源码 | 文件源码
def test_tubeloose_view_set(self):
        request = APIRequestFactory().get("")
        cabletype = CableStretchType.objects.create(description="random")
        cable_stretch_test = CableStretch.objects.create(length=1,
                                                         manufacturing_year=2012,
                                                         cod=1,
                                                         infrastructure="random",
                                                         owner="random",
                                                         fabricant='Potato Bread',
                                                         cable_stretch_type=cabletype,
                                                         access=False,
                                                         creation_date="2017-10-12",
                                                         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)
项目:2017.2-SiGI-Op_API    作者:fga-gpp-mds    | 项目源码 | 文件源码
def test_wrong_tubeloose_view_set(self):
        request = APIRequestFactory().get("")
        cabletype = CableStretchType.objects.create(description="random")
        cable_stretch_test = CableStretch.objects.create(length=1,
                                                         manufacturing_year=2012,
                                                         cod=1,
                                                         infrastructure="random",
                                                         owner="random",
                                                         fabricant='Potato Bread',
                                                         cable_stretch_type=cabletype,
                                                         access=False,
                                                         creation_date="2017-10-12",
                                                         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)
        primary_key = tubeloose_test.pk
        tubeloose_test.delete()
        response = tubeloose_detail(request, pk=primary_key)
        self.assertEqual(response.status_code, 404)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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'], [512, 512, 16])
        self.assertEqual(response.data["cuboid_size"]['5'], [512, 512, 16])
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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',
                              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'], [512, 512, 16])
        self.assertEqual(response.data["cuboid_size"]['5'], [512, 512, 16])
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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',
                              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'], [512, 512, 16])
        self.assertEqual(response.data["cuboid_size"]['5'], [512, 512, 16])
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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/',
                              content_type='application/json')
        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Downsample.as_view()(request, collection='col1', experiment='exp_aniso', 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'], [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'], [2000, 5000, 200])
        self.assertEqual(response.data["extent"]['3'], [250, 625, 200])
        self.assertEqual(response.data["extent"]['5'], [63, 157, 200])
        self.assertEqual(response.data["cuboid_size"]['0'], [512, 512, 16])
        self.assertEqual(response.data["cuboid_size"]['3'], [512, 512, 16])
        self.assertEqual(response.data["cuboid_size"]['5'], [512, 512, 16])
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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',
                              content_type='application/json')
        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Downsample.as_view()(request, collection='col1', experiment='exp_aniso', 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'], [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'], [2000, 5000, 200])
        self.assertEqual(response.data["extent"]['3'], [250, 625, 200])
        self.assertEqual(response.data["extent"]['5'], [63, 157, 200])
        self.assertEqual(response.data["cuboid_size"]['0'], [512, 512, 16])
        self.assertEqual(response.data["cuboid_size"]['3'], [512, 512, 16])
        self.assertEqual(response.data["cuboid_size"]['5'], [512, 512, 16])
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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, collection='col1', 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)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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, 2 ** 16 - 1, (16, 128, 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/', bb,
                               content_type='application/blosc-python')
        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', 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)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
def test_channel_uint8_wrong_dimensions(self):
        """ Test posting with the wrong xyz dims"""

        test_mat = np.random.randint(1, 2 ** 16 - 1, (16, 128, 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/', bb,
                               content_type='application/blosc')
        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', experiment='exp1', channel='channel1',
                                    resolution='0', x_range='0:100', y_range='0:128', z_range='0:16', t_range=None)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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, 2 ** 16 - 1, (16, 128, 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/', bb,
                               content_type='application/blosc-python')
        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', experiment='exp1', channel='channel2',
                                    resolution='0', x_range='0:100', y_range='0:128', z_range='0:16', t_range=None)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', experiment='exp1', channel='channel2',
                                    resolution='0', x_range='0:2048', y_range='0:2048', z_range='0:131', t_range=None)
        self.assertEqual(response.status_code, status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
def test_channel_uint64_wrong_data_type(self):
        """ Test posting the wrong bitdepth data """

        test_mat = np.random.randint(1, 2 ** 16 - 1, (16, 128, 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/layer1/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, collection='col1', experiment='exp1', channel='layer1',
                                    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)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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, 2 ** 16 - 1, (16, 128, 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/', bb,
                               content_type='application/blosc-python')
        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', experiment='exp1', channel='layer1',
                                    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)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
def test_channel_uint64_wrong_dimensions(self):
        """ Test posting with the wrong xyz dims"""

        test_mat = np.random.randint(1, 2 ** 16 - 1, (16, 128, 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/', bb,
                               content_type='application/blosc')
        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', experiment='exp1', channel='layer1',
                                    resolution='0', x_range='0:100', y_range='0:128', z_range='0:16', t_range=None)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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, 2 ** 16 - 1, (16, 128, 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/', bb,
                               content_type='application/blosc-python')
        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', experiment='exp1', channel='layer1',
                                    resolution='0', x_range='0:100', y_range='0:128', z_range='0:16', t_range=None)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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/',
                              accepts='application/blosc')

        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', experiment='exp1', channel='layer1',
                                    resolution='0', x_range='0:2048', y_range='0:2048', z_range='0:66', t_range=None)
        self.assertEqual(response.status_code, status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
def test_channel_uint16_wrong_data_type(self):
        """ Test posting the wrong bitdepth data """

        test_mat = np.random.randint(1, 2 ** 16 - 1, (16, 128, 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/channel2/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, collection='col1', experiment='exp1', channel='channel2',
                                    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)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
def test_channel_uint16_wrong_dimensions(self):
        """ Test posting with the wrong xyz dims"""

        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/channel2/0/0:100/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, collection='col1', experiment='exp1', channel='channel2',
                                    resolution='0', x_range='0:100', y_range='0:128', z_range='0:16', t_range=None)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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, 2 ** 16 - 1, (16, 128, 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/', bb,
                               content_type='application/blosc-python')
        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', experiment='exp1', channel='channel2',
                                    resolution='0', x_range='0:100', y_range='0:128', z_range='0:16', t_range=None)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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/',
                              accepts='application/blosc')

        # log in user
        force_authenticate(request, user=self.user)

        # Make request
        response = Cutout.as_view()(request, collection='col1', experiment='exp1', channel='channel2',
                                    resolution='0', x_range='0:100000', y_range='0:100000', z_range='0:10000', t_range=None)
        self.assertEqual(response.status_code, status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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, collection='col1', experiment='exp1', channel='channel1',
                                        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]))
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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/',
                              Accept='image/png')
        force_authenticate(request, user=self.user)
        # Make request
        response = CutoutTile.as_view()(request, collection='col1', experiment='exp1', channel='channel1',
                                        orientation='yz', resolution='0', x_args='5', y_args='20:400', 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, 20:400, 5]))
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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/',
                              Accept='image/png')
        force_authenticate(request, user=self.user)
        # Make request
        response = Tile.as_view()(request, collection='col1', experiment='exp1', channel='channel1',
                                  orientation='xy', tile_size='512', resolution='0',
                                  x_idx='0', y_idx='0', z_idx='5')
        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, self.test_data_8[5, 0:512, 0:512])
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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/',
                              Accept='image/png')
        force_authenticate(request, user=self.user)
        # Make request
        response = Tile.as_view()(request, collection='col1', experiment='exp1', channel='channel1',
                                  orientation='xy', tile_size='512', resolution='0',
                                  x_idx='0', y_idx='1', z_idx='7')
        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, self.test_data_8[7, 512:1024, 0:512])
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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/',
                              Accept='image/png')
        force_authenticate(request, user=self.user)
        # Make request
        response = Tile.as_view()(request, collection='col1', experiment='exp1', channel='channel1',
                                  orientation='xy', tile_size='512', resolution='0',
                                  x_idx='1', y_idx='1', z_idx='3')
        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, self.test_data_8[3, 512:1024, 512:1024])
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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/',
                              Accept='image/png')
        force_authenticate(request, user=self.user)
        # Make request
        response = Tile.as_view()(request, collection='col1', experiment='exp1', channel='channel1',
                                  orientation='yz', tile_size='4', resolution='0',
                                  x_idx='0', y_idx='7', z_idx='2')
        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[8:12, 28:32, 0]))
项目:boss    作者:jhuapl-boss    | 项目源码 | 文件源码
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
项目:semillas_platform    作者:Semillas    | 项目源码 | 文件源码
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
        )
项目:edx-enterprise    作者:edx    | 项目源码 | 文件源码
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
项目:uclapi    作者:uclapi    | 项目源码 | 文件源码
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, 10, 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")
项目:api-django    作者:lafranceinsoumise    | 项目源码 | 文件源码
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'
        })
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
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)