diff --git a/modules/zim/lib.py b/modules/zim/lib.py index 5c9189b7..4c855bd6 100644 --- a/modules/zim/lib.py +++ b/modules/zim/lib.py @@ -540,7 +540,10 @@ ZIM_NAME_PARSER = re.compile(r'(.+?)_(\d{4}-\d{2}).zim') def parse_name(path: pathlib.Path) -> Tuple[str, datetime]: - name, date = ZIM_NAME_PARSER.match(path.name).groups() + match = ZIM_NAME_PARSER.match(path.name) + if not match: + raise ValueError(f'Zim file name does not match expected pattern: {path.name}') + name, date = match.groups() date = datetime.strptime(date, '%Y-%m') return name, date @@ -558,8 +561,8 @@ def find_outdated_zim_files(path: pathlib.Path = None) -> Tuple[List[pathlib.Pat for file in files: try: name, date = parse_name(file) - except Exception as e: - logger.warning(f'Found Zim {file} but its name does not match.', exc_info=e) + except Exception: + logger.warning(f'Found Zim {file} but its name does not match.') continue zims.append((name, date, file)) diff --git a/modules/zim/test/test_api.py b/modules/zim/test/test_api.py index 3d617c81..6cd83808 100644 --- a/modules/zim/test/test_api.py +++ b/modules/zim/test/test_api.py @@ -200,6 +200,22 @@ async def test_get_zim_entry(test_session, async_client, test_zim): assert response.status_code == HTTPStatus.NOT_FOUND +def test_parse_name(): + """Zim file names that match the kiwix naming scheme are parsed. Non-matching names raise ValueError.""" + import pathlib + from datetime import datetime + + name, date = lib.parse_name(pathlib.Path('wikipedia_en_all_maxi_2023-01.zim')) + assert name == 'wikipedia_en_all_maxi' + assert date == datetime(2023, 1, 1) + + with pytest.raises(ValueError): + lib.parse_name(pathlib.Path('edibleplantdb.zim')) + + with pytest.raises(ValueError): + lib.parse_name(pathlib.Path('nodate.zim')) + + @pytest.mark.asyncio async def test_find_outdated_zim_files(test_session, test_directory, test_zim_bytes, async_client): """Outdated Zim files are found and reported. They can automatically be deleted."""