Example #1
0
    def download(self, headers, url, path, callback=None):
        """Downloads a file to the stated path

        Args:
            headers (dict of (str, str)): A dictionary of name-value
                pairs to be used as headers in the request
            url (str): The URL from which to download the file
            path (str): The local path to save the downloaded file

        Returns:
            :class:`HttpResponse<onedrivesdk.http_response.HttpResponse>`:
                The response to the request
        """
        response = requests.get(url, stream=True, headers=headers)

        if response.status_code == 200:
            total_length = response.headers.get('content-length')
            if total_length:
                total_length = int(total_length)
                dl = 0
            with open(path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=1024):
                    if callable(callback):
                        dl += len(chunk)
                        callback(dl / total_length)
                    if chunk:
                        f.write(chunk)
                        f.flush()
            custom_response = HttpResponse(response.status_code,
                                           response.headers, None)
        else:
            custom_response = HttpResponse(response.status_code,
                                           response.headers, response.text)

        return custom_response
Example #2
0
        def download(self, headers, url, path):

            response = requests.head(url, headers=headers)
            if response.status_code in [301, 302]:
                response = requests.head(response.headers['Location'], headers=headers)

            if response.status_code == 200:
                getFileWork(response.url, path, headers)
                custom_response = HttpResponse(response.status_code, response.headers, None)
            else:
                custom_response = HttpResponse(response.status_code, response.headers, response.text)

            return custom_response
Example #3
0
    def test_polling_background_method(self, MockHttpProvider,
                                       MockAuthProvider):
        """
        Test that polling in the background actually functions as it should and polls
        on a seperate thread.
        """
        response = HttpResponse(301, {"Location": "statusLocation"}, "")
        instance_http = MockHttpProvider.return_value
        instance_http.send.return_value = response

        instance_auth = MockAuthProvider.return_value
        instance_auth.authenticate.return_value = "blah"
        instance_auth.authenticate_request.return_value = None

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider,
                                            auth_provider)

        ref = ItemReference()
        ref.id = "testing!id"
        mock = Mock()

        copy_operation = client.drives["me"].items["testitem!id"].copy(
            parent_reference=ref, name="newName").request().post()

        response = HttpResponse(
            200, None,
            json.dumps({
                "operation": "copy",
                "percentageComplete": 0,
                "status": "In progress"
            }))
        instance_http.send.return_value = response

        time.sleep(0.2)

        assert copy_operation.item is None

        response = HttpResponse(
            200, None, json.dumps({
                "id": "testitem!id",
                "name": "newName"
            }))
        instance_http.send.return_value = response

        time.sleep(0.1)

        assert copy_operation.item is not None
Example #4
0
def resume_session(data):
    req = requests.get(data["uploadUrl"])
    HttpResponse(req.status_code, req.headers, req.content)
    result = convert_utf8_dict_to_dict(req.json())
    for k in ("expirationDateTime", "nextExpectedRanges"):
        data[k] = result[k]
    return data
Example #5
0
    def test_method_collections(self, MockHttpProvider, MockAuthProvider):
        """
        Test that collections are returned properly from method calls that return collections
        """
        response = HttpResponse(
            200, None,
            json.dumps({
                "@odata.nextLink":
                "testing",
                "value": [{
                    "name": "test1",
                    "folder": {}
                }, {
                    "name": "test2"
                }]
            }))

        instance = MockHttpProvider.return_value
        instance.send.return_value = response

        instance = MockAuthProvider.return_value
        instance.authenticate.return_value = "blah"
        instance.authenticate_request.return_value = None

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl", http_provider,
                                            auth_provider)

        items = client.drives["me"].items["testitem!id"].delta().request().get(
        )
        request = onedrivesdk.ItemDeltaRequest.get_next_page_request(
            items, client, None)
        assert type(request) is ItemDeltaRequest
        assert type(request.get()) is ItemDeltaCollectionPage
Example #6
0
    def test_error(self, MockHttpProvider, MockAuthProvider):
        """
        Test that the error is thrown and can be correctly handled
        """
        try:
            response = HttpResponse(
                404, None,
                json.dumps({
                    "error": {
                        "code": "itemNotFound",
                        "message": "The resource could not be found"
                    }
                }))
            assert False
        except OneDriveError as e:
            assert e.status_code == 404
            assert e.code == ErrorCode.ItemNotFound

        try:
            response = HttpResponse(
                403, None,
                json.dumps({
                    "error": {
                        "code": "generalException",
                        "message": "TestMessage",
                        "innererror": {
                            "code": "accessDenied",
                            "message": "TestMessage",
                            "innererror": {
                                "code": "unauthenticated",
                                "message": "TestMessage"
                            }
                        }
                    }
                }))
            assert False
        except OneDriveError as e:
            assert e.status_code == 403
            assert e.code == ErrorCode.GeneralException
            assert e.matches(ErrorCode.AccessDenied)
            assert e.matches(ErrorCode.Unauthenticated)
            assert not e.matches(ErrorCode.NotSupported)
    def test_download(self, MockHttpProvider, MockAuthProvider):

        path = "./myPath/myFile.txt"
        response = HttpResponse(200, None, None)

        instance = MockHttpProvider.return_value
        instance.download.return_value = response

        instance = MockAuthProvider.return_value
        instance.authenticate.return_value = "blah"
        instance.authenticate_request.return_value = None

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider, auth_provider)
        client.drives["me"].items["root"].children["newFile.txt"].content.request().download(path)

        assert client.http_provider.download.call_args[0][2] == path
        assert client.http_provider.download.call_args[0][1] == "onedriveurl/drives/me/items/root/children/newFile.txt/content"
    def test_put(self, MockHttpProvider, MockAuthProvider):

        response = HttpResponse(200, None, json.dumps({"name":"test1", "folder":{}, "id":"test!id"}))

        instance = MockHttpProvider.return_value
        instance.send.return_value = response

        instance = MockAuthProvider.return_value
        instance.authenticate.return_value = "blah"
        instance.authenticate_request.return_value = None

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider, auth_provider)

        response_item = client.drives["me"].items["root"].children["newFile.txt"].content.request().upload("./myPath/myFile.txt")

        assert client.http_provider.send.call_args[1]["path"] == "./myPath/myFile.txt"
        assert client.http_provider.send.call_args[0][2] == "onedriveurl/drives/me/items/root/children/newFile.txt/content"
        assert all(item in response_item._prop_dict.items() for item in json.loads(response.content).items())
    def test_paging(self, MockHttpProvider, MockAuthProvider):
        """
        Test paging of a file in situations where more than one page is available
        """
        response = HttpResponse(200, None, json.dumps({"@odata.nextLink":"testing", "value":[{"name":"test1", "folder":{}}, {"name":"test2"}]}))

        instance = MockHttpProvider.return_value
        instance.send.return_value = response

        instance = MockAuthProvider.return_value
        instance.authenticate.return_value = "blah"
        instance.authenticate_request.return_value = None

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider, auth_provider)

        items = client.drives["me"].items["root"].children.request().get()
        
        assert type(items.next_page_request) is ChildrenCollectionRequest
        assert type(items.next_page_request.get()) is ChildrenCollectionPage
Example #10
0
def create_session(api_base_url, token, source_file, dest_path):
    filename = os.path.basename(source_file)
    if not dest_path.endswith('/'):
        dest_path += '/'
    dest_path += filename

    api_url = api_base_url + \
        'drive/root:{dest_path}:/upload.createSession'.format(
            dest_path=dest_path)
    headers = {
        'Authorization': 'bearer {access_token}'.format(access_token=token),
        'content-type': 'application/json'
    }
    info_json = json.dumps(
        {'item': {
            '@name.conflictBehavior': 'fail',
            'name': filename
        }},
        sort_keys=True)

    # logger.debug("headers: %s, request data: %s" % (headers, info_json))
    req = requests.post(api_url, data=info_json, headers=headers)
    HttpResponse(req.status_code, req.headers, req.content)
    return convert_utf8_dict_to_dict(req.json())
Example #11
0
    def test_page_creation(self, MockHttpProvider, MockAuthProvider):
        """
        Test page creation when there is no nextLink attached to the collection
        """
        response = HttpResponse(200, None, json.dumps({"value":[{"name":"test1", "folder":{}}, {"name":"test2"}]}))

        instance = MockHttpProvider.return_value
        instance.send.return_value = response

        instance = MockAuthProvider.return_value
        instance.authenticate.return_value = "blah"
        instance.authenticate_request.return_value = None

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider, auth_provider)

        items = client.drives["me"].items["root"].children.request().get()
        
        assert len(items) == 2
        assert isinstance(items, ChildrenCollectionPage)
        assert items[0].name == "test1"
        assert isinstance(items[0].folder, Folder)
        assert items[1].folder is None