Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method to download an attachment #181

Merged
merged 1 commit into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions allspice/apiobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -1531,6 +1531,28 @@ def __eq__(self, other):
def __hash__(self):
return hash(self.uuid)

def download_to_file(self, io: IO):
"""
Download the raw, binary data of this Attachment to a file-like object.

Example:

with open("my_file.zip", "wb") as f:
attachment.download_to_file(f)

:param io: The file-like object to write the data to.
"""

response = self.allspice_client.requests.get(
self.browser_download_url,
headers=self.allspice_client.headers,
stream=True,
)
# 4kb chunks
for chunk in response.iter_content(chunk_size=4096):
if chunk:
io.write(chunk)


class Comment(ApiObject):
assets: List[Union[Any, Dict[str, Union[int, str]]]]
Expand Down
21 changes: 21 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,27 @@ def test_get_issue_attachments(instance):
assert attachments[0].name == "requirements.txt"


def test_download_issue_attachment(instance, tmp_path):
org = Organization.request(instance, test_org)
repo = Repository.request(instance, org.username, test_repo)
issue = repo.get_issues()[0]
comment = issue.get_comments()[0]
attachment = comment.get_attachments()[0]

filename = uuid.uuid4().hex[:8] + ".txt"
filepath = tmp_path / filename
with open(filepath, "wb") as f:
attachment.download_to_file(f)

with open(filepath, "r") as actual_f:
with open("requirements.txt", "r") as expected_f:
attachment_content = actual_f.read()
assert len(attachment_content) > 0

expected_content = expected_f.read()
assert expected_content == attachment_content


def test_edit_issue_attachment(instance):
org = Organization.request(instance, test_org)
repo = Repository.request(instance, org.username, test_repo)
Expand Down