Skip to content

Commit df331d7

Browse files
biefanromanlutzCopilot
authored
Handle empty CSV exports in remote dataset cache (#1481)
Co-authored-by: Roman Lutz <romanlutz13@gmail.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 71eaa26 commit df331d7

3 files changed

Lines changed: 33 additions & 0 deletions

File tree

pyrit/common/csv_helper.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ def write_csv(file: IO[Any], examples: list[dict[str, str]]) -> None:
2424
file: A file-like object opened for writing CSV data.
2525
examples (List[Dict[str, str]]): List of dictionaries to write as CSV rows.
2626
"""
27+
if not examples:
28+
return
29+
2730
writer = csv.DictWriter(file, fieldnames=examples[0].keys())
2831
writer.writeheader()
2932
writer.writerows(examples)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT license.
3+
4+
import io
5+
6+
from pyrit.common.csv_helper import write_csv
7+
8+
9+
def test_write_csv_empty_examples_writes_nothing():
10+
file = io.StringIO()
11+
write_csv(file, [])
12+
assert file.getvalue() == ""
13+
14+
15+
def test_write_csv_writes_header_and_rows():
16+
file = io.StringIO()
17+
write_csv(file, [{"name": "alice", "role": "admin"}])
18+
lines = file.getvalue().strip().splitlines()
19+
assert lines[0] == "name,role"
20+
assert lines[1] == "alice,admin"

tests/unit/datasets/test_remote_dataset_loader.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,13 @@ def test_write_cache_creates_directories(self, tmp_path):
7272
loader._write_cache(cache_file=cache_file, examples=data, file_type="json")
7373

7474
assert cache_file.exists()
75+
76+
def test_write_cache_csv_allows_empty_examples(self, tmp_path):
77+
loader = ConcreteRemoteLoader()
78+
cache_file = tmp_path / "empty.csv"
79+
80+
loader._write_cache(cache_file=cache_file, examples=[], file_type="csv")
81+
82+
assert cache_file.exists()
83+
assert cache_file.read_text(encoding="utf-8") == ""
84+
assert loader._read_cache(cache_file=cache_file, file_type="csv") == []

0 commit comments

Comments
 (0)