Download tasks/data/forward/accessibleapps__app_updater.646aac1/solution/golden.patch from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 63.2 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/accessibleapps__app_updater.646aac1/solution/golden.patch
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/accessibleapps__app_updater.646aac1/solution/golden.patch
-
curl -L -o golden.patch https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/accessibleapps__app_updater.646aac1/solution/golden.patch
63.2 kB
diff --git a/autoupdate/__init__.py b/autoupdate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d876613a4250bc82cd8a85a8a823535dde6876c7
--- /dev/null
+++ b/autoupdate/__init__.py
@@ -0,0 +1,13 @@
+import glob
+import os.path
+import platform
+
+
+def find_datafiles():
+ system = platform.system()
+ if system == "Windows":
+ file_ext = "*.exe"
+ else:
+ file_ext = "*.sh"
+ path = os.path.abspath(os.path.join(__path__[0], "bootstrappers", file_ext))
+ return [("", glob.glob(path))]
diff --git a/autoupdate/autoupdate.py b/autoupdate/autoupdate.py
new file mode 100644
index 0000000000000000000000000000000000000000..b92fdff66ca556783711f75739ff5141c80cf5f1
--- /dev/null
+++ b/autoupdate/autoupdate.py
@@ -0,0 +1,144 @@
+import contextlib
+import io
+import os
+import platform
+import tempfile
+import zipfile
+from logging import getLogger
+
+import requests
+from packaging.version import Version
+from platform_utils import paths
+
+logger = getLogger("autoupdate")
+
+
+def perform_update(
+ endpoint,
+ current_version,
+ app_name="",
+ password=None,
+ update_available_callback=None,
+ progress_callback=None,
+ update_complete_callback=None,
+):
+ requests_session = create_requests_session(app_name=app_name, version=current_version)
+ available_update = find_update(endpoint, requests_session=requests_session)
+ if not available_update:
+ return
+ available_version = available_update["current_version"]
+ if (
+ Version(str(available_version)) <= Version(str(current_version))
+ or platform.system() not in available_update["downloads"]
+ ):
+ return
+ available_description = available_update.get("description", None)
+ update_url = available_update["downloads"][platform.system()]
+ logger.info(f"A new update is available. Version {available_version}")
+ if callable(update_available_callback) and not update_available_callback(
+ version=available_version, description=available_description
+ ): # update_available_callback should return a falsy value to stop the process
+ logger.info("User canceled update.")
+ return
+ base_path = tempfile.mkdtemp()
+ download_path = os.path.join(base_path, "update.zip")
+ update_path = os.path.join(base_path, "update")
+ downloaded = download_update(
+ update_url, download_path, requests_session=requests_session, progress_callback=progress_callback
+ )
+ extracted = extract_update(downloaded, update_path, password=password)
+ bootstrap_path = move_bootstrap(extracted)
+ execute_bootstrap(bootstrap_path, extracted)
+ logger.info("Update prepared for installation.")
+ if callable(update_complete_callback):
+ update_complete_callback()
+
+
+def create_requests_session(app_name=None, version=None):
+ user_agent = ""
+ session = requests.session()
+ if app_name:
+ user_agent = f" {app_name}/{version!r}"
+ session.headers["User-Agent"] = str(session.headers["User-Agent"]) + user_agent
+ return session
+
+
+def find_update(endpoint, requests_session):
+ response = requests_session.get(endpoint)
+ response.raise_for_status()
+ content = response.json()
+ return content
+
+
+def download_update(
+ update_url, update_destination, requests_session, progress_callback=None, chunk_size=io.DEFAULT_BUFFER_SIZE
+):
+ total_downloaded = total_size = 0
+ with open(update_destination, "w+b") as outfile:
+ download = requests_session.get(update_url, stream=True)
+ total_size = int(download.headers.get("content-length", 0))
+ logger.debug(f"Total update size: {total_size}")
+ download.raise_for_status()
+ for chunk in download.iter_content(chunk_size):
+ outfile.write(chunk)
+ total_downloaded += len(chunk)
+ if callable(progress_callback):
+ call_callback(progress_callback, total_downloaded, total_size)
+ logger.debug("Update downloaded")
+ return update_destination
+
+
+def extract_update(update_archive, destination, password=None):
+ """Given an update archive, extracts it. Returns the directory to which it has been extracted"""
+ with contextlib.closing(zipfile.ZipFile(update_archive)) as archive:
+ if password:
+ archive.setpassword(password)
+ archive.extractall(path=destination)
+ logger.debug("Update extracted")
+ return destination
+
+
+def move_bootstrap(extracted_path):
+ working_path = os.path.abspath(os.path.join(extracted_path, ".."))
+ if platform.system() == "Darwin":
+ extracted_path = os.path.join(extracted_path, "Contents", "Resources")
+ downloaded_bootstrap = os.path.join(extracted_path, bootstrap_name())
+ new_bootstrap_path = os.path.join(working_path, bootstrap_name())
+ os.rename(downloaded_bootstrap, new_bootstrap_path)
+ return new_bootstrap_path
+
+
+def execute_bootstrap(bootstrap_path, source_path):
+ arguments = rf'"{os.getpid()}" "{source_path}" "{paths.app_path()}" "{paths.get_executable()}"'
+ if platform.system() == "Windows":
+ import win32api
+
+ win32api.ShellExecute(0, "open", bootstrap_path, arguments, "", 5)
+ else:
+ import subprocess
+
+ make_executable(bootstrap_path)
+ subprocess.Popen([f"{bootstrap_path} {arguments}"], shell=True)
+ logger.info("Bootstrap executed")
+
+
+def bootstrap_name():
+ if platform.system() == "Windows":
+ return "bootstrap.exe"
+ if platform.system() == "Darwin":
+ return "bootstrap-mac.sh"
+ return "bootstrap-lin.sh"
+
+
+def make_executable(path):
+ import stat
+
+ st = os.stat(path)
+ os.chmod(path, st.st_mode | stat.S_IEXEC)
+
+
+def call_callback(callback, *args, **kwargs):
+ try:
+ callback(*args, **kwargs)
+ except Exception:
+ logger.exception(f"Failed calling callback {callback!r} with args {args!r} and kwargs {kwargs!r}")
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8ccfe74ca1fa4d7625a554e1ac52953803babe5
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,126 @@
+"""Shared pytest fixtures for autoupdate tests."""
+
+import io
+import os
+import tempfile
+import zipfile
+from unittest.mock import Mock
+
+import pytest
+
+
+@pytest.fixture
+def temp_dir():
+ """Create a temporary directory for test files."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ yield tmpdir
+
+
+@pytest.fixture
+def sample_update_response():
+ """Sample update check response."""
+ return {
+ "current_version": "2.0.0",
+ "description": "New update available with bug fixes",
+ "downloads": {
+ "Windows": "https://example.com/app-2.0.0-win.zip",
+ "Darwin": "https://example.com/app-2.0.0-mac.zip",
+ "Linux": "https://example.com/app-2.0.0-linux.zip",
+ },
+ }
+
+
+@pytest.fixture
+def no_update_response():
+ """Response indicating no update available."""
+ return {
+ "current_version": "1.0.0",
+ "description": "Current version",
+ "downloads": {
+ "Windows": "https://example.com/app-1.0.0-win.zip",
+ "Darwin": "https://example.com/app-1.0.0-mac.zip",
+ "Linux": "https://example.com/app-1.0.0-linux.zip",
+ },
+ }
+
+
+@pytest.fixture
+def incomplete_update_response():
+ """Update response missing current platform."""
+ return {
+ "current_version": "2.0.0",
+ "description": "Update available",
+ "downloads": {
+ "OtherOS": "https://example.com/app-2.0.0-other.zip",
+ },
+ }
+
+
+@pytest.fixture
+def mock_callback():
+ """Create a mock callback function."""
+ return Mock(return_value=True)
+
+
+@pytest.fixture
+def mock_progress_callback():
+ """Create a mock progress callback."""
+ return Mock()
+
+
+@pytest.fixture
+def zip_file_path(temp_dir):
+ """Create a test zip file with a dummy bootstrap script."""
+ zip_path = os.path.join(temp_dir, "test_update.zip")
+
+ # Create a zip file with test content
+ with zipfile.ZipFile(zip_path, "w") as zf:
+ # Add a dummy bootstrap file
+ zf.writestr("bootstrap.exe", b"fake bootstrap content")
+ zf.writestr("app_file.txt", b"application content")
+
+ return zip_path
+
+
+@pytest.fixture
+def password_protected_zip(temp_dir):
+ """Create a password-protected zip file."""
+ zip_path = os.path.join(temp_dir, "protected_update.zip")
+ password = b"test_password"
+
+ # Create a password-protected zip
+ with zipfile.ZipFile(zip_path, "w") as zf:
+ zf.setpassword(password)
+ zf.writestr("bootstrap.exe", b"protected bootstrap", compress_type=zipfile.ZIP_DEFLATED)
+ zf.writestr("app_file.txt", b"protected app content", compress_type=zipfile.ZIP_DEFLATED)
+
+ return zip_path, password
+
+
+@pytest.fixture
+def mock_file_content():
+ """Create mock file content for download tests."""
+ return b"This is test update file content" * 1000 # ~33KB
+
+
+@pytest.fixture
+def chunked_file_content():
+ """Create chunked file content to test streaming."""
+ chunks = [b"chunk1" * 100, b"chunk2" * 100, b"chunk3" * 100]
+ return chunks, b"".join(chunks)
+
+
+@pytest.fixture(autouse=True)
+def reset_logging():
+ """Reset logging between tests."""
+ import logging
+
+ # Clear all handlers from the autoupdate logger
+ logger = logging.getLogger("autoupdate")
+ logger.handlers.clear()
+ logger.setLevel(logging.DEBUG)
+
+ yield
+
+ # Cleanup after test
+ logger.handlers.clear()
diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ffce4f8412de0881f79d4ad31dcfa752f2ae595
--- /dev/null
+++ b/tests/test_bootstrap.py
@@ -0,0 +1,218 @@
+"""Tests for bootstrap operations."""
+
+import os
+import platform
+import stat
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+from autoupdate.autoupdate import bootstrap_name, execute_bootstrap, make_executable, move_bootstrap
+
+
+class TestBootstrapName:
+ """Tests for bootstrap_name function."""
+
+ @patch("platform.system", return_value="Windows")
+ def test_bootstrap_name_windows(self, mock_system):
+ """Test bootstrap name on Windows."""
+ assert bootstrap_name() == "bootstrap.exe"
+
+ @patch("platform.system", return_value="Darwin")
+ def test_bootstrap_name_macos(self, mock_system):
+ """Test bootstrap name on macOS."""
+ assert bootstrap_name() == "bootstrap-mac.sh"
+
+ @patch("platform.system", return_value="Linux")
+ def test_bootstrap_name_linux(self, mock_system):
+ """Test bootstrap name on Linux."""
+ assert bootstrap_name() == "bootstrap-lin.sh"
+
+
+class TestMoveBootstrap:
+ """Tests for move_bootstrap function."""
+
+ @patch("platform.system", return_value="Windows")
+ def test_move_bootstrap_windows(self, mock_system, temp_dir):
+ """Test moving bootstrap on Windows."""
+ # Setup: create extracted directory with bootstrap
+ extracted_dir = os.path.join(temp_dir, "extracted")
+ os.makedirs(extracted_dir)
+ bootstrap_src = os.path.join(extracted_dir, "bootstrap.exe")
+
+ with open(bootstrap_src, "w") as f:
+ f.write("fake bootstrap")
+
+ # Execute
+ result = move_bootstrap(extracted_dir)
+
+ # Verify bootstrap moved to parent directory
+ expected_path = os.path.join(temp_dir, "bootstrap.exe")
+ assert result == expected_path
+ assert os.path.exists(expected_path)
+ assert not os.path.exists(bootstrap_src)
+
+ @patch("platform.system", return_value="Darwin")
+ def test_move_bootstrap_macos(self, mock_system, temp_dir):
+ """Test moving bootstrap on macOS (from Contents/Resources)."""
+ # Setup: create macOS app bundle structure
+ extracted_dir = os.path.join(temp_dir, "extracted")
+ resources_dir = os.path.join(extracted_dir, "Contents", "Resources")
+ os.makedirs(resources_dir)
+ bootstrap_src = os.path.join(resources_dir, "bootstrap-mac.sh")
+
+ with open(bootstrap_src, "w") as f:
+ f.write("#!/bin/bash\necho test")
+
+ # Execute
+ result = move_bootstrap(extracted_dir)
+
+ # Verify bootstrap moved to working directory (parent of extracted)
+ expected_path = os.path.join(temp_dir, "bootstrap-mac.sh")
+ assert result == expected_path
+ assert os.path.exists(expected_path)
+ assert not os.path.exists(bootstrap_src)
+
+ @patch("platform.system", return_value="Linux")
+ def test_move_bootstrap_linux(self, mock_system, temp_dir):
+ """Test moving bootstrap on Linux."""
+ # Setup
+ extracted_dir = os.path.join(temp_dir, "extracted")
+ os.makedirs(extracted_dir)
+ bootstrap_src = os.path.join(extracted_dir, "bootstrap-lin.sh")
+
+ with open(bootstrap_src, "w") as f:
+ f.write("#!/bin/bash\necho test")
+
+ # Execute
+ result = move_bootstrap(extracted_dir)
+
+ # Verify
+ expected_path = os.path.join(temp_dir, "bootstrap-lin.sh")
+ assert result == expected_path
+ assert os.path.exists(expected_path)
+ assert not os.path.exists(bootstrap_src)
+
+
+class TestMakeExecutable:
+ """Tests for make_executable function."""
+
+ @pytest.mark.skipif(platform.system() == "Windows", reason="Windows doesn't use Unix execute permissions")
+ def test_make_executable(self, temp_dir):
+ """Test making a file executable on Unix systems."""
+ # Create a test file
+ test_file = os.path.join(temp_dir, "test_script.sh")
+ with open(test_file, "w") as f:
+ f.write("#!/bin/bash\necho test")
+
+ # Get initial permissions
+ initial_stat = os.stat(test_file)
+ initial_mode = initial_stat.st_mode
+
+ # Make executable
+ make_executable(test_file)
+
+ # Verify executable bit is set
+ new_stat = os.stat(test_file)
+ new_mode = new_stat.st_mode
+ assert new_mode & stat.S_IEXEC
+ # Verify file is executable
+ assert os.access(test_file, os.X_OK)
+
+
+class TestExecuteBootstrap:
+ """Tests for execute_bootstrap function."""
+
+ @pytest.mark.windows
+ @patch("platform.system", return_value="Windows")
+ @patch("win32api.ShellExecute")
+ @patch("os.getpid", return_value=12345)
+ @patch("platform_utils.paths.app_path", return_value="C:\\App")
+ @patch("platform_utils.paths.get_executable", return_value="C:\\App\\app.exe")
+ def test_execute_bootstrap_windows(
+ self, mock_get_exe, mock_app_path, mock_getpid, mock_shell_exec, mock_system
+ ):
+ """Test executing bootstrap on Windows."""
+ bootstrap_path = "C:\\temp\\bootstrap.exe"
+ source_path = "C:\\temp\\update"
+
+ execute_bootstrap(bootstrap_path, source_path)
+
+ # Verify ShellExecute was called correctly
+ mock_shell_exec.assert_called_once()
+ args = mock_shell_exec.call_args[0]
+ assert args[0] == 0 # hwnd
+ assert args[1] == "open" # operation
+ assert args[2] == bootstrap_path # file
+ # args[3] should be the arguments string
+ assert "12345" in args[3] # PID
+ assert source_path in args[3]
+ assert "C:\\App" in args[3] # app_path
+ assert "C:\\App\\app.exe" in args[3] # executable
+
+ @pytest.mark.linux
+ @patch("platform.system", return_value="Linux")
+ @patch("subprocess.Popen")
+ @patch("os.getpid", return_value=12345)
+ @patch("platform_utils.paths.app_path", return_value="/opt/app")
+ @patch("platform_utils.paths.get_executable", return_value="/opt/app/app")
+ def test_execute_bootstrap_linux(
+ self, mock_get_exe, mock_app_path, mock_getpid, mock_popen, mock_system, temp_dir
+ ):
+ """Test executing bootstrap on Linux."""
+ bootstrap_path = os.path.join(temp_dir, "bootstrap-lin.sh")
+ source_path = os.path.join(temp_dir, "update")
+
+ # Create a dummy bootstrap file
+ with open(bootstrap_path, "w") as f:
+ f.write("#!/bin/bash\necho test")
+
+ # Mock make_executable (it's called within execute_bootstrap)
+ with patch("autoupdate.autoupdate.make_executable") as mock_make_exec:
+ execute_bootstrap(bootstrap_path, source_path)
+
+ # Verify make_executable was called
+ mock_make_exec.assert_called_once_with(bootstrap_path)
+
+ # Verify subprocess.Popen was called
+ mock_popen.assert_called_once()
+ call_args = mock_popen.call_args
+ assert call_args[1]["shell"] is True
+ # Verify command is passed as list with single string element
+ cmd = call_args[0][0]
+ assert isinstance(cmd, list)
+ assert len(cmd) == 1
+ # The command string should contain all parts
+ cmd_string = cmd[0]
+ assert bootstrap_path in cmd_string
+ assert "12345" in cmd_string # PID
+ assert source_path in cmd_string
+
+ @pytest.mark.darwin
+ @patch("platform.system", return_value="Darwin")
+ @patch("subprocess.Popen")
+ @patch("os.getpid", return_value=12345)
+ @patch("platform_utils.paths.app_path", return_value="/Applications/MyApp.app")
+ @patch("platform_utils.paths.get_executable", return_value="/Applications/MyApp.app/Contents/MacOS/MyApp")
+ def test_execute_bootstrap_macos(
+ self, mock_get_exe, mock_app_path, mock_getpid, mock_popen, mock_system, temp_dir
+ ):
+ """Test executing bootstrap on macOS."""
+ bootstrap_path = os.path.join(temp_dir, "bootstrap-mac.sh")
+ source_path = os.path.join(temp_dir, "update")
+
+ # Create a dummy bootstrap file
+ with open(bootstrap_path, "w") as f:
+ f.write("#!/bin/bash\necho test")
+
+ # Mock make_executable
+ with patch("autoupdate.autoupdate.make_executable") as mock_make_exec:
+ execute_bootstrap(bootstrap_path, source_path)
+
+ # Verify make_executable was called
+ mock_make_exec.assert_called_once_with(bootstrap_path)
+
+ # Verify subprocess.Popen was called
+ mock_popen.assert_called_once()
+ call_args = mock_popen.call_args
+ assert call_args[1]["shell"] is True
diff --git a/tests/test_callbacks.py b/tests/test_callbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..512dfb074f564de2c84306095be54e44ba01175d
--- /dev/null
+++ b/tests/test_callbacks.py
@@ -0,0 +1,126 @@
+"""Tests for callback handling functionality."""
+
+from unittest.mock import Mock
+
+import pytest
+
+from autoupdate.autoupdate import call_callback
+
+
+class TestCallCallback:
+ """Tests for call_callback function."""
+
+ def test_calls_callback_with_args(self):
+ """Test that callback is called with provided arguments."""
+ callback = Mock()
+ args = (1, 2, 3)
+
+ call_callback(callback, *args)
+
+ callback.assert_called_once_with(1, 2, 3)
+
+ def test_calls_callback_with_kwargs(self):
+ """Test that callback is called with keyword arguments."""
+ callback = Mock()
+ kwargs = {"key1": "value1", "key2": "value2"}
+
+ call_callback(callback, **kwargs)
+
+ callback.assert_called_once_with(key1="value1", key2="value2")
+
+ def test_calls_callback_with_args_and_kwargs(self):
+ """Test that callback is called with both args and kwargs."""
+ callback = Mock()
+
+ call_callback(callback, 1, 2, key="value")
+
+ callback.assert_called_once_with(1, 2, key="value")
+
+ def test_callback_exception_is_caught(self):
+ """Test that exceptions from callback are caught and logged."""
+ callback = Mock(side_effect=ValueError("Test error"))
+
+ # Should not raise exception
+ call_callback(callback, "arg1")
+
+ # Callback should have been called
+ callback.assert_called_once_with("arg1")
+
+ def test_callback_with_no_args(self):
+ """Test calling callback with no arguments."""
+ callback = Mock()
+
+ call_callback(callback)
+
+ callback.assert_called_once_with()
+
+ def test_multiple_exceptions_are_handled(self):
+ """Test that different exception types are handled."""
+ # Test with various exception types
+ exceptions = [
+ ValueError("value error"),
+ TypeError("type error"),
+ KeyError("key error"),
+ RuntimeError("runtime error"),
+ ]
+
+ for exc in exceptions:
+ callback = Mock(side_effect=exc)
+ # Should not raise
+ call_callback(callback, "test")
+ callback.assert_called_once()
+
+ def test_callback_return_value_when_successful(self):
+ """Test that callback return value is not used (void function)."""
+ callback = Mock(return_value="some_value")
+
+ # call_callback doesn't return anything
+ result = call_callback(callback, "arg")
+
+ assert result is None
+ callback.assert_called_once_with("arg")
+
+ def test_callback_with_complex_args(self):
+ """Test callback with complex argument types."""
+ callback = Mock()
+ args = ([1, 2, 3], {"key": "value"}, None, 42)
+
+ call_callback(callback, *args)
+
+ callback.assert_called_once_with([1, 2, 3], {"key": "value"}, None, 42)
+
+ def test_callback_exception_logged(self, caplog):
+ """Test that callback exceptions are logged."""
+ import logging
+
+ callback = Mock(side_effect=ValueError("Test exception"))
+
+ with caplog.at_level(logging.ERROR):
+ call_callback(callback, "arg1", "arg2")
+
+ # Should have logged the exception
+ assert len(caplog.records) == 1
+ assert "Failed calling callback" in caplog.text
+ assert "Test exception" in caplog.text
+
+ def test_preserves_callback_side_effects(self):
+ """Test that callback side effects are executed before exception."""
+ side_effect_list = []
+
+ def callback_with_side_effect(value):
+ side_effect_list.append(value)
+ raise ValueError("Error after side effect")
+
+ call_callback(callback_with_side_effect, "test_value")
+
+ # Side effect should have occurred
+ assert side_effect_list == ["test_value"]
+
+ def test_callback_with_nested_structures(self):
+ """Test callback with deeply nested data structures."""
+ callback = Mock()
+ nested_data = {"outer": {"inner": {"deep": [1, 2, {"nested": "value"}]}}}
+
+ call_callback(callback, nested_data)
+
+ callback.assert_called_once_with(nested_data)
diff --git a/tests/test_download.py b/tests/test_download.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a12d3f16a55bd53acc6ce8ff8f57904645a5bd2
--- /dev/null
+++ b/tests/test_download.py
@@ -0,0 +1,224 @@
+"""Tests for download functionality."""
+
+import io
+import os
+from unittest.mock import Mock
+
+import pytest
+import responses
+from requests import HTTPError
+
+from autoupdate.autoupdate import create_requests_session, download_update
+
+
+class TestDownloadUpdate:
+ """Tests for download_update function."""
+
+ @responses.activate
+ def test_successful_download(self, temp_dir, mock_file_content):
+ """Test successful file download."""
+ url = "https://example.com/update.zip"
+ destination = os.path.join(temp_dir, "update.zip")
+
+ responses.add(
+ responses.GET,
+ url,
+ body=mock_file_content,
+ status=200,
+ headers={"content-length": str(len(mock_file_content))},
+ stream=True,
+ )
+
+ session = create_requests_session()
+ result = download_update(url, destination, session)
+
+ assert result == destination
+ assert os.path.exists(destination)
+
+ # Verify downloaded content
+ with open(destination, "rb") as f:
+ assert f.read() == mock_file_content
+
+ @responses.activate
+ def test_download_with_progress_callback(self, temp_dir, mock_file_content):
+ """Test download with progress callback."""
+ url = "https://example.com/update.zip"
+ destination = os.path.join(temp_dir, "update.zip")
+ progress_callback = Mock()
+
+ responses.add(
+ responses.GET,
+ url,
+ body=mock_file_content,
+ status=200,
+ headers={"content-length": str(len(mock_file_content))},
+ stream=True,
+ )
+
+ session = create_requests_session()
+ download_update(url, destination, session, progress_callback=progress_callback)
+
+ # Progress callback should have been called
+ assert progress_callback.called
+ # Should be called at least once (exact count depends on chunk size)
+ assert progress_callback.call_count >= 1
+
+ # Last call should have total downloaded and total size
+ last_call_args = progress_callback.call_args[0]
+ assert len(last_call_args) == 2
+ total_downloaded, total_size = last_call_args
+ assert total_downloaded == len(mock_file_content)
+ assert total_size == len(mock_file_content)
+
+ @responses.activate
+ def test_download_with_custom_chunk_size(self, temp_dir, mock_file_content):
+ """Test download with custom chunk size."""
+ url = "https://example.com/update.zip"
+ destination = os.path.join(temp_dir, "update.zip")
+ progress_callback = Mock()
+ chunk_size = 100 # Small chunk size
+
+ responses.add(
+ responses.GET,
+ url,
+ body=mock_file_content,
+ status=200,
+ headers={"content-length": str(len(mock_file_content))},
+ stream=True,
+ )
+
+ session = create_requests_session()
+ download_update(
+ url, destination, session, progress_callback=progress_callback, chunk_size=chunk_size
+ )
+
+ # With smaller chunks, callback should be called more times
+ assert progress_callback.call_count > 1
+
+ # File should still be correct
+ with open(destination, "rb") as f:
+ assert f.read() == mock_file_content
+
+ @responses.activate
+ def test_download_without_content_length(self, temp_dir, mock_file_content):
+ """Test download when server doesn't provide content-length."""
+ url = "https://example.com/update.zip"
+ destination = os.path.join(temp_dir, "update.zip")
+ progress_callback = Mock()
+
+ # No content-length header
+ responses.add(
+ responses.GET,
+ url,
+ body=mock_file_content,
+ status=200,
+ stream=True,
+ )
+
+ session = create_requests_session()
+ download_update(url, destination, session, progress_callback=progress_callback)
+
+ # Download should still work
+ assert os.path.exists(destination)
+ with open(destination, "rb") as f:
+ assert f.read() == mock_file_content
+
+ # Callback should be called with total_size=0 (from missing header)
+ assert progress_callback.called
+ last_call_args = progress_callback.call_args[0]
+ total_downloaded, total_size = last_call_args
+ assert total_size == 0 # Missing content-length defaults to 0
+
+ @responses.activate
+ def test_download_http_error(self, temp_dir):
+ """Test download with HTTP error.
+
+ Note: File IS created (possibly empty with streaming), but error is raised.
+ """
+ url = "https://example.com/update.zip"
+ destination = os.path.join(temp_dir, "update.zip")
+
+ responses.add(
+ responses.GET,
+ url,
+ json={"error": "Not found"},
+ status=404,
+ )
+
+ session = create_requests_session()
+
+ with pytest.raises(HTTPError):
+ download_update(url, destination, session)
+
+ # File IS created when opened, even though download fails
+ # (Opened with 'w+b' before raise_for_status is called)
+ assert os.path.exists(destination)
+
+ @responses.activate
+ def test_download_without_progress_callback(self, temp_dir, mock_file_content):
+ """Test download works without progress callback."""
+ url = "https://example.com/update.zip"
+ destination = os.path.join(temp_dir, "update.zip")
+
+ responses.add(
+ responses.GET,
+ url,
+ body=mock_file_content,
+ status=200,
+ headers={"content-length": str(len(mock_file_content))},
+ stream=True,
+ )
+
+ session = create_requests_session()
+ result = download_update(url, destination, session, progress_callback=None)
+
+ assert result == destination
+ assert os.path.exists(destination)
+ with open(destination, "rb") as f:
+ assert f.read() == mock_file_content
+
+ @responses.activate
+ def test_download_empty_file(self, temp_dir):
+ """Test downloading an empty file."""
+ url = "https://example.com/empty.zip"
+ destination = os.path.join(temp_dir, "empty.zip")
+
+ responses.add(
+ responses.GET,
+ url,
+ body=b"",
+ status=200,
+ headers={"content-length": "0"},
+ stream=True,
+ )
+
+ session = create_requests_session()
+ result = download_update(url, destination, session)
+
+ assert result == destination
+ assert os.path.exists(destination)
+ assert os.path.getsize(destination) == 0
+
+ @responses.activate
+ def test_download_creates_file_in_binary_mode(self, temp_dir):
+ """Test that download creates file in binary write mode."""
+ url = "https://example.com/update.zip"
+ destination = os.path.join(temp_dir, "update.zip")
+ # Binary content with null bytes
+ binary_content = b"\x00\x01\x02\xff\xfe\xfd"
+
+ responses.add(
+ responses.GET,
+ url,
+ body=binary_content,
+ status=200,
+ headers={"content-length": str(len(binary_content))},
+ stream=True,
+ )
+
+ session = create_requests_session()
+ download_update(url, destination, session)
+
+ # Verify binary content is preserved
+ with open(destination, "rb") as f:
+ assert f.read() == binary_content
diff --git a/tests/test_extract.py b/tests/test_extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbff557faeb5ac64d5bbe007b0e0850b7a5219e0
--- /dev/null
+++ b/tests/test_extract.py
@@ -0,0 +1,139 @@
+"""Tests for archive extraction functionality."""
+
+import os
+import zipfile
+
+import pytest
+
+from autoupdate.autoupdate import extract_update
+
+
+class TestExtractUpdate:
+ """Tests for extract_update function."""
+
+ def test_extract_simple_zip(self, zip_file_path, temp_dir):
+ """Test extracting a simple zip file."""
+ extract_dir = os.path.join(temp_dir, "extracted")
+
+ result = extract_update(zip_file_path, extract_dir)
+
+ assert result == extract_dir
+ assert os.path.exists(extract_dir)
+ assert os.path.exists(os.path.join(extract_dir, "bootstrap.exe"))
+ assert os.path.exists(os.path.join(extract_dir, "app_file.txt"))
+
+ # Verify content
+ with open(os.path.join(extract_dir, "bootstrap.exe"), "rb") as f:
+ assert f.read() == b"fake bootstrap content"
+
+ def test_extract_preserves_content(self, zip_file_path, temp_dir):
+ """Test that extraction preserves file content correctly."""
+ extract_dir = os.path.join(temp_dir, "extracted")
+
+ extract_update(zip_file_path, extract_dir)
+
+ with open(os.path.join(extract_dir, "app_file.txt"), "rb") as f:
+ content = f.read()
+ assert content == b"application content"
+
+ def test_extract_password_protected_zip(self, password_protected_zip, temp_dir):
+ """Test extracting password-protected zip."""
+ zip_path, password = password_protected_zip
+ extract_dir = os.path.join(temp_dir, "extracted_protected")
+
+ result = extract_update(zip_path, extract_dir, password=password)
+
+ assert result == extract_dir
+ assert os.path.exists(extract_dir)
+ assert os.path.exists(os.path.join(extract_dir, "bootstrap.exe"))
+
+ # Verify content was extracted correctly
+ with open(os.path.join(extract_dir, "bootstrap.exe"), "rb") as f:
+ assert f.read() == b"protected bootstrap"
+
+
+ def test_extract_to_nonexistent_directory(self, zip_file_path, temp_dir):
+ """Test extracting to a directory that doesn't exist yet."""
+ extract_dir = os.path.join(temp_dir, "new", "nested", "directory")
+
+ # Should create the directory if it doesn't exist
+ result = extract_update(zip_file_path, extract_dir)
+
+ assert result == extract_dir
+ assert os.path.exists(extract_dir)
+ assert os.path.exists(os.path.join(extract_dir, "bootstrap.exe"))
+
+ def test_extract_returns_destination_path(self, zip_file_path, temp_dir):
+ """Test that extract_update returns the destination path."""
+ extract_dir = os.path.join(temp_dir, "extracted")
+
+ result = extract_update(zip_file_path, extract_dir)
+
+ assert result == extract_dir
+
+ def test_extract_multiple_files(self, temp_dir):
+ """Test extracting zip with multiple files and directories."""
+ # Create a more complex zip
+ zip_path = os.path.join(temp_dir, "complex.zip")
+ with zipfile.ZipFile(zip_path, "w") as zf:
+ zf.writestr("bootstrap.exe", b"bootstrap")
+ zf.writestr("file1.txt", b"content1")
+ zf.writestr("file2.txt", b"content2")
+ zf.writestr("subdir/file3.txt", b"content3")
+
+ extract_dir = os.path.join(temp_dir, "extracted")
+ extract_update(zip_path, extract_dir)
+
+ # Verify all files extracted
+ assert os.path.exists(os.path.join(extract_dir, "bootstrap.exe"))
+ assert os.path.exists(os.path.join(extract_dir, "file1.txt"))
+ assert os.path.exists(os.path.join(extract_dir, "file2.txt"))
+ assert os.path.exists(os.path.join(extract_dir, "subdir", "file3.txt"))
+
+ def test_extract_binary_files(self, temp_dir):
+ """Test extracting binary files maintains integrity."""
+ # Create zip with binary content
+ binary_content = bytes(range(256)) # All byte values
+ zip_path = os.path.join(temp_dir, "binary.zip")
+
+ with zipfile.ZipFile(zip_path, "w") as zf:
+ zf.writestr("bootstrap.exe", b"bootstrap")
+ zf.writestr("binary_file.bin", binary_content)
+
+ extract_dir = os.path.join(temp_dir, "extracted")
+ extract_update(zip_path, extract_dir)
+
+ # Verify binary content preserved
+ with open(os.path.join(extract_dir, "binary_file.bin"), "rb") as f:
+ assert f.read() == binary_content
+
+ def test_extract_empty_zip(self, temp_dir):
+ """Test extracting an empty zip file.
+
+ Note: Python's zipfile.extractall() doesn't create the destination
+ directory if the zip is empty. This is standard Python behavior.
+ """
+ zip_path = os.path.join(temp_dir, "empty.zip")
+
+ # Create empty zip
+ with zipfile.ZipFile(zip_path, "w") as zf:
+ pass # Empty zip
+
+ extract_dir = os.path.join(temp_dir, "extracted")
+ result = extract_update(zip_path, extract_dir)
+
+ assert result == extract_dir
+ # Python's extractall() doesn't create directory for empty zips
+ # This is expected behavior - nothing to extract, no directory needed
+
+ def test_extract_invalid_zip_raises_error(self, temp_dir):
+ """Test that extracting invalid zip file raises error."""
+ # Create a file that's not a valid zip
+ invalid_zip = os.path.join(temp_dir, "invalid.zip")
+ with open(invalid_zip, "wb") as f:
+ f.write(b"This is not a zip file")
+
+ extract_dir = os.path.join(temp_dir, "extracted")
+
+ with pytest.raises(zipfile.BadZipFile):
+ extract_update(invalid_zip, extract_dir)
diff --git a/tests/test_perform_update.py b/tests/test_perform_update.py
new file mode 100644
index 0000000000000000000000000000000000000000..41bcf12934b0a4cc104ecb3cfb2be431f53b37f7
--- /dev/null
+++ b/tests/test_perform_update.py
@@ -0,0 +1,315 @@
+"""Integration tests for the complete update flow."""
+
+import os
+import platform
+import zipfile
+from unittest.mock import Mock, patch
+
+import pytest
+import responses
+
+from autoupdate.autoupdate import perform_update
+
+
+class TestPerformUpdate:
+ """Integration tests for perform_update function."""
+
+ @responses.activate
+ @patch("platform.system", return_value="Windows")
+ @patch("win32api.ShellExecute")
+ @patch("os.getpid", return_value=12345)
+ @patch("platform_utils.paths.app_path", return_value="C:\\App")
+ @patch("platform_utils.paths.get_executable", return_value="C:\\App\\app.exe")
+ def test_successful_update_flow_windows(
+ self, mock_get_exe, mock_app_path, mock_getpid, mock_shell_exec, mock_system
+ ):
+ """Test complete successful update flow on Windows."""
+ endpoint = "https://api.example.com/check-update"
+ update_url = "https://example.com/update.zip"
+ current_version = "1.0.0"
+
+ # Mock update check response
+ update_response = {
+ "current_version": "2.0.0",
+ "description": "New version available",
+ "downloads": {
+ "Windows": update_url,
+ "Darwin": "https://example.com/update-mac.zip",
+ "Linux": "https://example.com/update-linux.zip",
+ },
+ }
+
+ # Create fake zip content with bootstrap
+ zip_content = self._create_zip_with_bootstrap("bootstrap.exe")
+
+ # Mock HTTP responses
+ responses.add(responses.GET, endpoint, json=update_response, status=200)
+ responses.add(
+ responses.GET,
+ update_url,
+ body=zip_content,
+ status=200,
+ headers={"content-length": str(len(zip_content))},
+ stream=True,
+ )
+
+ # Callbacks
+ update_available_callback = Mock(return_value=True)
+ progress_callback = Mock()
+ update_complete_callback = Mock()
+
+ # Execute
+ perform_update(
+ endpoint,
+ current_version,
+ app_name="TestApp",
+ update_available_callback=update_available_callback,
+ progress_callback=progress_callback,
+ update_complete_callback=update_complete_callback,
+ )
+
+ # Verify callbacks were called
+ update_available_callback.assert_called_once()
+ assert update_available_callback.call_args[1]["version"] == "2.0.0"
+ assert update_available_callback.call_args[1]["description"] == "New version available"
+
+ assert progress_callback.called
+ update_complete_callback.assert_called_once()
+
+ # Verify bootstrap execution
+ mock_shell_exec.assert_called_once()
+
+ @responses.activate
+ def test_no_update_available_same_version(self):
+ """Test when current version equals available version."""
+ endpoint = "https://api.example.com/check-update"
+ current_version = "1.0.0"
+
+ update_response = {
+ "current_version": "1.0.0", # Same version
+ "downloads": {"Windows": "https://example.com/update.zip"},
+ }
+
+ responses.add(responses.GET, endpoint, json=update_response, status=200)
+
+ update_available_callback = Mock()
+ update_complete_callback = Mock()
+
+ perform_update(
+ endpoint,
+ current_version,
+ update_available_callback=update_available_callback,
+ update_complete_callback=update_complete_callback,
+ )
+
+ # Callbacks should NOT be called
+ update_available_callback.assert_not_called()
+ update_complete_callback.assert_not_called()
+
+ @responses.activate
+ @patch("platform.system", return_value="Windows")
+ def test_no_update_for_current_platform(self, mock_system):
+ """Test when no update available for current platform."""
+ endpoint = "https://api.example.com/check-update"
+ current_version = "1.0.0"
+
+ update_response = {
+ "current_version": "2.0.0",
+ "downloads": {
+ "Darwin": "https://example.com/update-mac.zip",
+ "Linux": "https://example.com/update-linux.zip",
+ # No Windows download
+ },
+ }
+
+ responses.add(responses.GET, endpoint, json=update_response, status=200)
+
+ update_available_callback = Mock()
+
+ perform_update(endpoint, current_version, update_available_callback=update_available_callback)
+
+ # Should not call update_available_callback
+ update_available_callback.assert_not_called()
+
+ @responses.activate
+ def test_user_cancels_update(self):
+ """Test when user cancels update via callback."""
+ endpoint = "https://api.example.com/check-update"
+ current_version = "1.0.0"
+
+ update_response = {
+ "current_version": "2.0.0",
+ "downloads": {"Windows": "https://example.com/update.zip"},
+ }
+
+ responses.add(responses.GET, endpoint, json=update_response, status=200)
+
+ # User cancels update
+ update_available_callback = Mock(return_value=False)
+ update_complete_callback = Mock()
+
+ with patch("platform.system", return_value="Windows"):
+ perform_update(
+ endpoint,
+ current_version,
+ update_available_callback=update_available_callback,
+ update_complete_callback=update_complete_callback,
+ )
+
+ # Available callback should be called
+ update_available_callback.assert_called_once()
+ # But complete callback should NOT be called (user cancelled)
+ update_complete_callback.assert_not_called()
+
+ @responses.activate
+ def test_no_update_check_response(self):
+ """Test when update check returns empty dict."""
+ endpoint = "https://api.example.com/check-update"
+ current_version = "1.0.0"
+
+ # Empty response - no current_version or downloads
+ responses.add(responses.GET, endpoint, json={}, status=200)
+
+ update_available_callback = Mock()
+
+ # Should not crash - find_update returns {} which is falsy
+ perform_update(endpoint, current_version, update_available_callback=update_available_callback)
+
+ update_available_callback.assert_not_called()
+
+ @responses.activate
+ @patch("platform.system", return_value="Linux")
+ @patch("subprocess.Popen")
+ @patch("os.getpid", return_value=99999)
+ @patch("platform_utils.paths.app_path", return_value="/opt/app")
+ @patch("platform_utils.paths.get_executable", return_value="/opt/app/bin/app")
+ def test_successful_update_flow_linux(
+ self, mock_get_exe, mock_app_path, mock_getpid, mock_popen, mock_system
+ ):
+ """Test complete successful update flow on Linux."""
+ endpoint = "https://api.example.com/check-update"
+ update_url = "https://example.com/update-linux.zip"
+ current_version = "1.0.0"
+
+ update_response = {
+ "current_version": "2.0.0",
+ "downloads": {"Linux": update_url},
+ }
+
+ # Create zip with Linux bootstrap
+ zip_content = self._create_zip_with_bootstrap("bootstrap-lin.sh")
+
+ responses.add(responses.GET, endpoint, json=update_response, status=200)
+ responses.add(
+ responses.GET,
+ update_url,
+ body=zip_content,
+ status=200,
+ headers={"content-length": str(len(zip_content))},
+ stream=True,
+ )
+
+ update_available_callback = Mock(return_value=True)
+ update_complete_callback = Mock()
+
+ with patch("autoupdate.autoupdate.make_executable"):
+ perform_update(
+ endpoint,
+ current_version,
+ update_available_callback=update_available_callback,
+ update_complete_callback=update_complete_callback,
+ )
+
+ update_available_callback.assert_called_once()
+ update_complete_callback.assert_called_once()
+ mock_popen.assert_called_once()
+
+ @responses.activate
+ @patch("platform.system", return_value="Windows")
+ def test_update_with_password_protected_zip(self, mock_system):
+ """Test update with password-protected archive."""
+ endpoint = "https://api.example.com/check-update"
+ update_url = "https://example.com/update.zip"
+ current_version = "1.0.0"
+ password = b"secret123"
+
+ update_response = {
+ "current_version": "2.0.0",
+ "downloads": {"Windows": update_url},
+ }
+
+ # Create password-protected zip
+ zip_content = self._create_password_protected_zip("bootstrap.exe", password)
+
+ responses.add(responses.GET, endpoint, json=update_response, status=200)
+ responses.add(
+ responses.GET,
+ update_url,
+ body=zip_content,
+ status=200,
+ headers={"content-length": str(len(zip_content))},
+ stream=True,
+ )
+
+ update_available_callback = Mock(return_value=True)
+
+ with patch("win32api.ShellExecute"), patch("os.getpid", return_value=1), patch(
+ "platform_utils.paths.app_path", return_value="C:\\App"
+ ), patch("platform_utils.paths.get_executable", return_value="C:\\App\\app.exe"):
+ perform_update(
+ endpoint,
+ current_version,
+ password=password,
+ update_available_callback=update_available_callback,
+ )
+
+ update_available_callback.assert_called_once()
+
+ @responses.activate
+ @pytest.mark.parametrize(
+ "current_version,available_version,expected_callback_count",
+ [
+ ("9.10", "10.0", 1),
+ ("10.0", "9.10", 0),
+ ],
+ )
+ def test_version_comparison_uses_release_order(self, current_version, available_version, expected_callback_count):
+ """Compare release versions by their components rather than lexically."""
+ endpoint = "https://api.example.com/check-update"
+ update_response = {
+ "current_version": available_version,
+ "downloads": {"Windows": "https://example.com/update.zip"},
+ }
+
+ responses.add(responses.GET, endpoint, json=update_response, status=200)
+
+ update_available_callback = Mock(return_value=False) # Cancel to stop early
+
+ with patch("platform.system", return_value="Windows"):
+ perform_update(endpoint, current_version, update_available_callback=update_available_callback)
+
+ assert update_available_callback.call_count == expected_callback_count
+
+ # Helper methods
+ def _create_zip_with_bootstrap(self, bootstrap_name):
+ """Create a zip file with a bootstrap script."""
+ import io
+
+ zip_buffer = io.BytesIO()
+ with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
+ zf.writestr(bootstrap_name, b"fake bootstrap script")
+ zf.writestr("app.exe", b"fake app")
+
+ return zip_buffer.getvalue()
+
+ def _create_password_protected_zip(self, bootstrap_name, password):
+ """Create a password-protected zip file."""
+ import io
+
+ zip_buffer = io.BytesIO()
+ with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
+ zf.setpassword(password)
+ zf.writestr(bootstrap_name, b"protected bootstrap", compress_type=zipfile.ZIP_DEFLATED)
+ zf.writestr("app.exe", b"protected app", compress_type=zipfile.ZIP_DEFLATED)
+
+ return zip_buffer.getvalue()
diff --git a/tests/test_platform.py b/tests/test_platform.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e0bd897f2fbfb8c839df4634675d27b42c67e8f
--- /dev/null
+++ b/tests/test_platform.py
@@ -0,0 +1,126 @@
+"""Tests for platform-specific logic across Windows, macOS, and Linux."""
+
+import os
+from unittest.mock import patch
+
+import pytest
+
+from autoupdate.autoupdate import bootstrap_name, move_bootstrap
+
+
+class TestPlatformSpecificBootstrapSelection:
+ """Test that correct bootstrap is selected for each platform."""
+
+ @pytest.mark.parametrize(
+ "platform_name,expected_bootstrap",
+ [
+ ("Windows", "bootstrap.exe"),
+ ("Darwin", "bootstrap-mac.sh"),
+ ("Linux", "bootstrap-lin.sh"),
+ ],
+ )
+ def test_bootstrap_selection_by_platform(self, platform_name, expected_bootstrap):
+ """Test bootstrap name selection for each platform."""
+ with patch("platform.system", return_value=platform_name):
+ assert bootstrap_name() == expected_bootstrap
+
+
+class TestPlatformSpecificPathHandling:
+ """Test platform-specific path handling."""
+
+ @patch("platform.system", return_value="Darwin")
+ def test_macos_uses_resources_directory(self, mock_system, temp_dir):
+ """Test that macOS looks for bootstrap in Contents/Resources."""
+ # Create macOS bundle structure
+ extracted_dir = os.path.join(temp_dir, "MyApp.app")
+ resources_dir = os.path.join(extracted_dir, "Contents", "Resources")
+ os.makedirs(resources_dir)
+
+ # Create bootstrap in Resources
+ bootstrap_src = os.path.join(resources_dir, "bootstrap-mac.sh")
+ with open(bootstrap_src, "w") as f:
+ f.write("#!/bin/bash")
+
+ # Move bootstrap
+ result = move_bootstrap(extracted_dir)
+
+ # Should move to parent of extracted_dir
+ expected_dest = os.path.join(temp_dir, "bootstrap-mac.sh")
+ assert result == expected_dest
+ assert os.path.exists(expected_dest)
+
+ @patch("platform.system", return_value="Windows")
+ def test_windows_uses_flat_structure(self, mock_system, temp_dir):
+ """Test that Windows looks for bootstrap in root directory."""
+ extracted_dir = os.path.join(temp_dir, "extracted")
+ os.makedirs(extracted_dir)
+
+ # Create bootstrap in root
+ bootstrap_src = os.path.join(extracted_dir, "bootstrap.exe")
+ with open(bootstrap_src, "wb") as f:
+ f.write(b"MZ") # Fake PE header
+
+ # Move bootstrap
+ result = move_bootstrap(extracted_dir)
+
+ # Should move to parent
+ expected_dest = os.path.join(temp_dir, "bootstrap.exe")
+ assert result == expected_dest
+ assert os.path.exists(expected_dest)
+
+ @patch("platform.system", return_value="Linux")
+ def test_linux_uses_flat_structure(self, mock_system, temp_dir):
+ """Test that Linux looks for bootstrap in root directory."""
+ extracted_dir = os.path.join(temp_dir, "extracted")
+ os.makedirs(extracted_dir)
+
+ # Create bootstrap in root
+ bootstrap_src = os.path.join(extracted_dir, "bootstrap-lin.sh")
+ with open(bootstrap_src, "w") as f:
+ f.write("#!/bin/bash")
+
+ # Move bootstrap
+ result = move_bootstrap(extracted_dir)
+
+ # Should move to parent
+ expected_dest = os.path.join(temp_dir, "bootstrap-lin.sh")
+ assert result == expected_dest
+ assert os.path.exists(expected_dest)
+
+
+class TestCrossPlatformUpdateFlow:
+ """Test that update flow logic handles all platforms correctly."""
+
+ @pytest.mark.parametrize(
+ "platform_name,bootstrap_file",
+ [
+ ("Windows", "bootstrap.exe"),
+ ("Darwin", "bootstrap-mac.sh"),
+ ("Linux", "bootstrap-lin.sh"),
+ ],
+ )
+ def test_bootstrap_file_exists_for_platform(self, platform_name, bootstrap_file, temp_dir):
+ """Test that correct bootstrap file is expected for each platform."""
+ with patch("platform.system", return_value=platform_name):
+ # Setup directory
+ extracted_dir = os.path.join(temp_dir, "extracted")
+
+ if platform_name == "Darwin":
+ # macOS structure
+ resources_dir = os.path.join(extracted_dir, "Contents", "Resources")
+ os.makedirs(resources_dir)
+ bootstrap_path = os.path.join(resources_dir, bootstrap_file)
+ else:
+ # Windows/Linux structure
+ os.makedirs(extracted_dir)
+ bootstrap_path = os.path.join(extracted_dir, bootstrap_file)
+
+ # Create bootstrap
+ with open(bootstrap_path, "w") as f:
+ f.write("bootstrap content")
+
+ # Move and verify
+ result = move_bootstrap(extracted_dir)
+ expected = os.path.join(temp_dir, bootstrap_file)
+ assert result == expected
+ assert os.path.exists(expected)
diff --git a/tests/test_session.py b/tests/test_session.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4e316901ce0e6d6bae164488d5215875cf884cb
--- /dev/null
+++ b/tests/test_session.py
@@ -0,0 +1,75 @@
+"""Tests for session creation and user agent handling."""
+
+import pytest
+import requests
+
+from autoupdate.autoupdate import create_requests_session
+
+
+class TestCreateRequestsSession:
+ """Tests for create_requests_session function."""
+
+ def test_creates_session_without_app_info(self):
+ """Test creating session without app name and version."""
+ session = create_requests_session()
+
+ assert isinstance(session, requests.Session)
+ assert "User-Agent" in session.headers
+ # Should have default requests user agent
+ assert session.headers["User-Agent"].startswith("python-requests/")
+
+ def test_creates_session_with_app_name_only(self):
+ """Test creating session with app name but no version."""
+ session = create_requests_session(app_name="TestApp")
+
+ assert isinstance(session, requests.Session)
+ assert "User-Agent" in session.headers
+ # Should append app name with None version (no quotes around None in repr)
+ assert "TestApp/None" in session.headers["User-Agent"]
+
+ def test_creates_session_with_app_name_and_version(self):
+ """Test creating session with both app name and version."""
+ session = create_requests_session(app_name="TestApp", version="1.2.3")
+
+ assert isinstance(session, requests.Session)
+ assert "User-Agent" in session.headers
+ # Should append app name and version
+ assert "TestApp/'1.2.3'" in session.headers["User-Agent"]
+ # Should still have base user agent
+ assert "python-requests/" in session.headers["User-Agent"]
+
+ def test_session_with_version_only(self):
+ """Test creating session with version but no app name."""
+ session = create_requests_session(version="2.0.0")
+
+ assert isinstance(session, requests.Session)
+ assert "User-Agent" in session.headers
+ # Version without app name should not be appended
+ # (because app_name is falsy, the if condition fails)
+ assert "2.0.0" not in session.headers["User-Agent"]
+ # Should only have default user agent
+ assert session.headers["User-Agent"].startswith("python-requests/")
+
+ def test_user_agent_format(self):
+ """Test the exact format of the custom user agent string."""
+ session = create_requests_session(app_name="MyApp", version="3.4.5")
+
+ user_agent = session.headers["User-Agent"]
+
+ # Should contain both parts
+ assert "python-requests/" in user_agent
+ assert "MyApp/'3.4.5'" in user_agent
+
+ # Custom part should be appended with a space
+ assert user_agent.endswith(" MyApp/'3.4.5'")
+
+ def test_session_is_independent(self):
+ """Test that each session is independent."""
+ session1 = create_requests_session(app_name="App1", version="1.0")
+ session2 = create_requests_session(app_name="App2", version="2.0")
+
+ assert session1 is not session2
+ assert "App1/'1.0'" in session1.headers["User-Agent"]
+ assert "App2/'2.0'" in session2.headers["User-Agent"]
+ assert "App2" not in session1.headers["User-Agent"]
+ assert "App1" not in session2.headers["User-Agent"]
diff --git a/tests/test_update_check.py b/tests/test_update_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0abe655b30b5134d3d1c3ac3e92afb55b69560c
--- /dev/null
+++ b/tests/test_update_check.py
@@ -0,0 +1,156 @@
+"""Tests for update checking functionality."""
+
+import pytest
+import responses
+from requests import HTTPError
+
+from autoupdate.autoupdate import create_requests_session, find_update
+
+
+class TestFindUpdate:
+ """Tests for find_update function."""
+
+ @responses.activate
+ def test_successful_update_check(self, sample_update_response):
+ """Test successful update check returns correct data."""
+ endpoint = "https://api.example.com/check-update"
+ responses.add(
+ responses.GET,
+ endpoint,
+ json=sample_update_response,
+ status=200,
+ )
+
+ session = create_requests_session()
+ result = find_update(endpoint, session)
+
+ assert result == sample_update_response
+ assert result["current_version"] == "2.0.0"
+ assert "downloads" in result
+ assert len(responses.calls) == 1
+
+ @responses.activate
+ def test_update_check_with_custom_user_agent(self, sample_update_response):
+ """Test that custom user agent is sent in request."""
+ endpoint = "https://api.example.com/check-update"
+ responses.add(
+ responses.GET,
+ endpoint,
+ json=sample_update_response,
+ status=200,
+ )
+
+ session = create_requests_session(app_name="TestApp", version="1.0.0")
+ result = find_update(endpoint, session)
+
+ assert result == sample_update_response
+ # Verify user agent was sent
+ assert len(responses.calls) == 1
+ assert "TestApp/'1.0.0'" in responses.calls[0].request.headers["User-Agent"]
+
+ @responses.activate
+ def test_update_check_http_error(self):
+ """Test that HTTP errors are raised properly."""
+ endpoint = "https://api.example.com/check-update"
+ responses.add(
+ responses.GET,
+ endpoint,
+ json={"error": "Not found"},
+ status=404,
+ )
+
+ session = create_requests_session()
+
+ with pytest.raises(HTTPError) as exc_info:
+ find_update(endpoint, session)
+
+ assert "404" in str(exc_info.value)
+
+ @responses.activate
+ def test_update_check_server_error(self):
+ """Test that server errors are raised."""
+ endpoint = "https://api.example.com/check-update"
+ responses.add(
+ responses.GET,
+ endpoint,
+ json={"error": "Internal server error"},
+ status=500,
+ )
+
+ session = create_requests_session()
+
+ with pytest.raises(HTTPError):
+ find_update(endpoint, session)
+
+ @responses.activate
+ def test_update_check_returns_empty_response(self):
+ """Test handling of empty JSON response."""
+ endpoint = "https://api.example.com/check-update"
+ responses.add(
+ responses.GET,
+ endpoint,
+ json={},
+ status=200,
+ )
+
+ session = create_requests_session()
+ result = find_update(endpoint, session)
+
+ assert result == {}
+
+ @responses.activate
+ def test_update_check_minimal_response(self):
+ """Test handling of minimal valid response."""
+ endpoint = "https://api.example.com/check-update"
+ minimal_response = {
+ "current_version": "1.5.0",
+ "downloads": {},
+ }
+ responses.add(
+ responses.GET,
+ endpoint,
+ json=minimal_response,
+ status=200,
+ )
+
+ session = create_requests_session()
+ result = find_update(endpoint, session)
+
+ assert result == minimal_response
+ assert result["current_version"] == "1.5.0"
+ assert result["downloads"] == {}
+
+ @responses.activate
+ def test_update_check_with_description(self, sample_update_response):
+ """Test that description field is properly returned."""
+ endpoint = "https://api.example.com/check-update"
+ responses.add(
+ responses.GET,
+ endpoint,
+ json=sample_update_response,
+ status=200,
+ )
+
+ session = create_requests_session()
+ result = find_update(endpoint, session)
+
+ assert "description" in result
+ assert result["description"] == "New update available with bug fixes"
+
+ @responses.activate
+ def test_multiple_update_checks(self, sample_update_response, no_update_response):
+ """Test multiple update checks with same session."""
+ endpoint1 = "https://api.example.com/check-update"
+ endpoint2 = "https://api.example.com/check-update-v2"
+
+ responses.add(responses.GET, endpoint1, json=sample_update_response, status=200)
+ responses.add(responses.GET, endpoint2, json=no_update_response, status=200)
+
+ session = create_requests_session()
+
+ result1 = find_update(endpoint1, session)
+ result2 = find_update(endpoint2, session)
+
+ assert result1["current_version"] == "2.0.0"
+ assert result2["current_version"] == "1.0.0"
+ assert len(responses.calls) == 2
diff --git a/autoupdate/__init__.py b/autoupdate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d876613a4250bc82cd8a85a8a823535dde6876c7
--- /dev/null
+++ b/autoupdate/__init__.py
+import glob
+import os.path
+import platform
+
+
+def find_datafiles():
+ system = platform.system()
+ if system == "Windows":
+ file_ext = "*.exe"
+ else:
+ file_ext = "*.sh"
+ path = os.path.abspath(os.path.join(__path__[0], "bootstrappers", file_ext))
+ return [("", glob.glob(path))]
diff --git a/autoupdate/autoupdate.py b/autoupdate/autoupdate.py
new file mode 100644
index 0000000000000000000000000000000000000000..b92fdff66ca556783711f75739ff5141c80cf5f1
--- /dev/null
+++ b/autoupdate/autoupdate.py
+import contextlib
+import io
+import os
+import platform
+import tempfile
+import zipfile
+from logging import getLogger
+
+import requests
+from packaging.version import Version
+from platform_utils import paths
+
+logger = getLogger("autoupdate")
+
+
+def perform_update(
+ endpoint,
+ current_version,
+ app_name="",
+ password=None,
+ update_available_callback=None,
+ progress_callback=None,
+ update_complete_callback=None,
+):
+ requests_session = create_requests_session(app_name=app_name, version=current_version)
+ available_update = find_update(endpoint, requests_session=requests_session)
+ if not available_update:
+ return
+ available_version = available_update["current_version"]
+ if (
+ Version(str(available_version)) <= Version(str(current_version))
+ or platform.system() not in available_update["downloads"]
+ ):
+ return
+ available_description = available_update.get("description", None)
+ update_url = available_update["downloads"][platform.system()]
+ logger.info(f"A new update is available. Version {available_version}")
+ if callable(update_available_callback) and not update_available_callback(
+ version=available_version, description=available_description
+ ): # update_available_callback should return a falsy value to stop the process
+ logger.info("User canceled update.")
+ return
+ base_path = tempfile.mkdtemp()
+ download_path = os.path.join(base_path, "update.zip")
+ update_path = os.path.join(base_path, "update")
+ downloaded = download_update(
+ update_url, download_path, requests_session=requests_session, progress_callback=progress_callback
+ )
+ extracted = extract_update(downloaded, update_path, password=password)
+ bootstrap_path = move_bootstrap(extracted)
+ execute_bootstrap(bootstrap_path, extracted)
+ logger.info("Update prepared for installation.")
+ if callable(update_complete_callback):
+ update_complete_callback()
+
+
+def create_requests_session(app_name=None, version=None):
+ user_agent = ""
+ session = requests.session()
+ if app_name:
+ user_agent = f" {app_name}/{version!r}"
+ session.headers["User-Agent"] = str(session.headers["User-Agent"]) + user_agent
+ return session
+
+
+def find_update(endpoint, requests_session):
+ response = requests_session.get(endpoint)
+ response.raise_for_status()
+ content = response.json()
+ return content
+
+
+def download_update(
+ update_url, update_destination, requests_session, progress_callback=None, chunk_size=io.DEFAULT_BUFFER_SIZE
+):