Skip to content

Commit

Permalink
fix: raise SheetNotFoundError when reading a missing sheet name (#222)
Browse files Browse the repository at this point in the history
* fix: raise `SheetNotFoundError` when reading a missing sheet name

* chore: better error message
  • Loading branch information
PrettyWood authored Apr 5, 2024
1 parent 8060efa commit 21f7f22
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
16 changes: 14 additions & 2 deletions python/tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ def test_does_not_exist() -> None:
fastexcel.read_excel("path_does_not_exist.nope")


def test_sheet_not_found_error() -> None:
def test_sheet_idx_not_found_error() -> None:
excel_reader = fastexcel.read_excel(path_for_fixture("fixture-single-sheet.xlsx"))
expected_message = """sheet at index 42 not found
Context:
0: Sheet index 42 is out of range. File has 1 sheets"""
0: Sheet index 42 is out of range. File has 1 sheets."""

with pytest.raises(fastexcel.SheetNotFoundError, match=expected_message) as exc_info:
excel_reader.load_sheet(42)
Expand All @@ -43,6 +43,18 @@ def test_sheet_not_found_error() -> None:
excel_reader.load_sheet(42)


def test_sheet_name_not_found_error() -> None:
excel_reader = fastexcel.read_excel(path_for_fixture("fixture-single-sheet.xlsx"))
expected_message = """sheet with name "idontexist" not found
Context:
0: Sheet "idontexist" not found in file. Available sheets: "January"."""

with pytest.raises(fastexcel.SheetNotFoundError, match=expected_message) as exc_info:
excel_reader.load_sheet("idontexist")

assert exc_info.value.__doc__ == "Sheet was not found"


@pytest.mark.parametrize(
"exc_class, expected_docstring",
[
Expand Down
15 changes: 13 additions & 2 deletions src/types/python/excelreader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,14 +144,25 @@ impl ExcelReader {
let name = idx_or_name
.try_into()
.and_then(|idx_or_name| match idx_or_name {
IdxOrName::Name(name) => Ok(name),
IdxOrName::Name(name) => {
if self.sheet_names.contains(&name) {
Ok(name)
} else {
Err(FastExcelErrorKind::SheetNotFound(IdxOrName::Name(name.clone())).into()).with_context(|| {
let available_sheets = self.sheet_names.iter().map(|s| format!("\"{s}\"")).collect::<Vec<_>>().join(", ");
format!(
"Sheet \"{name}\" not found in file. Available sheets: {available_sheets}."
)
})
}
}
IdxOrName::Idx(idx) => self
.sheet_names
.get(idx)
.ok_or_else(|| FastExcelErrorKind::SheetNotFound(IdxOrName::Idx(idx)).into())
.with_context(|| {
format!(
"Sheet index {idx} is out of range. File has {} sheets",
"Sheet index {idx} is out of range. File has {} sheets.",
self.sheet_names.len()
)
})
Expand Down

0 comments on commit 21f7f22

Please sign in to comment.