def test_copy_file_request(self):
        response_body = RestResult(
            0, 'OK',
            FileDescriptor('/file.copy.txt', 'file-new-id', FileType.file,
                           'text/plain', 123).serialize())
        httpretty.register_uri(httpretty.POST,
                               'https://fish.barrel/_api/copy/file',
                               body=json.dumps(response_body.serialize()))

        file_descriptor = self.file_service.copy_file_request().set_source(
            Source('/file.txt')).set_destination(
                Destination('/file.copy.txt')).execute()

        assert_that(file_descriptor, instance_of(FileDescriptor))
        assert_that(file_descriptor.path, is_('/file.copy.txt'))
        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'source': {
                    'path': '/file.txt',
                    'fileId': None
                },
                'destination': {
                    'directory': None,
                    'path': '/file.copy.txt',
                    'lifecycle': None,
                    'acl': 'public',
                    'bucket': None
                }
            }))
    def test_create_files_request(self):
        expected_file_descriptor = FileDescriptor('/fish', 'file-id',
                                                  FileType.directory,
                                                  FileMimeType.directory, 0)
        expected_response_body = RestResult(
            0, 'OK', expected_file_descriptor.serialize())

        httpretty.register_uri(httpretty.POST,
                               'https://fish.barrel/_api/files',
                               body=json.dumps(
                                   expected_response_body.serialize()))

        response = self.file_service.create_files_request().add_file(
            self.file_service.create_file_request().set_path(
                '/fish')).execute()

        assert_that(response.file_descriptors, instance_of(list))
        assert_that(response.file_descriptors, has_length(1))
        assert_that(response.file_descriptors[0], instance_of(FileDescriptor))
        assert_that(response.file_descriptors[0].serialize(),
                    is_(expected_file_descriptor.serialize()))

        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'mimeType': FileMimeType.directory,
                'path': '/fish',
                'size': 0,
                'type': FileType.directory,
                'acl': ACL.public,
                'id': None,
                'bucket': None
            }))
    def test_file_metadata_request(self):
        response_body = RestResult(
            0, 'OK', {
                'mediaType': 'video',
                'fileDescriptor': {
                    'acl': 'private',
                    'hash': None,
                    'id': '2de4305552004e0b9076183651030646',
                    'mimeType': 'video/mp4',
                    'path': '/videos/animals/cat.mp4',
                    'size': 15431333,
                    'type': '-'
                },
                'basic': {
                    'interlaced':
                    False,
                    'videoStreams': [{
                        'codecLongName': 'MPEG-4 part 2',
                        'height': 720,
                        'duration': 59351,
                        'bitrate': 1950467,
                        'index': 0,
                        'rFrameRate': '3000/100',
                        'codecTag': 'mp4v',
                        'avgFrameRate': '2997/100',
                        'codecName': 'mpeg4',
                        'width': 1280,
                        'sampleAspectRatio': '1:1',
                        'displayAspectRatio': '16:9',
                        'fieldOrder': None,
                        'disposition': []
                    }],
                    'audioStreams': [{
                        'codecLongName': 'AAC (Advanced Audio Coding)',
                        'index': 1,
                        'codecTag': 'mp4a',
                        'codecName': 'aac',
                        'duration': 59351,
                        'bitrate': 128322
                    }],
                    'format': {
                        'duration': 59351,
                        'formatLongName': 'QuickTime / MOV',
                        'bitrate': 2085272,
                        'size': 15476893
                    }
                }
            })
        httpretty.register_uri(httpretty.GET,
                               'https://fish.barrel/_api/files/metadata',
                               body=json.dumps(response_body.serialize()))

        file_metadata = self.file_service.file_metadata_request().set_path(
            '/videos/animals/cat.mp4').execute()

        assert_that(file_metadata.file_descriptor.id,
                    is_('2de4305552004e0b9076183651030646'))
        assert_that(httpretty.last_request().querystring), is_({
            'path': ['/videos/animals/cat.mp4'],
        })
    def test_create_archive_manifest_request(self):
        payload = FileDescriptor('/m.zip', 'file-id', FileType.file,
                                 'application/vnd.wix-media.zip',
                                 123).serialize()
        response_body = RestResult(0, 'OK', payload)
        httpretty.register_uri(
            httpretty.POST,
            'https://fish.appspot.com/_api/archive/create/manifest',
            body=json.dumps(response_body.serialize()))

        file_descriptor = self.archive_service.create_archive_manifest_request(
        ).add_sources(Source('/video.mp4')).set_destination(
            Destination('/m.zip')).set_algorithm(
                ZipAlgorithm.store).set_name('archive.zip').execute()

        assert_that(file_descriptor, instance_of(FileDescriptor))
        assert_that(file_descriptor.path, is_('/m.zip'))
        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'sources': [{
                    'path': '/video.mp4',
                    'fileId': None
                }],
                'destination': {
                    'directory': None,
                    'path': '/m.zip',
                    'lifecycle': None,
                    'acl': 'public',
                    'bucket': None
                },
                'name': 'archive.zip',
                'algorithm': 'store'
            }))
    def test_upload_configuration_request(self):
        response_body = RestResult(0, 'OK', {
            'uploadToken': 'token',
            'uploadUrl': 'url'
        })
        httpretty.register_uri(
            httpretty.POST,
            'https://fish.barrel/_api/v2/upload/configuration',
            body=json.dumps(response_body.serialize()))

        upload_url = self.file_service.upload_configuration_request().set_path(
            '/fish.txt').execute()

        assert_that(upload_url, instance_of(UploadConfiguration))
        assert_that(upload_url.upload_token, is_('token'))
        assert_that(upload_url.upload_url, is_('url'))
        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'mimeType': None,
                'path': '/fish.txt',
                'bucket': None,
                'size': None,
                'acl': None,
                'callback': None
            }))
    def test_image_operation_request(self):
        payload = FileDescriptor('/pony.png', 'file-id', FileType.file,
                                 'image/png', 123).serialize()
        response = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.POST,
                               'https://fish.barrel/_api/images/operations',
                               body=json.dumps(response.serialize()))

        features = self.image_service.image_operation_request().set_source(
            Source('/omg.png')).set_specification(
                ImageOperationSpecification(
                    '/v1/fit/w_200,h_100',
                    Destination('/pony.png'))).execute()

        assert_that(features, instance_of(FileDescriptor))
        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'source': {
                    'path': '/omg.png',
                    'fileId': None
                },
                'specification': {
                    'destination': {
                        'directory': None,
                        'path': '/pony.png',
                        'lifecycle': None,
                        'acl': 'public',
                        'bucket': None
                    },
                    'command': '/v1/fit/w_200,h_100'
                }
            }))
    def test_file_list_request(self):
        response_body = RestResult(
            0, 'OK', {
                'nextPageToken':
                'next page',
                'files': [
                    FileDescriptor('/fish.txt', 'file-id', FileType.file,
                                   'text/plain', 123).serialize()
                ]
            })
        httpretty.register_uri(httpretty.GET,
                               'https://fish.barrel/_api/files/ls_dir',
                               body=json.dumps(response_body.serialize()))

        file_list = self.file_service.file_list_request().set_path('/files').set_next_page_token('next') \
            .set_order_by(OrderBy.name).set_page_size(12).set_recursive(True).set_type(FileType.file).execute()

        assert_that(file_list.next_page_token, is_('next page'))
        assert_that(
            httpretty.last_request().querystring,
            is_({
                'nextPageToken': ['next'],
                'orderBy': ['name'],
                'pageSize': ['12'],
                'r': ['True'],
                'path': ['/files'],
                'type': ['-'],
                'orderDirection': ['des']
            }))
    def test_get_expected_null_payload(self):
        response_body = RestResult(0, 'OK')
        httpretty.register_uri(httpretty.GET,
                               self.test_endpoint,
                               body=json.dumps(response_body.serialize()))

        payload = self.authenticated_http_client.get(self.test_endpoint)
        assert_that(payload, is_(None))
Пример #9
0
    def test_subset_font_request(self):
        payload = {
            'groupId':
            'g',
            'jobs': [{
                'type': 'urn:job:text.font.subset',
                'id': 'g_1',
                'groupId': 'g',
                'status': 'pending',
                'issuer': 'urn:app:app-id',
                'sources': [{
                    'path': '/font.ttf'
                }],
                'specification': {
                    'destination': {
                        'path': '/font.en.ttf',
                        'acl': 'public'
                    },
                    'languageCode': 'en'
                },
                'callback': {
                    'url': 'https://i.will.be.back/'
                },
                'dateUpdated': '2017-05-22T07:17:44Z',
                'dateCreated': '2017-05-22T07:17:44Z'
            }]
        }

        response = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.POST,
                               'https://fish.appspot.com/_api/fonts/subset',
                               body=json.dumps(response.serialize()))

        job_group = self.text_service.subset_font_request().set_source(
            Source('/font.ttf')).set_specification(
                SubsetFontSpecification(Destination('/font.en.ttf'),
                                        'en')).execute()

        assert_that(job_group.group_id, is_('g'))
        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'source': {
                    'path': '/font.ttf',
                    'fileId': None
                },
                'specification': {
                    'destination': {
                        'directory': None,
                        'path': '/font.en.ttf',
                        'bucket': None,
                        'lifecycle': None,
                        'acl': 'public'
                    },
                    'languageCode': 'en'
                },
                'jobCallback': None
            }))
Пример #10
0
    def test_abort_flow_request(self):
        response = RestResult(0, 'OK', None)
        httpretty.register_uri(
            httpretty.DELETE,
            'https://fish.barrel/_api/flow_control/flow/state-id',
            body=json.dumps(response.serialize()))

        self.flow_control_service.abort_flow_request().set_id(
            'state-id').execute()
    def test_extract_features_request(self):
        payload = {
            'colors': [
                {
                    'pixelFraction': 0.58838487,
                    'r': 236,
                    'b': 235,
                    'score': 0.5731545,
                    'g': 232
                },
                {
                    'pixelFraction': 0.09195876,
                    'r': 155,
                    'b': 119,
                    'score': 0.16580881,
                    'g': 119
                },
            ],
            'labels': [{
                'score': 0.8536242,
                'name': 'beauty'
            }, {
                'score': 0.71902096,
                'name': 'art model'
            }],
            'explicitContent': [{
                'likelihood': 'VERY_UNLIKELY',
                'name': 'violence'
            }, {
                'likelihood': 'VERY_LIKELY',
                'name': 'adult'
            }],
            'faces': [{
                'y': 446,
                'x': 1319,
                'height': 670,
                'width': 580
            }]
        }

        response = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.GET,
                               'https://fish.barrel/_api/images/features',
                               body=json.dumps(response.serialize()))

        features = self.image_service.extract_features_request().set_path(
            '/image.png').add_features(Feature.explicit_content, Feature.faces,
                                       Feature.colors,
                                       Feature.labels).execute()

        assert_that(features, instance_of(ImageFeatures))
        assert_that(
            httpretty.last_request().querystring,
            is_({
                'path': ['/image.png'],
                'features': ['explicit_content,faces,colors,labels']
            }))
    def test_delete_file_request(self):
        response_body = RestResult(0, 'OK', None)
        httpretty.register_uri(
            httpretty.DELETE,
            'https://fish.barrel/_api/files?path=%2Ffist.txt',
            body=json.dumps(response_body.serialize()))

        self.file_service.delete_file_request().set_path('/fish.txt').execute()

        assert_that(httpretty.last_request().querystring,
                    is_({'path': ['/fish.txt']}))
Пример #13
0
    def test_flow_state_request(self):
        response = RestResult(0, 'OK', flow_state_response)
        httpretty.register_uri(
            httpretty.GET,
            'https://fish.barrel/_api/flow_control/flow/state-id',
            body=json.dumps(response.serialize()))

        flow_state = self.flow_control_service.flow_state_request().set_id(
            'state-id').execute()

        assert_that(flow_state, instance_of(FlowState))
    def test_replace_extra_metadata_async_request(self):
        response_body = RestResult(0, 'OK', job.serialize())

        httpretty.register_uri(
            httpretty.POST,
            'https://domain/_api/av/extra-metadata',
            body=json.dumps(response_body.serialize())
        )

        got_job = self.audio_service.replace_extra_metadata_async_request().set_specification(
            specification
        ).set_source(source).execute()

        assert_that(got_job.serialize(), is_(job.serialize()))
    def test_get(self):
        payload = DummyPayload('fish')
        response_body = RestResult(0, 'OK', payload.serialize())

        httpretty.register_uri(httpretty.GET,
                               self.test_endpoint,
                               body=json.dumps(response_body.serialize()))

        payload = self.authenticated_http_client.get(self.test_endpoint,
                                                     payload_type=DummyPayload)

        assert_that(payload, instance_of(DummyPayload))
        assert_that(payload.dumdum, is_('fish'))
        assert_that(httpretty.last_request().headers.get('Authorization'),
                    not_none())
    def _handle_error(cls, response):
        try:
            rest_result = RestResult.deserialize(response.json())
            message = rest_result.message
        except (ValueError, KeyError):
            message = response.content

        status_code = response.status_code

        if status_code == 401:
            raise UnauthorizedException(message)

        if status_code == 403:
            raise ForbiddenException(message)

        if status_code == 404:
            raise NotFoundException(message)

        if status_code == 409:
            raise ConflictException(message)

        if status_code == 502:
            raise BadGatewayException(message)

        raise MediaPlatformException(message)
    def test_file_request(self):
        payload = FileDescriptor('/fish.txt', 'file-id', FileType.file,
                                 'text/plain', 123).serialize()
        response_body = RestResult(0, 'OK', payload)
        httpretty.register_uri(
            httpretty.GET,
            'https://fish.barrel/_api/files?path=%2Ffist.txt',
            body=json.dumps(response_body.serialize()))

        file_descriptor = self.file_service.file_request().set_path(
            '/fish.txt').execute()

        assert_that(file_descriptor.serialize(), is_(payload))
        assert_that(file_descriptor, instance_of(FileDescriptor))
        assert_that(httpretty.last_request().querystring,
                    is_({'path': ['/fish.txt']}))
Пример #18
0
    def deserialize(cls, data):
        # type: (dict) -> Job

        sources = [Source.deserialize(source) for source in data['sources']]
        date_created = datetime_serialization.deserialize(data['dateCreated'])
        date_updated = datetime_serialization.deserialize(data['dateUpdated'])
        callback_data = data.get('callback')
        callback = Callback.deserialize(
            callback_data) if callback_data else None
        specification = data['specification']
        if cls.specification_type:
            specification = cls.specification_type.deserialize(specification)

        result_data = data.get('result')
        if result_data:
            # todo: deserialize result payload as specific type
            result = RestResult.deserialize(result_data)
        else:
            result = None

        job = cls(data['id'], data['issuer'],
                  data['status'], specification, sources, callback,
                  data.get('flowId'), result, date_created, date_updated)
        job.type = data['type']
        return job
    def test_import_file_request(self):
        payload = {
            'status': 'pending',
            'specification': {
                'sourceUrl': 'http://source.url/filename.txt',
                'destination': {
                    'directory': '/fish',
                    'acl': 'public'
                }
            },
            'dateCreated': '2017-05-23T08:34:43Z',
            'sources': [],
            'result': None,
            'id':
            '71f0d3fde7f348ea89aa1173299146f8_19e137e8221b4a709220280b432f947f',
            'dateUpdated': '2017-05-23T08:34:43Z',
            'type': 'urn:job:import.file',
            'groupId': '71f0d3fde7f348ea89aa1173299146f8',
            'issuer': 'urn:app:app-id-1'
        }
        response_body = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.POST,
                               'https://fish.barrel/_api/import/file',
                               body=json.dumps(response_body.serialize()))

        import_file_job = self.file_service.import_file_request(
        ).set_destination(
            Destination('/img.png')).set_source_url('source-url').execute()

        assert_that(
            import_file_job.id,
            is_('71f0d3fde7f348ea89aa1173299146f8_19e137e8221b4a709220280b432f947f'
                ))
        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'sourceUrl': 'source-url',
                'destination': {
                    'directory': None,
                    'path': '/img.png',
                    'lifecycle': None,
                    'acl': 'public',
                    'bucket': None
                },
                'externalAuthorization': None
            }))
    def test_update_file_request(self):
        payload = FileDescriptor('/fish.txt', 'file-id', FileType.file,
                                 'text/plain', 18).serialize()
        response_body = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.PUT,
                               'https://fish.barrel/_api/files',
                               body=json.dumps(response_body.serialize()))

        file_descriptor = self.file_service.update_file_request().set_path(
            '/fish.txt').set_acl(ACL.public).execute()

        assert_that(file_descriptor.serialize(), is_(payload))
        assert_that(file_descriptor, instance_of(FileDescriptor))
        assert_that(json.loads(httpretty.last_request().body),
                    is_({
                        'path': '/fish.txt',
                        'id': None,
                        'acl': 'public'
                    }))
Пример #21
0
    def test_job_list_request(self):
        payload = {
            'nextPageToken':
            'next',
            'jobs': [{
                'status': 'pending',
                'specification': {},
                'dateCreated': '2017-05-23T08:34:43Z',
                'sources': [],
                'result': None,
                'id': 'g_1',
                'dateUpdated': '2017-05-23T08:34:43Z',
                'type': 'urn:job:something.fresh',
                'groupId': '71f0d3fde7f348ea89aa1173299146f8',
                'issuer': 'urn:app:app-id-1'
            }]
        }
        response = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.GET,
                               'https://fish.barrel/_api/jobs',
                               body=json.dumps(response.serialize()))

        job_list = self.job_service.job_list_request().set_type(
            'urn:job:fish').set_page_size(3).set_order_by(
                OrderBy.date_updated).set_next_page_token('nnn').set_path(
                    '/mmm').set_issuer('urn:me').set_order_direction(
                        OrderDirection.descending).set_status(
                            JobStatus.pending).execute()

        assert_that(job_list.jobs[0], instance_of(Job))
        assert_that(job_list.jobs[0].id, is_('g_1'))
        assert_that(
            httpretty.last_request().querystring,
            is_({
                'nextPageToken': ['nnn'],
                'orderBy': ['dateUpdated'],
                'pageSize': ['3'],
                'status': ['pending'],
                'path': ['/mmm'],
                'type': ['urn:job:fish'],
                'orderDirection': ['des'],
                'issuer': ['urn:me']
            }))
Пример #22
0
    def test_job_request_base_job(self):
        payload = {
            'status': 'pending',
            'specification': {},
            'dateCreated': '2017-05-23T08:34:43Z',
            'sources': [],
            'result': None,
            'id': 'g_1',
            'dateUpdated': '2017-05-23T08:34:43Z',
            'type': 'urn:job:something.fresh',
            'groupId': '71f0d3fde7f348ea89aa1173299146f8',
            'issuer': 'urn:app:app-id-1'
        }
        response_1 = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.GET,
                               'https://fish.barrel/_api/jobs/1_g',
                               body=json.dumps(response_1.serialize()))

        job = self.job_service.job_request().set_id('1_g').execute()

        assert_that(job, instance_of(Job))
    def test_upload_url_request(self):
        response_body = RestResult(0, 'OK', {
            'uploadToken': 'token',
            'uploadUrl': 'url'
        })
        httpretty.register_uri(httpretty.GET,
                               'https://fish.barrel/_api/upload/url',
                               body=json.dumps(response_body.serialize()))

        upload_url = self.file_service.upload_url_request().set_path(
            '/fish.txt').execute()

        assert_that(upload_url, instance_of(UploadUrl))
        assert_that(upload_url.upload_token, is_('token'))
        assert_that(upload_url.upload_url, is_('url'))
        assert_that(
            httpretty.last_request().querystring,
            is_({
                'path': ['/fish.txt'],
                'acl': ['public'],
                'mimeType': ['application/octet-stream']
            }))
    def test_upload_file_request_with_callback(self):
        url_response_body = RestResult(
            0, 'OK', {
                'uploadToken': 'token',
                'uploadUrl': 'https://fish.barrel/cryptic-path'
            })
        httpretty.register_uri(httpretty.GET,
                               'https://fish.barrel/_api/upload/url',
                               body=json.dumps(url_response_body.serialize()))

        upload_response_body = RestResult(0, 'OK', [
            FileDescriptor('/fish.txt', 'file-id', FileType.file,
                           FileMimeType.defualt, 123).serialize()
        ])
        httpretty.register_uri(httpretty.POST,
                               'https://fish.barrel/cryptic-path',
                               body=json.dumps(
                                   upload_response_body.serialize()))

        callback = Callback('https://valid.url/', {'attach': 'fish'},
                            {'head': 'dog'})
        self.file_service.upload_file_request().set_path(
            '/fish.txt').set_content('some content').set_callback(
                callback).execute()

        request_body = httpretty.last_request().body.decode('utf-8')
        assert_that(
            request_body,
            contains_string(
                'Content-Disposition: form-data; name="acl"\r\n\r\n%s' %
                ACL.public))
        assert_that(
            request_body,
            contains_string(
                'Content-Disposition: form-data; name="path"\r\n\r\n%s' %
                '/fish.txt'))
        assert_that(
            request_body,
            contains_string(
                'Content-Disposition: form-data; name="uploadToken"\r\n\r\n%s'
                % 'token'))
        assert_that(
            request_body,
            contains_string(
                'Content-Disposition: form-data; name="mimeType"\r\n\r\n%s' %
                FileMimeType.defualt))
        assert_that(
            request_body,
            contains_string(
                'Content-Disposition: form-data; name="callback"\r\n\r\n%s' %
                json.dumps(callback.serialize())))
        assert_that(
            request_body,
            contains_string(
                'Content-Disposition: form-data; name="file"; filename="file-name"\r\n'
                'Content-Type: %s\r\n\r\n%s' %
                (FileMimeType.defualt, 'some content')))
    def test_create_file_request(self):
        payload = FileDescriptor('/fish', 'file-id', FileType.directory,
                                 FileMimeType.directory, 0).serialize()
        response_body = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.POST,
                               'https://fish.barrel/_api/files',
                               body=json.dumps(response_body.serialize()))

        file_descriptor = self.file_service.create_file_request().set_path(
            '/fish').execute()

        assert_that(file_descriptor.serialize(), is_(payload))
        assert_that(file_descriptor, instance_of(FileDescriptor))
        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'mimeType': FileMimeType.directory,
                'path': '/fish',
                'size': 0,
                'type': FileType.directory,
                'acl': ACL.public,
                'id': None,
                'bucket': None
            }))
Пример #26
0
    def test_job_request(self):
        payload = {
            'status': 'pending',
            'specification': {
                'sourceUrl': 'http://source.url/filename.txt',
                'destination': {
                    'directory': '/fish',
                    'acl': 'public'
                }
            },
            'dateCreated': '2017-05-23T08:34:43Z',
            'sources': [],
            'result': None,
            'id': 'g_1',
            'dateUpdated': '2017-05-23T08:34:43Z',
            'type': 'urn:job:import.file',
            'groupId': '71f0d3fde7f348ea89aa1173299146f8',
            'issuer': 'urn:app:app-id-1'
        }
        response_1 = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.GET,
                               'https://fish.barrel/_api/jobs/g_1',
                               body=json.dumps(response_1.serialize()))
        payload = {
            'status': 'pending',
            'specification': {
                'sourceUrl': 'http://source.url/filename.txt',
                'destination': {
                    'directory': '/fish',
                    'acl': 'public'
                }
            },
            'dateCreated': '2017-05-23T08:34:43Z',
            'sources': [],
            'result': None,
            'id': 'g_2',
            'dateUpdated': '2017-05-23T08:34:43Z',
            'type': 'urn:job:import.file',
            'groupId': '71f0d3fde7f348ea89aa1173299146f8',
            'issuer': 'urn:app:app-id-1'
        }
        response_2 = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.GET,
                               'https://fish.barrel/_api/jobs/g_2',
                               body=json.dumps(response_2.serialize()))

        request = self.job_service.job_request().set_id('g_1')
        job_1 = request.execute()
        # verify that url rewrite works as intended
        job_2 = request.set_id('g_2').execute()

        assert_that(job_1, instance_of(ImportFileJob))
        assert_that(job_1.id, is_('g_1'))
        assert_that(job_2.id, is_('g_2'))
    def _handle_success(cls, response, payload_type):
        # type: (requests.Response, Type[Deserializable] or [Type[Deserializable]]) -> object or None
        try:
            rest_result = RestResult.deserialize(response.json())
            rest_result.raise_for_code()

            if rest_result.payload is None:
                return None

            if payload_type is None:
                raise MediaPlatformException(
                    'Unexpected payload (expected None)')

            return payload_type.deserialize(rest_result.payload)

        except (ValueError, KeyError) as e:
            raise MediaPlatformException('Bad response format', e)
    def test_upload_file_v2_request(self):
        url_response_body = RestResult(
            0, 'OK', {
                'uploadToken': 'token',
                'uploadUrl': 'https://fish.barrel/v2/cryptic-path'
            })
        httpretty.register_uri(
            httpretty.POST,
            'https://fish.barrel/_api/v2/upload/configuration',
            body=json.dumps(url_response_body.serialize()))

        upload_mime_type = 'text/plain'
        upload_response_body = RestResult(
            0, 'OK',
            FileDescriptor('/fish.txt', 'file-id', FileType.file,
                           upload_mime_type, 123).serialize())
        httpretty.register_uri(httpretty.POST,
                               'https://fish.barrel/v2/cryptic-path',
                               body=json.dumps(
                                   upload_response_body.serialize()))

        upload_content = 'some content'
        upload_lifecycle = Lifecycle(age=30, action=Action.delete)
        file_descriptor = self.file_service.upload_file_v2_request() \
            .set_acl(ACL.private).set_path('/fish.txt').set_content(upload_content).set_mime_type(upload_mime_type) \
            .set_lifecycle(upload_lifecycle).set_filename('fishenzon').execute()

        assert_that(file_descriptor, instance_of(FileDescriptor))
        assert_that(file_descriptor.path, is_('/fish.txt'))

        request_body = httpretty.last_request().body.decode('utf-8')

        assert_that(
            request_body,
            contains_string(
                'Content-Disposition: form-data; name="uploadToken"\r\n\r\n%s'
                % 'token'))
        assert_that(
            request_body,
            contains_string(
                'Content-Disposition: form-data; name="lifecycle"\r\n\r\n%s' %
                json.dumps(upload_lifecycle.serialize())))
        assert_that(
            request_body,
            contains_string(
                'Content-Disposition: form-data; name="file"; filename="fishenzon"\r\n'
                'Content-Type: %s\r\n\r\n%s' %
                (upload_mime_type, upload_content)))
    def test_create_archive_request(self):
        payload = {
            'type': 'urn:job:archive.create',
            'id': 'g_1',
            'groupId': 'g',
            'status': 'pending',
            'issuer': 'urn:app:app-id',
            'sources': [{
                'path': '/video.mp4'
            }],
            'specification': {
                'sources': [{
                    'path': '/video.mp4'
                }],
                'destination': {
                    'path': '/video.tar',
                    'acl': 'public'
                },
                'archiveType': 'tar'
            },
            'callback': {
                'url': 'https://call.me.back/'
            },
            'dateUpdated': '2017-05-22T07:17:44Z',
            'dateCreated': '2017-05-22T07:17:44Z'
        }

        response = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.POST,
                               'https://fish.appspot.com/_api/archive/create',
                               body=json.dumps(response.serialize()))

        job = self.archive_service.create_archive_request().add_sources(
            Source('/video.mp4')).set_destination(
                Destination('/video.tar')).set_archive_type(
                    ArchiveType.tar).set_callback(
                        Callback('https://call.me.back/')).execute()

        assert_that(job, instance_of(CreateArchiveJob))
        assert_that(job.group_id, is_('g'))
        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'archiveType': 'tar',
                'sources': [{
                    'path': '/video.mp4',
                    'fileId': None
                }],
                'destination': {
                    'directory': None,
                    'path': '/video.tar',
                    'lifecycle': None,
                    'acl': 'public',
                    'bucket': None
                },
                'jobCallback': {
                    'url': 'https://call.me.back/',
                    'headers': None,
                    'attachment': None,
                    'passthrough': False
                }
            }))
    def test_extract_archive_request(self):
        payload = {
            'id': 'g_1',
            'groupId': '8c9063175f214bd78f8f6391dbc49a93',
            'type': 'urn:job:archive.extract',
            'issuer': 'urn:app:app-id',
            'status': 'success',
            'sources': [{
                'path': '/video.zip',
                'fileId': 'file id'
            }],
            'specification': {
                'source': {
                    'path': '/video.zip',
                    'fileId': 'file id'
                },
                'destination': {
                    'directory': '/video',
                    'path': None,
                    'acl': 'public',
                    'bucket': None
                },
                'extractedFilesReport': {
                    'destination': {
                        'directory': None,
                        'path': '/video.report.json',
                        'acl': 'public'
                    },
                    'format': 'json'
                }
            },
            'result': {
                'message': 'OK',
                'code': 0,
                'payload': {
                    'reportFileDescriptor': {
                        'path': '/video.report.json',
                        'id': 'report file id',
                        'acl': 'public',
                        'mimeType': 'application/json',
                        'size': 1718,
                        'hash': None,
                        'type': '-',
                        'dateUpdated': '2017-07-30T12:46:39Z',
                        'dateCreated': '2017-07-30T12:46:39Z',
                    }
                }
            },
            'dateCreated': '2017-07-30T12:46:31Z',
            'dateUpdated': '2017-07-30T12:46:40Z',
        }

        response = RestResult(0, 'OK', payload)
        httpretty.register_uri(httpretty.POST,
                               'https://fish.appspot.com/_api/archive/extract',
                               body=json.dumps(response.serialize()))

        job = self.archive_service.extract_archive_request().set_source(
            Source('/video.zip')).set_destination(
                Destination(directory='/video')).set_report(
                    ExtractionReport(Destination(path='/video.report.json'),
                                     ExtractionReportFormat.json)).execute()

        assert_that(job, instance_of(ExtractArchiveJob))
        assert_that(job.group_id, is_('g'))
        assert_that(
            json.loads(httpretty.last_request().body),
            is_({
                'source': {
                    'path': '/video.zip',
                    'fileId': None
                },
                'destination': {
                    'directory': '/video',
                    'path': None,
                    'lifecycle': None,
                    'acl': 'public',
                    'bucket': None
                },
                'extractedFilesReport': {
                    'destination': {
                        'directory': None,
                        'path': '/video.report.json',
                        'lifecycle': None,
                        'acl': 'public',
                        'bucket': None
                    },
                    'format': 'json'
                },
                'jobCallback': None
            }))