Skip to content

Commit

Permalink
Added insert_records/insert_record and related tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
muddi900 authored Jul 24, 2024
1 parent 87b3504 commit 69902b5
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
40 changes: 39 additions & 1 deletion gspread/worksheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ def append_records(
ignore_extra_headers: bool = False,
default_blank: Any = "",
) -> None:
"""Update the sheet via records(list of dicts). The keys for the dicts must be the headers for the column.
"""Adds rows to the end of data range via records(list of dicts). The keys for the dicts must be the headers for the column.
Missing columns are filled with `default blank` in the row.
Expand Down Expand Up @@ -661,6 +661,44 @@ def append_record(
default_blank=default_blank,
)

def insert_records(
self,
rows: List[Dict[str, Any]],
ignore_extra_headers: bool = False,
default_blank: Any = "",
insert_row: int = 2,
) -> None:
cols = self.column_headers
insert_rows = []
for row in rows:
if not set(row).issubset(set(cols)) and not ignore_extra_headers:
raise GSpreadException("Extra headers found in the data set")

ins_row = []
for col in cols:
ins_row.append(row.get(col, default_blank))
insert_rows.append(ins_row)

self.insert_rows(
insert_rows,
row=insert_row,
value_input_option=ValueInputOption.user_entered,
)

def insert_record(
self,
row: Dict[str, Any],
ignore_extra_headers: bool = False,
default_blank: Any = "",
insert_row: int = 2,
) -> None:
self.insert_records(
[row],
ignore_extra_headers=ignore_extra_headers,
insert_row=insert_row,
default_blank=default_blank,
)

def get_all_cells(self) -> List[Cell]:
"""Returns a list of all `Cell` of the current sheet."""

Expand Down
42 changes: 42 additions & 0 deletions tests/worksheet_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1717,6 +1717,48 @@ def test_append_records(self):
],
)

@pytest.mark.vcr()
def test_insert_rows(self):
w = self.spreadsheet.sheet1
values = [
["header1", "header2"],
["value1", "value2"],
]
w.update(values, "A1:B2")
self.assertEqual(
w.get_all_values(value_render_option=utils.ValueRenderOption.unformatted),
values,
)

w.insert_records(
[
{"header1": "value3", "header2": "value4"},
{"header2": "value5"},
]
)

new_values = [
values[0],
["value3", "value4"],
["", "value5"],
]

self.assertEqual(w.get_all_values(), new_values)

with pytest.raises(GSpreadException):
w.insert_record({"header1": "error value1", "location": "error value2"})

w.insert_record(
{"header4": "ignore value", "header1": "value6", "header2": "value7"},
insert_row=4,
ignore_extra_headers=True,
)

self.assertEqual(
w.get_all_values(),
[*new_values, ["value6", "value7"]],
)

@pytest.mark.vcr()
def test_group_columns(self):
w = self.sheet
Expand Down

0 comments on commit 69902b5

Please sign in to comment.