From c3cc0e5a29e71fe2e8dae043c5069abacf093a5c Mon Sep 17 00:00:00 2001 From: chrisdebian Date: Fri, 6 Nov 2026 19:45:37 +0000 Subject: [PATCH 1/2] Report failed folder uploads and keep the description file A failed folder upload was silent: upload() returned the failure in its result, nothing read it, the command exited 0, and the description file was removed in `finally`, so the upload couldn't simply be run again. Now the failure is logged, the upload command exits non-zero, and the description file is only removed after a successful upload. Refused descriptions from upload_desc() also count as a failure. upload() still returns its result dict, because MapSyncer reads it. --- mapilio_kit/base/loader.py | 7 +- mapilio_kit/components/upload/upload.py | 13 ++- mapilio_kit/components/upload/uploader.py | 7 ++ tests/test_upload_failure.py | 113 ++++++++++++++++++++++ 4 files changed, 135 insertions(+), 5 deletions(-) create mode 100644 tests/test_upload_failure.py diff --git a/mapilio_kit/base/loader.py b/mapilio_kit/base/loader.py index bd8a643..a69b321 100644 --- a/mapilio_kit/base/loader.py +++ b/mapilio_kit/base/loader.py @@ -62,4 +62,9 @@ def perform_task(self, vars_args: dict): decomposer().perform_task(vars_args) valid_args = self.filter_args(vars_args) - return upload(**valid_args) \ No newline at end of file + result = upload(**valid_args) + # A failed folder upload is reported in the result, not raised, because + # MapSyncer reads it. Raise here so the command exits with an error. + if isinstance(result, dict) and not result.get("Success"): + raise RuntimeError(f"Upload failed: {result.get('Error')}") + return result \ No newline at end of file diff --git a/mapilio_kit/components/upload/upload.py b/mapilio_kit/components/upload/upload.py index 97a5548..254f433 100644 --- a/mapilio_kit/components/upload/upload.py +++ b/mapilio_kit/components/upload/upload.py @@ -132,12 +132,17 @@ def upload( dry_run=dry_run, organization_key=organization_key if organization_key else None, project_key=project_key if project_key else None) - #logger.warning(f"{Fore.GREEN}Upload has been successfully finished. Thanks for your contributions to Mapilio 🎉!{Fore.RESET}") - return {'Success': True} except Exception as e: + LOG.error( + f"{Fore.RED}Upload failed for {import_path}: {e}. " + f"Your image descriptions are kept in {desc_path}, " + f"so you can run the upload again.{Fore.RESET}" + ) return {'Success': False, "Error": e} - finally: - os.remove(desc_path) + + os.remove(desc_path) + #logger.warning(f"{Fore.GREEN}Upload has been successfully finished. Thanks for your contributions to Mapilio 🎉!{Fore.RESET}") + return {'Success': True} else: diff --git a/mapilio_kit/components/upload/uploader.py b/mapilio_kit/components/upload/uploader.py index 029cf8a..183c9b6 100644 --- a/mapilio_kit/components/upload/uploader.py +++ b/mapilio_kit/components/upload/uploader.py @@ -135,6 +135,7 @@ def upload_desc( return {"Success": True} except requests.exceptions.HTTPError as e: print(e.response.text) + return {"Success": False, "Error": str(e)} def upload_image_dir_and_description( @@ -177,6 +178,12 @@ def upload_image_dir_and_description( response_list.append(response['Success']) + failed = response_list.count(False) + if failed: + raise RuntimeError( + f"Descriptions for {failed} of {len(response_list)} sequence(s) were not accepted" + ) + if any(response_list): LOG.warning( f"{Fore.GREEN}Upload has been successfully finished. {sum(response_list)} sequence(s) out of {len(response_list)} sequences were uploaded correctly. Thanks for your contributions to Mapilio 🎉!{Fore.RESET}") diff --git a/tests/test_upload_failure.py b/tests/test_upload_failure.py new file mode 100644 index 0000000..32748d9 --- /dev/null +++ b/tests/test_upload_failure.py @@ -0,0 +1,113 @@ +"""A failed folder upload must be visible, exit non-zero and keep the metadata.""" + +import importlib.util +import json +import logging +from pathlib import Path + +import pytest +import requests + +from mapilio_kit.components.upload import upload as upload_module +from mapilio_kit.components.upload import uploader + +USER = {"SettingsEmail": "fixture@example.invalid", "user_upload_token": "synthetic-token"} + + +@pytest.fixture +def folder(tmp_path, monkeypatch): + desc_path = tmp_path / "mapilio_image_description.json" + desc_path.write_text(json.dumps([{"filename": "a.jpg", "heading": 1.0}])) + monkeypatch.setattr(upload_module, "user_items_retriever", lambda *_: USER) + monkeypatch.setattr(upload_module, "photo_uuid_generate", lambda user_email, descs: descs) + monkeypatch.setattr(upload_module.time, "sleep", lambda _: None) + return tmp_path, desc_path + + +def _fail_upload(*_args, **_kwargs): + raise RuntimeError("server said no") + + +def test_failed_upload_keeps_description_and_reports_it(folder, monkeypatch, caplog): + path, desc_path = folder + monkeypatch.setattr(uploader, "upload_image_dir_and_description", _fail_upload) + # The project logger doesn't propagate, so listen on it directly. + logger = upload_module.LOG + logger.addHandler(caplog.handler) + try: + with caplog.at_level(logging.ERROR, logger=logger.name): + result = upload_module.upload(str(path)) + finally: + logger.removeHandler(caplog.handler) + + assert result["Success"] is False + assert "server said no" in str(result["Error"]) + assert desc_path.exists() + assert "server said no" in caplog.text + assert str(desc_path) in caplog.text + + +def test_successful_upload_removes_description(folder, monkeypatch): + path, desc_path = folder + monkeypatch.setattr(uploader, "upload_image_dir_and_description", lambda *a, **k: None) + + assert upload_module.upload(str(path)) == {"Success": True} + assert not desc_path.exists() + + +def test_interrupted_upload_keeps_description(folder, monkeypatch): + path, desc_path = folder + + def interrupt(*_args, **_kwargs): + raise KeyboardInterrupt + + monkeypatch.setattr(uploader, "upload_image_dir_and_description", interrupt) + with pytest.raises(KeyboardInterrupt): + upload_module.upload(str(path)) + assert desc_path.exists() + + +def _load_upload_command(): + # Loaded by path: importing mapilio_kit.base pulls in the stubbed pipeline packages. + path = Path(upload_module.__file__).parents[2] / "base" / "loader.py" + spec = importlib.util.spec_from_file_location("upload_command_under_test", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.Upload() + + +def test_upload_command_raises_when_upload_fails(folder, monkeypatch): + """main() turns this exception into an error message and a non-zero exit.""" + path, _ = folder + monkeypatch.setattr(uploader, "upload_image_dir_and_description", _fail_upload) + + with pytest.raises(RuntimeError, match="server said no"): + _load_upload_command().perform_task({"processed": True, "import_path": str(path)}) + + +def test_rejected_description_upload_raises(tmp_path, monkeypatch): + """A sequence whose descriptions are refused must not count as a success.""" + response = requests.Response() + response.status_code = 500 + response._content = b"refused" + response.url = "https://api.example.invalid/upload" + + monkeypatch.setattr(uploader.requests, "request", lambda *a, **k: response) + monkeypatch.setattr(uploader.jsonschema, "validate", lambda **_: None) + monkeypatch.setattr(uploader, "_validate_descs", lambda *_: None) + monkeypatch.setattr(uploader, "_group_sequences_by_uuid", lambda _: {"seq": {}}) + monkeypatch.setattr( + uploader, "_zip_and_upload_single_sequence", lambda *a, **k: {"seq": {"count": 1}} + ) + monkeypatch.setattr( + uploader.upload_desc, + "__defaults__", + (None, None, None, str(tmp_path)), + ) + descs = [ + {"sequenceUuid": "seq", "heading": 1.0}, + {"Information": {"total_images": 1}}, + ] + + with pytest.raises(RuntimeError, match="1 of 1"): + uploader.upload_image_dir_and_description(str(tmp_path), descs, USER) From e3d30662f73e498579c257e365633c403035156b Mon Sep 17 00:00:00 2001 From: chrisdebian Date: Fri, 6 Nov 2026 19:55:04 +0000 Subject: [PATCH 2/2] Stub gps_anomaly in the test setup upload.py imports it at module level, and CI doesn't install it. tests.yml already says it's stubbed in conftest.py, but it wasn't, because no test imported upload.py until now. --- tests/conftest.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index f94ef33..e197829 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -38,6 +38,11 @@ def _install_stub(name: str, attrs: dict | None = None) -> None: ) +# ``gps-anomaly-detector`` isn't installed in CI. Upload imports it but tests don't use it. +_install_stub("gps_anomaly") +_install_stub("gps_anomaly.detector", {"Anomaly": object}) + + def _unexpected_coordinate_conversion(*args, **kwargs): raise AssertionError("Upload retry tests must not perform EXIF coordinate conversion")