diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b9f36c2 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +# The suite is all mocks: it runs the PTP and CHDK protocol logic without a +# camera, which is the only way this library can be tested between bench +# sessions. `tests/` is named explicitly because `examples/` holds hardware +# scripts that pytest would otherwise collect and fail to import. +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.12"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Install + run: | + python -m pip install --upgrade pip + pip install -e ".[dev]" + - name: Test + run: pytest tests/ -q diff --git a/README.md b/README.md index 4eca8bd..056376e 100644 --- a/README.md +++ b/README.md @@ -87,9 +87,11 @@ pyusb / libusb — raw USB access ## Camera side assignment -For book scanning with two cameras, each camera is identified as "odd" or "even" (left/right pages). This is stored in a file called `OWN.TXT` on the camera's SD card containing either `ODD` or `EVEN`. The Captua workflow reads this via `download_file('OWN.TXT')` to determine page sequencing and EXIF orientation. +For book scanning with two cameras, each body is assigned a page parity — which pages it shoots — stored in a file called `OWN.TXT` on the camera's SD card. A parity line reads `ODD` or `EVEN`; which of the two sits on the left is the operator's reading direction, and the file says nothing about it. An id line, `id=3f9a1c2b7d4e`, gives the body a stable identity, because pyusb cannot always read a serial number from a Canon compact. The Captua workflow reads the file via `download_file('A/OWN.TXT')` to determine page sequencing and EXIF orientation, and to tell one body from the other across replugs. Note the `A/` prefix: `download_file` and `upload_file` both take a card path. -The `tools/flash_chdk.py` script writes this file during SD card preparation. +Either line can stand alone, so a reader must handle four shapes: both lines, a parity alone, an identity alone, and no file at all. `parse_own_txt` and `format_own_txt` in `util.py` read and write all four; treat a missing parity as unassigned rather than as an error. + +Skipping the parity prompt while flashing means "leave the assignment alone", so a card that said `EVEN` still says `EVEN` afterwards. An identity-only file is what skipping produces on a card that had no parity to preserve — the body keeps its identity even though nobody has said yet which pages it shoots — and a card with neither a parity nor an identity gets no file at all. In practice `tools/flash_chdk.py` never writes a parity on its own, because it mints an identity whenever it writes one; a parity-only file comes from an older card or a hand-written one, and is read normally. ## Tools diff --git a/pyproject.toml b/pyproject.toml index e53bfb2..6130ffd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pychdk" -version = "0.1.0" +version = "0.1.1" description = "Pure Python CHDK PTP camera control" requires-python = ">=3.11" dependencies = [ diff --git a/src/pychdk/__init__.py b/src/pychdk/__init__.py index fb483f3..2e758c2 100644 --- a/src/pychdk/__init__.py +++ b/src/pychdk/__init__.py @@ -1,13 +1,58 @@ """Pure Python CHDK PTP camera control.""" -__version__ = "0.1.0" +import importlib -from pychdk.device import ChdkDevice, list_devices, DeviceInfo -from pychdk.ptp import PTPError -from pychdk.chdk import ChdkPTP -from pychdk.multicam import MultiCam -from pychdk import util +__version__ = "0.1.1" __all__ = [ - "ChdkDevice", "list_devices", "DeviceInfo", + "ChdkDevice", "list_devices", "DeviceInfo", "install_signal_handlers", "PTPError", "ChdkPTP", "MultiCam", "util", + "parse_own_txt", "format_own_txt", ] + +# Submodules reachable as attributes of the package. +_SUBMODULES = ("util",) + +# Every other export, mapped to the submodule that owns it. +_EXPORTS = { + "ChdkDevice": "pychdk.device", + "list_devices": "pychdk.device", + "DeviceInfo": "pychdk.device", + "install_signal_handlers": "pychdk.device", + "PTPError": "pychdk.ptp", + "ChdkPTP": "pychdk.chdk", + "MultiCam": "pychdk.multicam", + "parse_own_txt": "pychdk.util", + "format_own_txt": "pychdk.util", +} + + +def __getattr__(name): + """Resolve an export on first access (PEP 562). + + Importing the submodules eagerly meant that reaching pychdk.util — + which needs nothing but math — imported pychdk.device and so pyusb. + Each name now costs only the submodule that owns it, and is cached + in the module globals afterwards. + + Args: + name: Attribute being looked up on the package. + + Returns: + The submodule or the exported object. + + Raises: + AttributeError: If the package exports no such name. + """ + if name in _SUBMODULES: + value = importlib.import_module(f"pychdk.{name}") + elif name in _EXPORTS: + value = getattr(importlib.import_module(_EXPORTS[name]), name) + else: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + globals()[name] = value + return value + + +def __dir__(): + """List the exports alongside whatever has already been resolved.""" + return sorted(set(globals()) | set(__all__)) diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index dfd4377..a6ae810 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -51,6 +51,18 @@ class MessageType(IntEnum): USER = 3 +class ScriptErrorType(IntEnum): + """ptp_chdk_script_error_type, the subtype of an ERR message. + + SCRIPT_RUNNING is an ExecuteScript startup status only, never a + message subtype, per core/ptp.h. + """ + NONE = 0 + COMPILE = 1 + RUN = 2 + SCRIPT_RUNNING = 0x1000 + + class ScriptFlag(IntEnum): NONE = 0 NOKILL = 0x100 @@ -62,8 +74,58 @@ class ScriptFlag(IntEnum): REMOTE_CAP_RAW = 0x02 REMOTE_CAP_DNG_HDR = 0x04 +# Not a data type: the status PTP_CHDK_RemoteCaptureIsReady reports when +# init_usb_capture has not run (PTP_CHDK_CAPTURE_NOTSET in core/ptp.h). +REMOTE_CAP_NOTSET = 0x10000000 + +# A full-resolution still needs a few hundred chunks at most; this only +# exists so a camera that never clears the "more" flag cannot hang us. +MAX_CAPTURE_CHUNKS = 10000 + ScriptMessage = namedtuple("ScriptMessage", ["msg_type", "data_type", "script_id", "value"]) +ScriptMessage.__doc__ = """One message from the camera's script queue. + +The data_type field carries whichever subtype the message type calls +for, as core/ptp.h defines it: a ScriptDataType for RET and USER +messages, and a ScriptErrorType for ERR. The field keeps its name for +the sake of callers that already read it. +""" + + +def _script_error_name(error_type): + """Name a script error type for a message a human has to read. + + Args: + error_type: Value of an ERR message's subtype, or an + ExecuteScript startup status. + + Returns: + Lowercase name, or the raw value in hex if CHDK sends one we + do not know. + """ + try: + return ScriptErrorType(error_type).name.lower() + except ValueError: + return f"unknown 0x{int(error_type):x}" + + +def _as_signed32(value): + """Reinterpret a PTP uint32 parameter as a signed 32-bit integer. + + PTP parameters are unsigned, so CHDK's -1 sentinels arrive as + 0xFFFFFFFF and have to be folded back before they are used. + + Args: + value: Parameter value as received (unsigned). + + Returns: + Integer in the range -2**31 .. 2**31 - 1. + """ + value &= 0xFFFFFFFF + if value >= 0x80000000: + return value - 0x100000000 + return value def _decode_script_value(data_type, data): @@ -117,8 +179,16 @@ def execute_script(self, script, language=ScriptLanguage.LUA, language: ScriptLanguage.LUA or ScriptLanguage.UBASIC. flags: ScriptFlag bitmask (NOKILL, FLUSH). + CHDK returns the script id in param1 and a startup status from + ptp_chdk_script_error_type in param2 (core/ptp.h). A nonzero + status means the script never started, so the id is not one: + waiting on it would only burn the caller's whole timeout. + Returns: Script ID assigned by the camera. + + Raises: + RuntimeError: If the camera refused to start the script. """ script_bytes = script.encode("utf-8") + b"\x00" params, _ = self._session.transaction( @@ -126,6 +196,14 @@ def execute_script(self, script, language=ScriptLanguage.LUA, params=[ChdkCommand.EXECUTE_SCRIPT, language | flags], send_data=script_bytes, ) + status = params[1] if len(params) > 1 else 0 + if status: + if status == ScriptErrorType.SCRIPT_RUNNING: + reason = ("a script is already running and NOKILL was set, " + "so this one was refused") + else: + reason = f"{_script_error_name(status)} error" + raise RuntimeError(f"Script did not start: {reason}") return params[0] if params else 0 def get_script_status(self): @@ -149,8 +227,16 @@ def read_script_message(self): [msg_type, data_type, script_id, data_size] Data phase contains the raw value bytes. + Param2 is the message subtype, and what it means depends on the + message type: for RET and USER it is a ScriptDataType, but for + ERR it is a ScriptErrorType, and the data phase is the error + text rather than an encoded value. Reading an ERR's subtype as + a data type silently threw that text away — the two enums + overlap, so COMPILE decoded as NIL and RUN as BOOLEAN. + Returns: - ScriptMessage namedtuple. + ScriptMessage namedtuple. Its data_type field holds an + error type when msg_type is ERR, a data type otherwise. """ params, data = self._session.transaction( OperationCode.CHDK, @@ -162,7 +248,11 @@ def read_script_message(self): msg_type = params[0] data_type = params[1] if len(params) > 1 else ScriptDataType.NIL script_id = params[2] if len(params) > 2 else 0 - value = _decode_script_value(data_type, data) + if msg_type == MessageType.ERR: + # The header guarantees at least one zero byte, even empty. + value = data.decode("utf-8", errors="replace").rstrip("\x00") + else: + value = _decode_script_value(data_type, data) return ScriptMessage(msg_type, data_type, script_id, value) def write_script_message(self, message, script_id=0): @@ -230,39 +320,144 @@ def get_display_data(self, flags=0): def remote_capture_is_ready(self): """Check if a remote capture is ready for download. + CHDK's PTP_CHDK_RemoteCaptureIsReady (core/ptp.h) returns a + status in param1: 0 is not ready yet, 0x10000000 says remote + capture is not initialized, and any other value is a bitmask of + the PTP_CHDK_CAPTURE_* data types that are ready. + + The uninitialized status is reported rather than raised on, + because on its own it does not mean anything is wrong. CHDK + acknowledges a script as loaded and scheduled, not as run, so a + poll can arrive before init_usb_capture has executed and get + this answer perfectly legitimately. It is a failure only once + the script has had its chance — which the caller knows and this + method does not. A caller seeing it after the script has ended + is looking at an initialization that never happened. + Returns: - Tuple of (is_ready, image_format). + Tuple of (is_ready, status). status is REMOTE_CAP_NOTSET + when the camera reports remote capture uninitialized, 0 + when there is simply nothing ready yet, and otherwise a + bitmask of the data types ready to download. """ params, _ = self._session.transaction( OperationCode.CHDK, params=[ChdkCommand.REMOTE_CAPTURE_IS_READY], receive_data=False, ) - if not params or params[0] == 0: - return False, 0 - return True, params[0] + status = params[0] if params else 0 + if status == 0 or status == REMOTE_CAP_NOTSET: + return False, status + return True, status - def remote_capture_get_data(self, format_flag): - """Download remote capture image data. + def remote_capture_get_chunk(self, format_flag): + """Fetch one chunk of a remote capture. + + CHDK's PTP_CHDK_RemoteCaptureGetData handler (core/ptp.c) + answers one chunk per transaction and describes it in the + response parameters: + + * param1 — the chunk's size in bytes; + * param2 — 1 while further chunks follow, 0 on the last one; + * param3 — "seek required to pos (-1 = no seek)", in the + header's words. No seek means the chunk continues from the + current write position, which is not the same as the end of + the file once a chunk has seeked backwards. Parameters are + unsigned, so -1 arrives as 0xFFFFFFFF and is folded back + here. + + A camera that sends fewer parameters is read as a single + appended chunk the size of the data phase. Args: format_flag: Which format to download (JPEG=1, RAW=2, DNG_HDR=4). Returns: - Image data as bytes. + Tuple of (chunk_bytes, more, position), where more is a bool + and position is a sign-corrected int (-1 means no seek). """ - _, data = self._session.transaction( + params, data = self._session.transaction( OperationCode.CHDK, params=[ChdkCommand.REMOTE_CAPTURE_GET_DATA, format_flag], receive_data=True, ) - return data + params = params or [] + size = params[0] if len(params) > 0 else len(data) + more = bool(params[1]) if len(params) > 1 else False + position = _as_signed32(params[2]) if len(params) > 2 else -1 + # Trust the data phase when the camera claims more than it sent. + if 0 <= size < len(data): + data = data[:size] + return data, more, position + + def remote_capture_get_data(self, format_flag): + """Download remote capture image data. + + Loops over remote_capture_get_chunk until the camera clears its + "more" flag, following the same write cursor a file would. A + chunk that asks for a seek moves the cursor; every chunk is + written at the cursor and advances it by its own length. That + is what "-1 = no seek" means: the chunk continues from wherever + the last one ended, which is only the end of the file while no + chunk has seeked backwards. + + Args: + format_flag: Which format to download (JPEG=1, RAW=2, DNG_HDR=4). - def wait_for_script(self, timeout=30.0): - """Wait until no script is running on the camera.""" + Returns: + Image data as bytes. + + Raises: + RuntimeError: If the camera never clears its "more" flag. + """ + image = bytearray() + cursor = 0 + for _ in range(MAX_CAPTURE_CHUNKS): + chunk, more, position = self.remote_capture_get_chunk(format_flag) + if position >= 0: + cursor = position + end = cursor + len(chunk) + if len(image) < end: + image.extend(bytes(end - len(image))) + image[cursor:end] = chunk + cursor = end + if not more: + return bytes(image) + raise RuntimeError( + f"Remote capture did not end after {MAX_CAPTURE_CHUNKS} chunks" + ) + + def wait_for_script(self, timeout=30.0, script_id=None): + """Wait until no script is running on the camera. + + Reads waiting messages as it goes, rather than watching only + the running flag: a script that starts and then fails clears + that flag like any other, so waiting without reading the queue + reported a failed capture as a clean one and left the error + behind for the next caller to trip over. + + Args: + timeout: Max seconds to wait for the script to finish. + script_id: Only raise on errors from this script. Starting + a script does not flush the queue, so an error left by + a previous one would otherwise fail this one. None + matches any script, which is only right when the caller + has no id to match. + + Raises: + RuntimeError: If the script reported an error. + TimeoutError: If the script is still running at the deadline. + """ deadline = time.monotonic() + timeout while time.monotonic() < deadline: - running, _ = self.get_script_status() + running, has_msgs = self.get_script_status() + if has_msgs: + msg = self.read_script_message() + is_ours = script_id is None or msg.script_id == script_id + if is_ours and msg.msg_type == MessageType.ERR: + kind = _script_error_name(msg.data_type) + raise RuntimeError(f"Script error ({kind}): {msg.value}") + continue if not running: return time.sleep(0.5) @@ -302,7 +497,8 @@ def execute_lua_wait(self, script, timeout=10.0): if msg.msg_type == MessageType.RET: return msg.value if msg.msg_type == MessageType.ERR: - raise RuntimeError(f"Script error: {msg.value}") + kind = _script_error_name(msg.data_type) + raise RuntimeError(f"Script error ({kind}): {msg.value}") if not running and not has_msgs: return None time.sleep(0.05) diff --git a/src/pychdk/device.py b/src/pychdk/device.py index 1858154..314c2da 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -5,6 +5,7 @@ """ import atexit import signal +import threading import time import weakref from collections import namedtuple @@ -14,13 +15,22 @@ from pychdk.chdk import ( ChdkPTP, MessageType, + _script_error_name, REMOTE_CAP_JPEG, + REMOTE_CAP_NOTSET, REMOTE_CAP_RAW, REMOTE_CAP_DNG_HDR, ) from pychdk.util import shutter_to_tv96, iso_to_sv96 +# How long a capture script is allowed to still be starting before an +# "uninitialized" answer counts against it. CHDK acknowledges a script +# as scheduled, not as run, so the first polls can legitimately land +# before init_usb_capture has executed. +CAPTURE_INIT_GRACE = 5.0 + + DeviceInfo = namedtuple("DeviceInfo", [ "vendor_id", "product_id", "bus_num", "device_num", "serial_num", ]) @@ -90,11 +100,44 @@ def _signal_handler(signum, frame): signal.raise_signal(signum) +def install_signal_handlers(): + """Install the SIGINT/SIGTERM handlers that close open cameras. + + Python only allows handlers to be installed from the main thread of + the main interpreter, so this declines anywhere else instead of + raising: a host that first imports pychdk inside a worker thread — + a synchronous FastAPI route, say — would otherwise fail on the + import. Such a host can call this later from its main thread to get + the handlers after all. Installing twice is harmless; the originals + are captured once. + + Returns: + True if our handlers are in place, False if it declined. + """ + global _original_sigint, _original_sigterm + if threading.current_thread() is not threading.main_thread(): + return False + current_sigint = signal.getsignal(signal.SIGINT) + current_sigterm = signal.getsignal(signal.SIGTERM) + if current_sigint is _signal_handler and current_sigterm is _signal_handler: + return True + # Never save our own handler as the original: that would recurse. + if current_sigint is not _signal_handler: + _original_sigint = current_sigint + if current_sigterm is not _signal_handler: + _original_sigterm = current_sigterm + try: + signal.signal(signal.SIGINT, _signal_handler) + signal.signal(signal.SIGTERM, _signal_handler) + except ValueError: + # Some embeddings refuse even on the main thread. + return False + return True + + +# atexit is thread-safe, so it is registered unconditionally. atexit.register(_cleanup_all) -_original_sigint = signal.getsignal(signal.SIGINT) -_original_sigterm = signal.getsignal(signal.SIGTERM) -signal.signal(signal.SIGINT, _signal_handler) -signal.signal(signal.SIGTERM, _signal_handler) +install_signal_handlers() class ChdkDevice: @@ -133,9 +176,10 @@ def switch_mode(self, mode): get_mode() to confirm the physical switch completed. """ mode_val = 1 if mode == "record" else 0 - self.lua_execute(f"switch_mode_usb({mode_val})", do_return=False) - # Wait for the script to finish before polling - self._chdk.wait_for_script(timeout=5) + script_id = self._chdk.execute_script(f"switch_mode_usb({mode_val})") + # Wait for the script to finish before polling, matching its id + # so an error left by an earlier shot is not blamed on this. + self._chdk.wait_for_script(timeout=5, script_id=script_id) # Give the camera time to physically switch (lens motor, etc.) time.sleep(1) for _ in range(8): @@ -170,7 +214,8 @@ def shoot(self, shutter_speed=None, market_iso=None, dng=False, Args: shutter_speed: Shutter speed in seconds (e.g., 1/100). market_iso: ISO value (e.g., 100, 200). - dng: If True, capture in DNG raw format. + dng: Request DNG. Not implemented on either path: streaming + refuses it, and the card path ignores it. stream: If True, use remote capture (direct USB transfer). download_after: If True (and stream=False), download from SD card. remove_after: If True, delete from SD card after download. @@ -192,32 +237,133 @@ def shoot(self, shutter_speed=None, market_iso=None, dng=False, return self._shoot_standard(parts, download_after, remove_after) def _shoot_streaming(self, setup_parts, dng): - """Capture using remote capture (PTP commands 13/14).""" - fmt = REMOTE_CAP_JPEG + """Capture using remote capture (PTP commands 13/14). + + Setup and shutter go out as one script, because a second script + kills the first unless NOKILL is set ("if script is running + return error instead of killing", core/ptp.h) — so a separate + shoot() could terminate the init_usb_capture that was still + running and leave the camera taking an ordinary card shot while + we waited for bytes that were never coming. + + The script is started, not waited on, and that order matters: + CHDK can hold the capture pipeline until the host takes the + data, so waiting for the script to return before downloading + leaves both sides waiting on each other and the capture times + out having never once asked whether data was ready. We service + the camera while the script runs — readiness first, messages + second. Once the picture is in hand the queue is cleared of + whatever the script left, which is housekeeping so the next + capture does not read a stale message: it is a bounded sweep of + what is already waiting, not a wait for a result still to come. + + Raises: + RuntimeError: If the camera refuses to initialize remote + capture. + NotImplementedError: If dng is True. CHDK's DNG_HDR flag + sends the DNG header only; the raw data is a separate + transfer, and the client has to splice the two into a + file. This method downloads one format, so it cannot, + and _shoot_standard does not request a DNG either. + """ if dng: - fmt = REMOTE_CAP_RAW | REMOTE_CAP_DNG_HDR - - script = "init_usb_capture({})".format(fmt) - for part in setup_parts: - script = part + "; " + script - self.lua_execute(script, do_return=False) + raise NotImplementedError( + "DNG capture is not implemented. Streaming would need the " + "DNG header and the raw data fetched as two separate " + "transfers and assembled into a file on this side, which " + "this library does not do; capturing to the card does not " + "request a DNG either, it runs shoot() and takes whatever " + "the camera is set to produce. Streamed JPEG works." + ) - self.lua_execute("shoot()", do_return=False) + fmt = REMOTE_CAP_JPEG + setup = "".join(part + "; " for part in setup_parts) + script = ( + f"{setup}local ok = init_usb_capture({fmt}); " + "if ok == false then return false end; " + "shoot(); " + "return true" + ) + script_id = self._chdk.execute_script(script) + image = None deadline = time.monotonic() + 30 + grace = CAPTURE_INIT_GRACE + init_deadline = time.monotonic() + grace while time.monotonic() < deadline: - ready, img_fmt = self._chdk.remote_capture_is_ready() + ready, status = self._chdk.remote_capture_is_ready() + formats = status if ready: - return self._chdk.remote_capture_get_data(img_fmt) + # A mask without the format we asked for is a fault, not + # a menu: the other bits are a different picture. + if not formats & fmt: + raise RuntimeError( + f"The camera has no 0x{fmt:02x} data ready; " + f"it offers 0x{formats:02x}" + ) + # The request parameter is one bit, not the whole mask. + image = self._chdk.remote_capture_get_data(fmt) + break + + running, has_msgs = self._chdk.get_script_status() + if has_msgs: + msg = self._chdk.read_script_message() + if msg.script_id == script_id: + if msg.msg_type == MessageType.ERR: + kind = _script_error_name(msg.data_type) + raise RuntimeError( + f"Capture script failed ({kind}): {msg.value}" + ) + # Only an explicit false is a refusal: an older CHDK + # returns nil, which must not be read as failure. + if msg.msg_type == MessageType.RET and msg.value is False: + raise RuntimeError( + "The camera refused to initialize remote " + "capture: init_usb_capture returned false" + ) + continue + + # Checked after the queue, so a script that explained itself + # is reported by its own words rather than by this status. + # The two ways of getting here are different observations + # and read differently in a bench log: a script that ran and + # did not initialize, versus one still going after we gave + # up waiting. Neither proves the camera cannot do this. + if status == REMOTE_CAP_NOTSET: + if not running: + raise RuntimeError( + "The capture script ended without initializing " + "remote capture" + ) + if time.monotonic() >= init_deadline: + raise RuntimeError( + "The capture script did not initialize remote " + f"capture within {grace}s and is still running" + ) + if not running: + raise RuntimeError( + "The capture script finished without producing a capture" + ) time.sleep(0.1) - raise TimeoutError("Remote capture did not complete") + + if image is None: + raise TimeoutError("Remote capture did not complete") + + # Clear what the script left behind so the next capture does not + # read a stale message — but never at the cost of this picture. + try: + self._chdk.drain_messages() + except Exception: + pass + return image def _shoot_standard(self, setup_parts, download, remove): """Capture to SD card, optionally download and delete.""" script = "; ".join(setup_parts + ["shoot()"]) - self.lua_execute(script, do_return=False) - # Wait for the shoot script to finish (shutter + SD write) - self._chdk.wait_for_script(timeout=30) + script_id = self._chdk.execute_script(script) + # Wait for the shoot script to finish (shutter + SD write), + # matching its id so a previous shot's error is not ours. + self._chdk.wait_for_script(timeout=30, script_id=script_id) if not download: return None diff --git a/src/pychdk/util.py b/src/pychdk/util.py index 766dfe6..e6b49ba 100644 --- a/src/pychdk/util.py +++ b/src/pychdk/util.py @@ -4,6 +4,7 @@ These functions convert between human-readable values and APEX96. """ import math +import re def shutter_to_tv96(shutter_speed): @@ -62,3 +63,86 @@ def to_camerapath(path): if path.startswith("A/") or path.startswith("A\\"): return path return "A/" + path + + +# A camera id is hex, long enough not to collide and short enough to +# read aloud over a workbench. The flasher mints twelve characters. +_CAMERA_ID_RE = re.compile(r"^[0-9a-f]{12,32}$") + + +def parse_own_txt(data): + """Read a camera's page parity and id from OWN.TXT. + + OWN.TXT records which pages a body shoots — ODD or EVEN — not which + side of the table it stands on; which parity appears on the left is + the operator's reading direction, and the file says nothing about + it. A second line, 'id=', carries a stable identity for the + body, because pyusb cannot always read a serial number from a Canon + compact. + + Tolerates CRLF, a byte order mark, surrounding whitespace, blank + lines, lowercase keywords, a missing id line and unknown lines. It + never raises: rubbish simply parses as nothing. + + An id counts only when it is twelve to thirty-two hexadecimal + characters. Every 'id=' line is examined and the first valid one + wins, so a corrupt line cannot shield a good one below it; any + further valid id is ignored rather than merged, because a file with + two identities has no way to say which body it belongs to. The id + comes back lowercased, so callers can compare it directly. + + Args: + data: File contents as bytes or str. + + Returns: + Tuple of (side, camera_id), where side is 'ODD', 'EVEN' or None + and camera_id is the first well-formed id, lowercased, or None. + """ + if isinstance(data, (bytes, bytearray)): + text = bytes(data).decode("utf-8-sig", errors="replace") + elif isinstance(data, str): + text = data + else: + return None, None + + side = None + camera_id = None + for line in text.splitlines(): + line = line.replace("\ufeff", "").strip() + if not line: + continue + if side is None and line.upper() in ("ODD", "EVEN"): + side = line.upper() + elif camera_id is None and line.upper().startswith("ID="): + value = line.split("=", 1)[1].strip().lower() + if _CAMERA_ID_RE.match(value): + camera_id = value + return side, camera_id + + +def format_own_txt(side, camera_id=None): + """Render the canonical OWN.TXT for a page parity and camera id. + + The parity is which pages the body shoots, ODD or EVEN, not a side + of the table. Each line is written only when there is something to + put on it: an id with no parity is a valid file, since a body keeps + its identity whether or not an operator has decided which pages it + shoots, and parse_own_txt reads it back. With neither, there is + nothing to record and the result is empty. + + Args: + side: 'ODD' or 'EVEN', in any case, or None for no parity. + camera_id: Stable hex identity for the body, or None. + + Returns: + File contents as a str with a single trailing newline, or an + empty string when there is nothing to write. + """ + lines = [] + if side: + lines.append(str(side).strip().upper()) + if camera_id: + lines.append("id=" + str(camera_id).strip()) + if not lines: + return "" + return "\n".join(lines) + "\n" diff --git a/tests/test_chdk.py b/tests/test_chdk.py index b7b932e..b0346ce 100644 --- a/tests/test_chdk.py +++ b/tests/test_chdk.py @@ -1,13 +1,16 @@ """Tests for CHDK PTP extension protocol.""" import struct -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch import pytest from pychdk.chdk import ( ChdkPTP, + REMOTE_CAP_NOTSET, ChdkCommand, ScriptLanguage, ScriptDataType, + ScriptErrorType, MessageType, + ScriptMessage, _decode_script_value, ) from pychdk.ptp import ResponseCode, PTPContainer, ContainerType @@ -75,6 +78,194 @@ def test_read_script_message_none(self): assert msg.value is None +class TestScriptErrors: + """An ERR message's subtype is an error type, not a data type.""" + + def _make_chdk(self): + mock_session = MagicMock() + return ChdkPTP(mock_session), mock_session + + def test_a_compile_error_keeps_its_text_and_kind(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ( + [MessageType.ERR, ScriptErrorType.COMPILE, 7, 28], + b"attempt to call a nil value\x00", + ) + msg = chdk.read_script_message() + assert msg.data_type == ScriptErrorType.COMPILE + assert msg.value == "attempt to call a nil value" + + def test_a_run_error_keeps_its_text_and_kind(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ( + [MessageType.ERR, ScriptErrorType.RUN, 7, 15], + b"bad argument\x00", + ) + msg = chdk.read_script_message() + assert msg.data_type == ScriptErrorType.RUN + assert msg.value == "bad argument" + + def test_an_error_with_no_text_is_empty_but_still_named(self): + chdk, session = self._make_chdk() + # The header promises at least one zero byte even with no message. + session.transaction.return_value = ( + [MessageType.ERR, ScriptErrorType.RUN, 7, 1], + b"\x00", + ) + msg = chdk.read_script_message() + assert msg.data_type == ScriptErrorType.RUN + assert msg.value == "" + + def test_a_return_value_with_a_colliding_subtype_still_decodes(self): + chdk, session = self._make_chdk() + # Subtype 2 is BOOLEAN for a RET and ERRTYPE_RUN for an ERR. + session.transaction.return_value = ( + [MessageType.RET, ScriptDataType.BOOLEAN, 7, 4], + struct.pack("= 1 + + def test_streaming_raises_when_the_camera_refuses_to_initialize(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = (False, 0) + mock_chdk.get_script_status.return_value = (True, True) + # init_usb_capture returned false, so the script returns false. + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.RET, ScriptDataType.BOOLEAN, 7, False, + ) + with pytest.raises(RuntimeError, match="initialize remote capture"): + dev.shoot(stream=True) + + def test_streaming_raises_a_script_error_with_its_text(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = (False, 0) + mock_chdk.get_script_status.return_value = (True, True) + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.ERR, ScriptErrorType.RUN, 7, "no such function", + ) + with pytest.raises(RuntimeError, match="no such function"): + dev.shoot(stream=True) + + def test_streaming_names_the_error_kind(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = (False, 0) + mock_chdk.get_script_status.return_value = (True, True) + seen = {} + for kind in (ScriptErrorType.COMPILE, ScriptErrorType.RUN): + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.ERR, kind, 7, "boom", + ) + with pytest.raises(RuntimeError) as caught: + dev.shoot(stream=True) + seen[kind] = str(caught.value) + # Telling the kinds apart in read_script_message is worth + # nothing if the capture path flattens them again. + assert "compile" in seen[ScriptErrorType.COMPILE] + assert "run" in seen[ScriptErrorType.RUN] + assert seen[ScriptErrorType.COMPILE] != seen[ScriptErrorType.RUN] + + def test_streaming_ignores_a_message_from_another_script(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.side_effect = [ + (False, 0), (True, 0x01), + ] + mock_chdk.get_script_status.return_value = (True, True) + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.ERR, ScriptErrorType.RUN, 3, "stale error", + ) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + + def test_streaming_tolerates_a_camera_that_returns_nothing(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.side_effect = [ + (False, 0), (True, 0x01), + ] + mock_chdk.get_script_status.return_value = (True, True) + # An older CHDK returns nil, which is not a refusal. + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.RET, ScriptDataType.NIL, 7, None, + ) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + + def test_an_early_not_initialized_poll_is_not_a_failure(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + # CHDK acknowledges a script as scheduled, not as run, so the + # first poll can land before init_usb_capture has executed. + mock_chdk.remote_capture_is_ready.side_effect = [ + (False, REMOTE_CAP_NOTSET), + (True, 0x01), + ] + mock_chdk.get_script_status.return_value = (True, False) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + + def test_a_script_that_ended_without_initializing_says_so(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + mock_chdk.get_script_status.return_value = (False, False) + with pytest.raises(RuntimeError, match="ended without initializing"): + dev.shoot(stream=True) + assert mock_chdk.remote_capture_is_ready.call_count == 1 + + def test_an_expired_grace_says_how_long_it_waited(self, monkeypatch): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + # Still running: the camera may merely be slow, which is a + # different observation from a script that finished. + mock_chdk.get_script_status.return_value = (True, False) + monkeypatch.setattr("pychdk.device.CAPTURE_INIT_GRACE", 0.0) + with pytest.raises(RuntimeError, match=r"within 0.0s"): + dev.shoot(stream=True) + + def test_neither_initialization_message_claims_incompatibility( + self, monkeypatch, + ): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + monkeypatch.setattr("pychdk.device.CAPTURE_INIT_GRACE", 0.0) + seen = [] + for running in (True, False): + mock_chdk.get_script_status.return_value = (running, False) + with pytest.raises(RuntimeError) as caught: + dev.shoot(stream=True) + seen.append(str(caught.value)) + assert seen[0] != seen[1] + for message in seen: + assert "support" not in message.lower() + assert "incompatible" not in message.lower() + + def test_an_initialization_failure_beats_the_early_status(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + # The status arrives first, but the script's own false is the + # better answer and must be the one reported. + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + mock_chdk.get_script_status.return_value = (True, True) + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.RET, ScriptDataType.BOOLEAN, 7, False, + ) + with pytest.raises(RuntimeError, match="refused to initialize"): + dev.shoot(stream=True) + + def test_a_script_error_beats_the_early_status(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + mock_chdk.get_script_status.return_value = (True, True) + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.ERR, ScriptErrorType.RUN, 7, "no such function", + ) + with pytest.raises(RuntimeError, match="no such function"): + dev.shoot(stream=True) + + def test_streaming_stops_when_the_script_ends_without_a_capture(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = (False, 0) + mock_chdk.get_script_status.return_value = (False, False) + with pytest.raises(RuntimeError, match="without producing a capture"): + dev.shoot(stream=True) + # Promptly, rather than spinning out the thirty-second deadline. + assert mock_chdk.remote_capture_is_ready.call_count == 1 + + def test_streaming_drains_the_script_after_downloading(self): + dev, mock_chdk = self._make_device() + self._ready_camera(mock_chdk) + assert dev.shoot(stream=True) == b"jpeg" + mock_chdk.drain_messages.assert_called_once() + + def test_a_failure_draining_does_not_lose_the_picture(self): + dev, mock_chdk = self._make_device() + self._ready_camera(mock_chdk) + mock_chdk.drain_messages.side_effect = RuntimeError("late boom") + assert dev.shoot(stream=True) == b"jpeg" + + def test_streaming_asks_for_a_single_data_type(self): + dev, mock_chdk = self._make_device() + # JPEG and RAW both ready; the request parameter takes one bit. + mock_chdk.remote_capture_is_ready.return_value = (True, 0x03) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + mock_chdk.remote_capture_get_data.assert_called_once_with(1) + + def test_streaming_refuses_a_mask_without_the_requested_format(self): + dev, mock_chdk = self._make_device() + # No JPEG on offer: RAW (0x2) and DNG header (0x4). Returning + # raw framebuffer bytes as though they were the JPEG asked for + # would be a wrong picture, not a substitute. + mock_chdk.remote_capture_is_ready.return_value = (True, 0x06) + with pytest.raises(RuntimeError, match="0x01.*0x06"): + dev.shoot(stream=True) + mock_chdk.remote_capture_get_data.assert_not_called() + + def test_streaming_jpeg_is_unchanged(self): + dev, mock_chdk = self._make_device() + mock_chdk.remote_capture_is_ready.return_value = (True, 0x01) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + mock_chdk.remote_capture_get_data.assert_called_once_with(1) + + def test_standard_shot_waits_on_its_own_script_id(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 11 + dev.shoot() + mock_chdk.wait_for_script.assert_called_once_with( + timeout=30, script_id=11, + ) + def test_close(self): dev, mock_chdk = self._make_device() dev.close() assert not dev.is_connected + + +class TestSignalHandlers: + """Signal handlers may only be installed from the main thread.""" + + def test_importing_from_a_worker_thread_does_not_raise(self): + saved_module = sys.modules.pop("pychdk.device", None) + failures = [] + + def reimport(): + try: + importlib.import_module("pychdk.device") + except BaseException as exc: + failures.append(exc) + + try: + thread = threading.Thread(target=reimport) + thread.start() + thread.join() + finally: + if saved_module is not None: + sys.modules["pychdk.device"] = saved_module + pychdk.device = saved_module + assert failures == [] + + def test_declines_on_a_worker_thread(self): + before = ( + signal.getsignal(signal.SIGINT), + signal.getsignal(signal.SIGTERM), + ) + results = [] + + def install(): + results.append(device.install_signal_handlers()) + + thread = threading.Thread(target=install) + thread.start() + thread.join() + assert results == [False] + assert signal.getsignal(signal.SIGINT) is before[0] + assert signal.getsignal(signal.SIGTERM) is before[1] + + def test_installing_twice_keeps_the_first_saved_originals(self): + saved_handlers = ( + signal.getsignal(signal.SIGINT), + signal.getsignal(signal.SIGTERM), + ) + saved_originals = (device._original_sigint, device._original_sigterm) + + def sentinel_sigint(signum, frame): + pass + + def sentinel_sigterm(signum, frame): + pass + + try: + signal.signal(signal.SIGINT, sentinel_sigint) + signal.signal(signal.SIGTERM, sentinel_sigterm) + assert device.install_signal_handlers() is True + assert device.install_signal_handlers() is True + assert signal.getsignal(signal.SIGINT) is device._signal_handler + assert signal.getsignal(signal.SIGTERM) is device._signal_handler + assert device._original_sigint is sentinel_sigint + assert device._original_sigterm is sentinel_sigterm + finally: + signal.signal(signal.SIGINT, saved_handlers[0]) + signal.signal(signal.SIGTERM, saved_handlers[1]) + device._original_sigint = saved_originals[0] + device._original_sigterm = saved_originals[1] diff --git a/tests/test_flash_chdk.py b/tests/test_flash_chdk.py new file mode 100644 index 0000000..a61a52b --- /dev/null +++ b/tests/test_flash_chdk.py @@ -0,0 +1,712 @@ +"""The flasher must not change a body's identity when a card is re-flashed.""" +import importlib.util +import plistlib +import subprocess +from pathlib import Path + +import pytest + +from pychdk.util import parse_own_txt + +TOOL = Path(__file__).resolve().parent.parent / "tools" / "flash_chdk.py" + +# Real `diskutil list -plist` output, captured on macOS 15 from a disk +# with a GUID partition scheme. The shapes below are taken from it: +# AllDisksAndPartitions holds whole disks, each with a Content naming +# the partition scheme and a Partitions list (APFS containers add +# APFSVolumes). A genuinely blank card — no partition map at all — +# could not be captured here, since it needs an SD card in a reader; +# _blank_layout() is this structure with the layout emptied, and the +# real thing is still worth one check at the bench. +PARTITIONED_LAYOUT = { + "AllDisks": ["disk4", "disk4s1"], + "AllDisksAndPartitions": [ + { + "Content": "GUID_partition_scheme", + "DeviceIdentifier": "disk4", + "OSInternal": False, + "Partitions": [ + { + "Content": "Apple_HFS", + "DeviceIdentifier": "disk4s1", + "DiskUUID": "12EEA754-2CA1-4EA7-A1B4-54DF40936F21", + "Size": 15931539456, + }, + ], + "Size": 15931539456, + }, + ], + "VolumesFromDisks": [], + "WholeDisks": ["disk4"], +} + + +def _blank_layout(): + """PARTITIONED_LAYOUT with no partition map and no filesystem.""" + return { + "AllDisks": ["disk4"], + "AllDisksAndPartitions": [ + { + "Content": "", + "DeviceIdentifier": "disk4", + "OSInternal": False, + "Size": 15931539456, + }, + ], + "VolumesFromDisks": [], + "WholeDisks": ["disk4"], + } + + +def _fake_run(layout=None, returncode=0, stdout=None): + """Stand in for _run, answering `diskutil list -plist` with a plist.""" + if stdout is None: + stdout = plistlib.dumps(layout).decode() if layout else "" + + def run(cmd, **kwargs): + return subprocess.CompletedProcess(cmd, returncode, stdout, "") + + return run + + +def _scheme_only_layout(scheme): + """A card carrying a partition map and nothing else.""" + return { + "AllDisksAndPartitions": [ + { + "Content": scheme, + "DeviceIdentifier": "disk4", + "OSInternal": False, + "Partitions": [], + "Size": 15931539456, + }, + ], + "WholeDisks": ["disk4"], + } + + +def _fat32_layout(): + """A card with the single FAT32 partition this tool creates.""" + return { + "AllDisksAndPartitions": [ + { + "Content": "FDisk_partition_scheme", + "DeviceIdentifier": "disk4", + "OSInternal": False, + "Partitions": [ + { + "Content": "DOS_FAT_32", + "DeviceIdentifier": "disk4s1", + "VolumeName": "CHDK_A2500", + "Size": 15931539456, + }, + ], + "Size": 15931539456, + }, + ], + "WholeDisks": ["disk4"], + } + + +def _two_volume_layout(): + """A card whose identity could live on a partition we never read.""" + return { + "AllDisks": ["disk4", "disk4s1", "disk4s2"], + "AllDisksAndPartitions": [ + { + "Content": "GUID_partition_scheme", + "DeviceIdentifier": "disk4", + "OSInternal": False, + "Partitions": [ + { + "Content": "Microsoft Basic Data", + "DeviceIdentifier": "disk4s1", + "Size": 7965769728, + }, + { + "Content": "Apple_HFS", + "DeviceIdentifier": "disk4s2", + "Size": 7965769728, + }, + ], + "Size": 15931539456, + }, + ], + "VolumesFromDisks": [], + "WholeDisks": ["disk4"], + } + + +def _dispatching_run(info=None, layout=None): + """Stand in for _run, answering `info` and `list` separately.""" + + def run(cmd, **kwargs): + payload = layout if "list" in cmd else info + stdout = plistlib.dumps(payload).decode() if payload is not None else "" + return subprocess.CompletedProcess(cmd, 0, stdout, "") + + return run + + +def _load_tool(): + """Load tools/flash_chdk.py, which is a script and not a package.""" + spec = importlib.util.spec_from_file_location("flash_chdk", TOOL) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class TestGetMountPoint: + """A path we guessed is worse than no path: callers cannot tell.""" + + def test_a_report_with_no_mount_point_fails(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr( + tool, "_run", _dispatching_run(info={"DeviceIdentifier": "disk4s1"}), + ) + with pytest.raises(SystemExit): + tool.get_mount_point("/dev/disk4") + + def test_an_empty_mount_point_fails(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _dispatching_run(info={"MountPoint": ""})) + with pytest.raises(SystemExit): + tool.get_mount_point("/dev/disk4") + + def test_a_mount_point_that_is_not_there_fails(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr( + tool, "_run", + _dispatching_run(info={"MountPoint": "/Volumes/NoSuchCard"}), + ) + with pytest.raises(SystemExit): + tool.get_mount_point("/dev/disk4") + + def test_a_real_mount_point_is_returned(self, tmp_path, monkeypatch): + tool = _load_tool() + monkeypatch.setattr( + tool, "_run", _dispatching_run(info={"MountPoint": str(tmp_path)}), + ) + assert tool.get_mount_point("/dev/disk4") == str(tmp_path) + + +class TestFormatCard: + """A format that did not come back mounted must not look like success.""" + + def test_a_reported_mount_point_proceeds(self, tmp_path, monkeypatch): + tool = _load_tool() + monkeypatch.setattr( + tool, "_run", _dispatching_run(info={"MountPoint": str(tmp_path)}), + ) + assert tool.format_card("/dev/disk4") == str(tmp_path) + + def test_no_mount_point_stops_before_anything_is_extracted( + self, monkeypatch, capsys, + ): + tool = _load_tool() + monkeypatch.setattr( + tool, "_run", _dispatching_run(info={"DeviceIdentifier": "disk4s1"}), + ) + with pytest.raises(SystemExit): + tool.format_card("/dev/disk4") + out = capsys.readouterr().out + assert "Nothing has been written" in out + + def test_a_mount_point_that_is_not_there_stops(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr( + tool, "_run", + _dispatching_run(info={"MountPoint": "/Volumes/NoSuchCard"}), + ) + with pytest.raises(SystemExit): + tool.format_card("/dev/disk4") + + def test_main_extracts_nothing_when_the_format_does_not_mount( + self, monkeypatch, + ): + tool = _load_tool() + extracted = [] + monkeypatch.setattr(tool, "download_chdk", lambda: None) + monkeypatch.setattr(tool, "find_removable_disks", lambda: []) + monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk4") + monkeypatch.setattr(tool, "_run", _dispatching_run( + info={"DeviceIdentifier": "disk4s1"}, + layout=_blank_layout(), + )) + monkeypatch.setattr( + tool, "extract_chdk", + lambda zip_path, mount: extracted.append(mount), + ) + with pytest.raises(SystemExit): + tool.main() + assert extracted == [] + + +class TestCameraIdSurvivesAReflash: + def test_main_reads_the_id_before_it_erases_the_card(self, monkeypatch): + tool = _load_tool() + calls = [] + received = {} + + def record(name, result=None): + def fake(*args, **kwargs): + calls.append(name) + return result + return fake + + def fake_write(mount_point, existing_side=None, existing_id=None): + calls.append("write_camera_side") + received["existing_side"] = existing_side + received["existing_id"] = existing_id + + monkeypatch.setattr(tool, "download_chdk", record("download_chdk")) + monkeypatch.setattr(tool, "find_removable_disks", record("find", [])) + monkeypatch.setattr(tool, "pick_disk", record("pick_disk", "/dev/disk9")) + monkeypatch.setattr( + tool, "read_existing_own_txt", + record("read_existing_own_txt", ("EVEN", "abc123def456")), + ) + monkeypatch.setattr(tool, "format_card", record("format_card", "/Volumes/X")) + monkeypatch.setattr(tool, "extract_chdk", record("extract_chdk")) + monkeypatch.setattr(tool, "patch_boot_sector", record("patch_boot_sector")) + monkeypatch.setattr(tool, "get_mount_point", record("get_mount_point", "/Volumes/X")) + monkeypatch.setattr(tool, "write_camera_side", fake_write) + monkeypatch.setattr(tool, "eject_card", record("eject_card")) + + tool.main() + + assert calls.index("read_existing_own_txt") < calls.index("format_card") + assert received["existing_id"] == "abc123def456" + assert received["existing_side"] == "EVEN" + + def test_write_camera_side_keeps_the_id_it_is_handed( + self, tmp_path, monkeypatch, capsys, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "e") + tool.write_camera_side(str(tmp_path), existing_id="abc123def456") + assert (tmp_path / "OWN.TXT").read_text() == "EVEN\nid=abc123def456\n" + assert "kept" in capsys.readouterr().out + + def test_write_camera_side_mints_an_id_when_there_is_none( + self, tmp_path, monkeypatch, capsys, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "o") + tool.write_camera_side(str(tmp_path)) + side, camera_id = parse_own_txt((tmp_path / "OWN.TXT").read_bytes()) + assert side == "ODD" + assert camera_id is not None + assert "minted" in capsys.readouterr().out + + def test_skipping_parity_leaves_the_existing_assignment_alone( + self, tmp_path, monkeypatch, capsys, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "s") + tool.write_camera_side( + str(tmp_path), existing_side="EVEN", existing_id="abc123def456", + ) + assert (tmp_path / "OWN.TXT").read_text() == "EVEN\nid=abc123def456\n" + assert "kept" in capsys.readouterr().out + + def test_skipping_parity_on_a_card_that_had_none_writes_the_id_alone( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "s") + tool.write_camera_side(str(tmp_path), existing_id="abc123def456") + assert (tmp_path / "OWN.TXT").read_text() == "id=abc123def456\n" + + def test_an_unrecognized_answer_leaves_the_assignment_alone( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "banana") + tool.write_camera_side( + str(tmp_path), existing_side="ODD", existing_id="abc123def456", + ) + assert (tmp_path / "OWN.TXT").read_text() == "ODD\nid=abc123def456\n" + + def test_choosing_a_parity_overrides_the_one_on_the_card( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "o") + tool.write_camera_side( + str(tmp_path), existing_side="EVEN", existing_id="abc123def456", + ) + assert (tmp_path / "OWN.TXT").read_text() == "ODD\nid=abc123def456\n" + + def test_skipping_parity_with_no_id_writes_nothing( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "s") + tool.write_camera_side(str(tmp_path)) + assert not (tmp_path / "OWN.TXT").exists() + + def test_a_card_with_no_filesystem_is_treated_as_blank( + self, monkeypatch, capsys, + ): + tool = _load_tool() + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "get_mount_point", refuse) + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) + assert tool.read_existing_own_txt("/dev/disk4") == (None, None) + assert "blank" in capsys.readouterr().out + + def test_a_volume_that_will_not_mount_stops_the_run( + self, monkeypatch, capsys, + ): + tool = _load_tool() + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "get_mount_point", refuse) + # diskutil says there is a filesystem, but it would not mount. + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) + with pytest.raises(SystemExit): + tool.read_existing_own_txt("/dev/disk4") + assert "could not be mounted" in capsys.readouterr().out + + def test_main_does_not_erase_a_volume_it_could_not_mount( + self, monkeypatch, + ): + tool = _load_tool() + formatted = [] + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "download_chdk", lambda: None) + monkeypatch.setattr(tool, "find_removable_disks", lambda: []) + monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk4") + monkeypatch.setattr(tool, "get_mount_point", refuse) + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) + monkeypatch.setattr( + tool, "format_card", lambda disk: formatted.append(disk), + ) + with pytest.raises(SystemExit): + tool.main() + assert formatted == [] + + def test_a_layout_that_cannot_be_inspected_stops_the_run( + self, monkeypatch, + ): + tool = _load_tool() + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "get_mount_point", refuse) + # diskutil itself failed: the card is not demonstrably blank. + monkeypatch.setattr(tool, "_run", _fake_run(returncode=1)) + with pytest.raises(SystemExit): + tool.read_existing_own_txt("/dev/disk4") + + def test_unparseable_layout_stops_the_run(self, monkeypatch): + tool = _load_tool() + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "get_mount_point", refuse) + monkeypatch.setattr(tool, "_run", _fake_run(stdout="not a plist")) + with pytest.raises(SystemExit): + tool.read_existing_own_txt("/dev/disk4") + + def test_a_nested_volume_with_no_content_is_still_a_filesystem( + self, monkeypatch, + ): + tool = _load_tool() + # The parent carries nothing but a scheme, so the nested volume + # is the only thing that can decide. Real APFS volumes have no + # Content of their own and name themselves instead; without the + # name and mount-point checks this classifies as blank. + layout = { + "AllDisksAndPartitions": [ + { + "Content": "GUID_partition_scheme", + "DeviceIdentifier": "disk4", + "Size": 15931539456, + "Partitions": [], + "APFSVolumes": [ + { + "DeviceIdentifier": "disk4s1", + "MountPoint": "/Volumes/Card", + "VolumeName": "Card", + "Size": 15931539456, + }, + ], + }, + ], + } + monkeypatch.setattr(tool, "_run", _fake_run(layout)) + assert tool._classify_card("/dev/disk4") == tool.CARD_HAS_FILESYSTEM + + def test_an_apfs_container_on_the_whole_disk_is_a_filesystem( + self, monkeypatch, + ): + tool = _load_tool() + # The parent-level case, separated out: Apple_APFS_Container is + # not a partition scheme, so the entry decides on its own and + # the nested volumes are never reached. + layout = { + "AllDisksAndPartitions": [ + { + "Content": "Apple_APFS_Container", + "DeviceIdentifier": "disk4", + "Size": 15931539456, + }, + ], + } + monkeypatch.setattr(tool, "_run", _fake_run(layout)) + assert tool._classify_card("/dev/disk4") == tool.CARD_HAS_FILESYSTEM + + def test_a_volume_is_judged_by_name_or_mount_point_or_content(self): + tool = _load_tool() + assert tool._volume_holds_a_filesystem({"VolumeName": "Card"}) + assert tool._volume_holds_a_filesystem({"MountPoint": "/Volumes/Card"}) + assert tool._volume_holds_a_filesystem({"Content": "DOS_FAT_32"}) + assert not tool._volume_holds_a_filesystem( + {"DeviceIdentifier": "disk4s1", "Size": 1}, + ) + + def test_a_blank_layout_is_classified_blank(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) + assert tool._classify_card("/dev/disk4") == tool.CARD_BLANK + + def test_a_partitioned_layout_holds_a_filesystem(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) + assert tool._classify_card("/dev/disk4") == tool.CARD_HAS_FILESYSTEM + + def test_an_empty_layout_list_is_unknown_not_blank(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run({"AllDisksAndPartitions": []})) + assert tool._classify_card("/dev/disk4") == tool.CARD_UNKNOWN + + def test_an_empty_entry_is_unknown_not_blank(self, monkeypatch): + tool = _load_tool() + # Nothing here says the device is empty; it says nothing at all. + monkeypatch.setattr(tool, "_run", _fake_run({ + "AllDisksAndPartitions": [{}], + })) + assert tool._classify_card("/dev/disk4") == tool.CARD_UNKNOWN + + def test_an_entry_of_unrecognized_fields_is_unknown(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run({ + "AllDisksAndPartitions": [ + {"SomeFutureKey": "whatever", "DeviceIdentifier": "disk4"}, + ], + })) + assert tool._classify_card("/dev/disk4") == tool.CARD_UNKNOWN + + def test_a_payload_about_another_device_is_unknown(self, monkeypatch): + tool = _load_tool() + # A blank layout, but not for the card we asked about. + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) + assert tool._classify_card("/dev/disk9") == tool.CARD_UNKNOWN + + def test_a_bare_disk_identifier_is_accepted(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) + assert tool._classify_card("disk4") == tool.CARD_BLANK + + def test_an_unmountable_card_with_a_filesystem_stops_the_run( + self, monkeypatch, + ): + tool = _load_tool() + # diskutil reports no mount point; the layout shows a filesystem. + # The old guessed path made this read as a clean absence. + monkeypatch.setattr(tool, "_run", _dispatching_run( + info={"DeviceIdentifier": "disk4s1"}, + layout=PARTITIONED_LAYOUT, + )) + with pytest.raises(SystemExit): + tool.read_existing_own_txt("/dev/disk4") + + def test_main_does_not_erase_a_card_it_could_not_mount(self, monkeypatch): + tool = _load_tool() + formatted = [] + monkeypatch.setattr(tool, "download_chdk", lambda: None) + monkeypatch.setattr(tool, "find_removable_disks", lambda: []) + monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk4") + monkeypatch.setattr(tool, "_run", _dispatching_run( + info={"DeviceIdentifier": "disk4s1"}, + layout=PARTITIONED_LAYOUT, + )) + monkeypatch.setattr( + tool, "format_card", lambda disk: formatted.append(disk), + ) + with pytest.raises(SystemExit): + tool.main() + assert formatted == [] + + def test_a_partition_map_with_no_partitions_is_blank(self, monkeypatch): + tool = _load_tool() + # A card that has been formatted and emptied still carries a + # scheme. That is the ordinary state of a card from a camera. + monkeypatch.setattr(tool, "_run", _fake_run(_scheme_only_layout( + "FDisk_partition_scheme", + ))) + assert tool._classify_card("/dev/disk4") == tool.CARD_BLANK + + def test_a_guid_scheme_with_no_partitions_is_blank(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(_scheme_only_layout( + "GUID_partition_scheme", + ))) + assert tool._classify_card("/dev/disk4") == tool.CARD_BLANK + + def test_a_device_with_no_content_at_all_is_blank(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) + assert tool._classify_card("/dev/disk4") == tool.CARD_BLANK + + def test_one_fat32_partition_holds_a_filesystem(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(_fat32_layout())) + assert tool._classify_card("/dev/disk4") == tool.CARD_HAS_FILESYSTEM + + def test_a_freshly_formatted_card_can_still_be_flashed( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr(tool, "_run", _fake_run(_fat32_layout())) + assert tool.read_existing_own_txt("/dev/disk4") == (None, None) + + def test_an_empty_partitioned_card_is_not_refused(self, monkeypatch): + tool = _load_tool() + # The common case: a card out of a camera or a shop. Refusing + # this made the tool unusable on the first card anyone picked up. + monkeypatch.setattr(tool, "_run", _fake_run(_scheme_only_layout( + "FDisk_partition_scheme", + ))) + assert tool.read_existing_own_txt("/dev/disk4") == (None, None) + + def test_a_volume_we_cannot_characterize_is_unknown(self, monkeypatch): + tool = _load_tool() + # Something is under there, but nothing says what it is. + monkeypatch.setattr(tool, "_run", _fake_run({ + "AllDisksAndPartitions": [ + { + "Content": "FDisk_partition_scheme", + "DeviceIdentifier": "disk4", + "Size": 15931539456, + "Partitions": [{"DeviceIdentifier": "disk4s1"}], + }, + ], + })) + assert tool._classify_card("/dev/disk4") == tool.CARD_UNKNOWN + + def test_a_mounted_card_with_no_own_txt_has_no_id( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) + assert tool.read_existing_own_txt("/dev/disk4") == (None, None) + + def test_an_unreadable_own_txt_stops_rather_than_reporting_no_id( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + # A path that exists but cannot be read as a file: not absence. + (tmp_path / "OWN.TXT").mkdir() + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) + with pytest.raises(SystemExit): + tool.read_existing_own_txt("/dev/disk4") + + def test_main_does_not_erase_a_card_it_could_not_check( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + (tmp_path / "OWN.TXT").mkdir() + formatted = [] + monkeypatch.setattr(tool, "download_chdk", lambda: None) + monkeypatch.setattr(tool, "find_removable_disks", lambda: []) + monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk4") + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) + monkeypatch.setattr( + tool, "format_card", lambda disk: formatted.append(disk), + ) + with pytest.raises(SystemExit): + tool.main() + assert formatted == [] + + +class TestOnlyAnInspectableLayoutMayBeErased: + """A mountable first partition is not an inspection of the card.""" + + def test_a_second_volume_stops_before_any_erase( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + formatted = [] + monkeypatch.setattr(tool, "download_chdk", lambda: None) + monkeypatch.setattr(tool, "find_removable_disks", lambda: []) + monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk4") + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr(tool, "_run", _fake_run(_two_volume_layout())) + monkeypatch.setattr( + tool, "format_card", lambda disk: formatted.append(disk), + ) + with pytest.raises(SystemExit): + tool.main() + assert formatted == [] + + def test_a_mountable_s1_with_another_volume_is_not_an_absence( + self, tmp_path, monkeypatch, capsys, + ): + tool = _load_tool() + # s1 mounts and has no OWN.TXT — but disk4s2 does, and we never + # look there, so this is not evidence the card has no identity. + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr(tool, "_run", _fake_run(_two_volume_layout())) + with pytest.raises(SystemExit): + tool.read_existing_own_txt("/dev/disk4") + assert "cannot inspect" in capsys.readouterr().out + + def test_a_single_inspectable_volume_proceeds( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + (tmp_path / "OWN.TXT").write_text("EVEN\nid=abc123def456\n") + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) + assert tool.read_existing_own_txt("/dev/disk4") == ( + "EVEN", "abc123def456", + ) + + def test_a_blank_layout_proceeds_with_no_identity(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) + assert tool.read_existing_own_txt("/dev/disk4") == (None, None) + + def test_a_filesystem_on_the_whole_device_is_not_inspectable( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr(tool, "_run", _fake_run({ + "AllDisksAndPartitions": [ + { + "Content": "Apple_HFS", + "DeviceIdentifier": "disk4", + "Size": 15931539456, + }, + ], + })) + with pytest.raises(SystemExit): + tool.read_existing_own_txt("/dev/disk4") diff --git a/tests/test_imports.py b/tests/test_imports.py new file mode 100644 index 0000000..c194f07 --- /dev/null +++ b/tests/test_imports.py @@ -0,0 +1,45 @@ +"""What importing the package is allowed to drag in with it.""" +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import pychdk + +SRC = Path(__file__).resolve().parent.parent / "src" + + +def _run_import(code): + """Run a snippet against this checkout in a fresh interpreter.""" + env = dict(os.environ, PYTHONPATH=str(SRC)) + return subprocess.run( + [sys.executable, "-c", code], + capture_output=True, text=True, env=env, + ) + + +class TestFlasherStaysStdlibOnly: + """tools/flash_chdk.py must run on a fresh macOS, pyusb or not.""" + + def test_importing_pychdk_util_does_not_pull_in_pyusb(self): + result = _run_import( + "import pychdk.util, sys; print('usb' in sys.modules)" + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "False" + + +class TestExports: + def test_every_name_in_all_is_reachable(self): + for name in pychdk.__all__: + assert getattr(pychdk, name) is not None + + def test_util_is_the_submodule(self): + import pychdk.util + assert pychdk.util is sys.modules["pychdk.util"] + + def test_unknown_name_raises_attribute_error(self): + with pytest.raises(AttributeError, match="has no attribute 'nope'"): + pychdk.nope diff --git a/tests/test_util.py b/tests/test_util.py index 40a58b8..b296100 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -5,6 +5,8 @@ iso_to_sv96, aperture_to_av96, to_camerapath, + parse_own_txt, + format_own_txt, ) @@ -48,3 +50,102 @@ def test_already_prefixed(self): def test_own_txt(self): assert to_camerapath("OWN.TXT") == "A/OWN.TXT" + + +class TestParseOwnTxt: + def test_parity_only(self): + assert parse_own_txt(b"EVEN\n") == ("EVEN", None) + + def test_parity_and_id(self): + assert parse_own_txt(b"EVEN\nid=3f9a1c2b7d4e\n") == ( + "EVEN", "3f9a1c2b7d4e", + ) + + def test_accepts_str(self): + assert parse_own_txt("ODD\nid=abc123def456\n") == ("ODD", "abc123def456") + + def test_crlf(self): + assert parse_own_txt(b"ODD\r\nid=abc123def456\r\n") == ("ODD", "abc123def456") + + def test_byte_order_mark(self): + assert parse_own_txt(b"\xef\xbb\xbfEVEN\nid=abc123def456\n") == ( + "EVEN", "abc123def456", + ) + + def test_trailing_whitespace(self): + assert parse_own_txt(b" EVEN \n id=abc123def456 \n") == ( + "EVEN", "abc123def456", + ) + + def test_blank_lines(self): + assert parse_own_txt(b"\n\nODD\n\n\nid=abc123def456\n\n") == ( + "ODD", "abc123def456", + ) + + def test_lowercase(self): + assert parse_own_txt(b"odd\nId=ABC123DEF456\n") == ("ODD", "abc123def456") + + def test_missing_id_line(self): + assert parse_own_txt(b"ODD") == ("ODD", None) + + def test_unknown_lines_are_ignored(self): + data = b"# written by flash_chdk\nEVEN\nnotes=whatever\nid=abc123def456\n" + assert parse_own_txt(data) == ("EVEN", "abc123def456") + + def test_a_malformed_id_line_does_not_hide_a_good_one(self): + assert parse_own_txt(b"ODD\nid=\xff\nid=3f9a1c2b7d4e\n") == ( + "ODD", "3f9a1c2b7d4e", + ) + + def test_an_uppercase_id_comes_back_lowercase(self): + assert parse_own_txt(b"ODD\nid=3F9A1C2B7D4E\n") == ( + "ODD", "3f9a1c2b7d4e", + ) + + def test_a_too_short_id_is_rejected(self): + assert parse_own_txt(b"ODD\nid=3f9a1c2b\n") == ("ODD", None) + + def test_a_non_hex_id_is_rejected(self): + assert parse_own_txt(b"ODD\nid=not-an-id-at-all\n") == ("ODD", None) + + def test_the_first_valid_id_wins(self): + data = b"ODD\nid=3f9a1c2b7d4e\nid=aaaaaaaaaaaa\n" + assert parse_own_txt(data) == ("ODD", "3f9a1c2b7d4e") + + def test_rubbish_gives_nothing(self): + assert parse_own_txt(b"\xff\xfe not a parity file at all") == ( + None, None, + ) + + def test_empty(self): + assert parse_own_txt(b"") == (None, None) + + def test_does_not_raise_on_a_wrong_type(self): + assert parse_own_txt(None) == (None, None) + + +class TestFormatOwnTxt: + def test_parity_and_id(self): + assert format_own_txt("EVEN", "3f9a1c2b7d4e") == ( + "EVEN\nid=3f9a1c2b7d4e\n" + ) + + def test_id_line_omitted_without_an_id(self): + assert format_own_txt("ODD") == "ODD\n" + + def test_parity_is_uppercased(self): + assert format_own_txt("even", "abc123def456") == "EVEN\nid=abc123def456\n" + + def test_an_id_alone_needs_no_parity(self): + assert format_own_txt(None, "3f9a1c2b7d4e") == "id=3f9a1c2b7d4e\n" + + def test_nothing_to_say_writes_nothing(self): + assert format_own_txt(None, None) == "" + + def test_round_trip_of_an_id_without_a_parity(self): + text = format_own_txt(None, "3f9a1c2b7d4e") + assert parse_own_txt(text) == (None, "3f9a1c2b7d4e") + + def test_round_trip(self): + text = format_own_txt("odd", "3f9a1c2b7d4e") + assert parse_own_txt(text) == ("ODD", "3f9a1c2b7d4e") diff --git a/tests/test_version.py b/tests/test_version.py new file mode 100644 index 0000000..aa9f545 --- /dev/null +++ b/tests/test_version.py @@ -0,0 +1,17 @@ +"""The package version and pyproject.toml must not drift apart.""" +import tomllib +from pathlib import Path + +import pychdk + + +def _pyproject_version(): + """Read project.version from the pyproject.toml beside this checkout.""" + pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml" + with pyproject.open("rb") as f: + return tomllib.load(f)["project"]["version"] + + +class TestVersion: + def test_package_version_matches_pyproject(self): + assert pychdk.__version__ == _pyproject_version() diff --git a/tools/flash_chdk.py b/tools/flash_chdk.py index c6af5a9..9e074e5 100755 --- a/tools/flash_chdk.py +++ b/tools/flash_chdk.py @@ -7,12 +7,17 @@ """ import plistlib +import secrets import subprocess import sys import urllib.request import zipfile from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src")) + +from pychdk.util import format_own_txt, parse_own_txt + CHDK_URL = "https://www.mighty-hoernsche.de/bins/a2500-100a-1.6.1-6315-full.zip" CHDK_FILENAME = "a2500-100a-1.6.1-6315-full.zip" CACHE_DIR = Path.home() / ".cache" / "pychdk" @@ -110,10 +115,17 @@ def format_card(disk: str) -> str: "FAT32", VOLUME_LABEL, "MBRFormat", disk, ]) - partition = disk + "s1" - info_result = _run(["diskutil", "info", "-plist", partition]) - info = plistlib.loads(info_result.stdout.encode()) - mount_point = info.get("MountPoint", f"/Volumes/{VOLUME_LABEL}") + # eraseDisk leaves the new volume mounted, so do not mount again — + # but insist that it really is mounted rather than guessing a path. + mount_point = get_mount_point( + disk, + mount=False, + context=( + f"{disk} was formatted and then did not come back as a " + "mounted volume. Nothing has been written to the card. " + "Reinsert it and run this again." + ), + ) print(f"Formatted. Mounted at {mount_point}") return mount_point @@ -174,32 +186,406 @@ def patch_boot_sector(disk: str): print("Boot sector patched.") -def get_mount_point(disk: str) -> str: - """Mount partition and return mount point.""" +def _no_mount_point(reason: str, context: str): + """Report that there is no usable mount point, and stop.""" + print(reason) + if context: + print(context) + sys.exit(1) + + +def get_mount_point(disk: str, mount: bool = True, context: str = "") -> str: + """Return where the card's first partition is actually mounted. + + This is the only place that decides what counts as a mount point, + and the only place that fails when there is not one. Both callers + used to fall back to /Volumes/