Skip to content

Commit

Permalink
Added first tests to excel_to_entities function
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosmada22 committed Feb 5, 2025
1 parent 759b918 commit a4a6b70
Show file tree
Hide file tree
Showing 2 changed files with 151 additions and 0 deletions.
11 changes: 11 additions & 0 deletions bam_masterdata/excel/excel_to_entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ def index_to_excel_column(self, index: int) -> str:
Returns:
The corresponding Excel column name.
"""
if not index >= 1:
raise ValueError("Index must be a positive integer starting from 1.")

column = ""
while index > 0:
index, remainder = divmod(index - 1, 26)
Expand All @@ -58,6 +61,11 @@ def get_last_non_empty_row(
The row number of the last non-empty row before an empty row is encountered,
or None if no non-empty rows are found starting from the given index.
"""
if start_index < 1 or start_index > sheet.max_row:
raise ValueError(
f"Invalid start index: {start_index}. It must be between 1 and {sheet.max_row}."
)

last_non_empty_row = None
for row in range(start_index, sheet.max_row + 1):
if all(
Expand All @@ -81,6 +89,9 @@ def is_reduced_version(self, generated_code_value: str, code: str) -> bool:
Returns:
bool: True if generated_code_value is a reduced version of code, False otherwise.
"""
if code.startswith(generated_code_value):
return True

# Check if both are single words (no delimiters)
if not any(delimiter in code for delimiter in "._") and not any(
delimiter in generated_code_value for delimiter in "._"
Expand Down
140 changes: 140 additions & 0 deletions tests/excel/test_excel_to_entities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import openpyxl
import pytest

from bam_masterdata.excel import MasterdataExcelExtractor


@pytest.fixture
def excel_extractor(tmp_path):
"""Fixture to create an instance of MasterdataExcelExtractor with a dummy Excel file."""
# Create a dummy Excel file in the temporary test directory
dummy_excel = tmp_path / "test.xlsx"
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Sheet1"

# Add some dummy data
ws.append(["Header1", "Header2", "Header3"])
ws.append(["Data1", "Data2", "Data3"])
ws.append(["", "", ""]) # Empty row
ws.append(["Last", "Row", "Data"])

wb.save(dummy_excel)

# Create an instance with the dummy file
return MasterdataExcelExtractor(excel_path=str(dummy_excel))


# Tests for `index_to_excel_column`
@pytest.mark.parametrize(
"index, expected_column",
[
(1, "A"),
(2, "B"),
(26, "Z"),
(27, "AA"),
(28, "AB"),
(52, "AZ"),
(53, "BA"),
(702, "ZZ"),
(703, "AAA"),
(704, "AAB"),
(1378, "AZZ"),
(1379, "BAA"),
(18278, "ZZZ"),
(18279, "AAAA"),
(18280, "AAAB"),
],
)
def test_index_to_excel_column(excel_extractor, index, expected_column):
"""Tests the index_to_excel_column method."""
result = excel_extractor.index_to_excel_column(index)
assert result == expected_column


# # Failing cases for `index_to_excel_column`
# @pytest.mark.parametrize(
# "invalid_index",
# [-1, 0, "ABC", None, 3.5], # Invalid cases
# )
# def test_index_to_excel_column_invalid(excel_extractor, invalid_index):
# """Tests that index_to_excel_column fails with invalid input."""
# with pytest.raises(ValueError):
# excel_extractor.index_to_excel_column(invalid_index)


# Tests for `get_last_non_empty_row`
def test_get_last_non_empty_row(excel_extractor):
"""Tests finding the last non-empty row."""
sheet = excel_extractor.workbook["Sheet1"]

result = excel_extractor.get_last_non_empty_row(sheet, 1)

assert result == 2 # Last non-empty row should be 4


# # Failing cases for `get_last_non_empty_row`
# @pytest.mark.parametrize(
# "invalid_sheet, start_index, expected_exception",
# [
# (None, 1, AttributeError), # No sheet provided
# ("Not a sheet", 1, KeyError), # Invalid type
# ("Sheet1", -1, ValueError), # Negative index
# ("Sheet1", "ABC", TypeError), # Non-integer index
# ("Sheet1", 999, ValueError), # Index out of bounds
# ],
# )
# def test_get_last_non_empty_row_invalid(
# excel_extractor, invalid_sheet, start_index, expected_exception
# ):
# """Tests that get_last_non_empty_row fails with invalid input."""
# try:
# sheet = (
# excel_extractor.workbook[invalid_sheet]
# if isinstance(invalid_sheet, str)
# else invalid_sheet
# )
# except KeyError:
# if expected_exception is KeyError:
# return # Test passes if KeyError was expected
# raise # Otherwise, raise the error

# with pytest.raises(expected_exception):
# excel_extractor.get_last_non_empty_row(sheet, start_index)


# Tests for `is_reduced_version`
@pytest.mark.parametrize(
"generated_code, full_code, expected_result",
[
("ABC", "ABC", True), # Identical codes
("ABC", "ABC_DEF", True), # Not a reduced version
("ABC.DEF", "ABC.DEF.GHI", True), # Matching delimiter (.)
("ABC_DEF", "ABC_DEF_GHI", True), # Matching delimiter (_)
("ABC.DEF", "ABC_DEF_GHI", False), # Mismatched delimiters
],
)
def test_is_reduced_version(
excel_extractor, generated_code, full_code, expected_result
):
"""Tests whether generated_code_value is a reduced version of code."""
result = excel_extractor.is_reduced_version(generated_code, full_code)
assert result == expected_result


# # Failing cases for `is_reduced_version`
# @pytest.mark.parametrize(
# "generated_code, full_code, expected_exception",
# [
# (None, "ABC.DEF", TypeError), # None input
# ("ABC.DEF", None, TypeError), # None input
# (123, "ABC.DEF", TypeError), # Non-string input
# ("ABC.DEF", 456, TypeError), # Non-string input
# ],
# )
# def test_is_reduced_version_invalid(
# excel_extractor, generated_code, full_code, expected_exception
# ):
# """Tests that is_reduced_version fails with invalid input."""
# with pytest.raises(expected_exception):
# excel_extractor.is_reduced_version(generated_code, full_code)

1 comment on commit a4a6b70

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report
FileStmtsMissCoverMissing
bam_masterdata
   logger.py80100% 
bam_masterdata/cli
   cli.py794646 42%
   entities_to_excel.py5433 94%
   entities_to_json.py3655 86%
   fill_masterdata.py195181181 7%
bam_masterdata/datamodel
   collection_types.py370100% 
   dataset_types.py184184184 0%
   object_types.py15150100% 
   property_types.py8000100% 
   vocabulary_types.py137210100% 
bam_masterdata/excel
   excel_to_entities.py197149149 24%
bam_masterdata/metadata
   definitions.py780100% 
   entities.py5433 94%
bam_masterdata/openbis
   get_entities.py534343 19%
   login.py633 50%
bam_masterdata/utils
   utils.py6299 85%
TOTAL1707962696% 

Tests Skipped Failures Errors Time
98 1 💤 0 ❌ 0 🔥 18.902s ⏱️

Please sign in to comment.