Skip to content

A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.

Rust

Add disposable transfer baseline and safe export design (#60)

Vishnu Srivatsava6758071a28de
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index d959423..ba193bf 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -73,6 +73,10 @@ jobs:
- name: Test frontend helpers
run: npm test
+ - name: Test transfer benchmark offline on Windows
+ if: runner.os == 'Windows'
+ run: python -m unittest discover -s tests -p test_transfer_benchmark.py -v
+
- name: Test daemon protocol on host
if: runner.os != 'Windows'
run: python3 -m unittest discover -s tests -v
diff --git a/README.md b/README.md
index cdc3af2..f494d38 100644
--- a/README.md
+++ b/README.md
@@ -282,6 +282,10 @@ npm run build
cargo test --locked --manifest-path src-tauri/Cargo.toml --lib
```
+For the optional, manually run ADB/MTP copy experiment, see
+[the file-transfer baseline and export plan](docs/file-transfer.md). Regression
+tests use offline fixtures and mocked ADB calls; they do not contact a phone.
+
The line-based protocol preserves spaces in filenames. Paths containing a
newline, carriage return, or null byte are rejected before sending, so they
cannot cause a different file to be deleted. Scan responses containing invalid
diff --git a/docs/file-transfer.md b/docs/file-transfer.md
new file mode 100644
index 0000000..2cce42c
--- /dev/null
+++ b/docs/file-transfer.md
@@ -0,0 +1,150 @@
+# File-transfer baseline and single-file export plan
+
+Tracked in [#59](https://github.com/VishnuSrivatsava/SocketSweep/issues/59).
+This change adds an experiment and a design, not an application download button.
+No device throughput has been measured for this work. Backend selection remains
+open until the manual results and source-access requirements below are assessed.
+
+## Why measure the existing backend first?
+
+[ADB already supports file and directory downloads, explicit device selection,
+and optional compression](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/user/adb.1.md).
+Using it may avoid maintaining another binary protocol in both the C++ daemon
+and Rust host. It does not provide the application's overwrite, session,
+cancellation, or source-confinement policy by itself.
+
+[matu6968's transfer fork](https://github.com/matu6968/SocketSweep/commit/eda8a628cdd14d0a66f24fb86a093fc0cf5971dc)
+provides useful prior art for file pickers, progress, and streaming transfers.
+Its direct destination writes are unsuitable for adoption unchanged: a failed
+transfer can damage an existing destination. It also predates the current
+authenticated sessions and generation-scoped scan store. No transfer-speed
+advantage has been demonstrated here. Scan traversal timings do not establish
+file-copy throughput.
+
+## Run the disposable experiment
+
+Requirements: Python 3.9+, an installed ADB CLI supporting `pull -Z`, a connected
+authorized device, and enough free host/device space. The script uses only the
+Python standard library. **Only the `pull` subcommand contacts a device.**
+Upload and cleanup are manual. There is no remote shell, deletion, daemon start,
+root command, or permission change in the script.
+
+Run these commands yourself from the repository root. On macOS/Linux:
+
+```sh
+BENCH_BASE=$(mktemp -d /tmp/socketsweep-transfer.XXXXXX)
+WORKSPACE="$BENCH_BASE/fixture"
+python3 tests/benchmark_transfer.py prepare "$WORKSPACE"
+FIXTURE=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["fixture"])' "$WORKSPACE/manifest.json")
+
+# Choose the exact serial from your own device list.
+adb devices -l
+SERIAL='YOUR_DEVICE_SERIAL'
+adb version
+
+# /sdcard/Download must already exist. Upload only the generated fixture.
+adb -s "$SERIAL" push -Z "$WORKSPACE/$FIXTURE" /sdcard/Download/
+
+# First verified ADB downloads; each output directory must be new.
+python3 tests/benchmark_transfer.py pull "$WORKSPACE" --serial "$SERIAL" --workload large --output "$BENCH_BASE/adb-large-1"
+python3 tests/benchmark_transfer.py pull "$WORKSPACE" --serial "$SERIAL" --workload small --output "$BENCH_BASE/adb-small-1"
+```
+
+The default fixture is one 64 MiB file and 1,000 files of 4,096 bytes each
+(67.90625 MiB total). Bytes come from `os.urandom`; they approximate incompressible
+data, not zero-filled files that make compression look unrealistically fast.
+The same fixture must be used across backends. A new fixture has a random UUID
+name and a SHA-256 manifest. Creation never reuses an existing workspace.
+`prepare --large-mib 512 --small-count 2000` can create a longer experiment in a
+new workspace; limits are 1–1,024 MiB and 1–5,000 small files. Generation, upload,
+and hash checking are not part of measured transfer time.
+
+An ADB run writes `result.json` only after a successful command and exact file
+count, type, size, and SHA-256 verification. It reports transfer wall time,
+verification time separately, and payload MiB/s. Serial numbers are not written
+to the result. Console ADB output may still contain device/local information;
+review it before posting. `--compression any` explicitly tests ADB's negotiated
+compression separately; default `none` passes `-Z`. No silent flag fallback is
+allowed. `--adb /path/to/adb` selects another executable if needed.
+
+For MTP, use your chosen MTP client to copy the **large** workload directory from
+`Download/<fixture>/large` into a fresh local directory. Time the copy from start
+until the client reports completion; stop the timer before hash verification.
+Then run, substituting your destination and measured seconds:
+
+```sh
+python3 tests/benchmark_transfer.py verify "$WORKSPACE" --workload large --copy /path/to/copied/large --seconds 12.34 --backend mtp
+```
+
+Repeat for `small`. `verify` prints JSON only on success and never contacts the
+device. MTP timing is explicitly manual; it is not directly instrumented like
+ADB timing. Use `--backend local-control` only for an offline copy/harness check,
+never as a device performance result. Copy directories must contain exactly the
+generated regular files; missing/extra entries, symlinks, directories, changed
+sizes, or changed hashes fail validation.
+
+Use at least three verified runs per workload/backend, with a new destination
+each time. Alternate ADB and MTP order between rounds. Keep first and repeated
+runs separate; upload and previous reads warm caches. Do not claim cold-cache
+measurements without a controlled way to establish them. Keep the same cable,
+port, device mode, and workload. Some MTP clients may require releasing their
+connection before ADB can use USB; record that and exclude switching/setup from
+the timed copy consistently. Do not change global ADB server state to make a
+benchmark pass.
+
+Record device model/Android version (not serial), host OS, ADB version, MTP
+client/version, cable/port, workload manifest, compression setting, run order,
+all verified durations, and failures. Report medians **and individual runs**.
+64 MiB may be too short for sustained throughput: increase it if startup cost or
+timing precision dominates. These two workloads do not cover real photos,
+compressible data, arbitrary filenames, or long-duration thermals.
+
+On failure, timeout (10 minutes per ADB copy), or Ctrl-C, the fresh output folder
+may contain partial data; no successful result is written. Keep it for inspection
+or remove that exact local experiment folder manually. Do not reuse it. After
+testing, delete only the UUID-named fixture directory you created in the phone's
+Download folder through your file manager, and your local experiment directory.
+No automatic recursive device cleanup is supplied.
+
+The tool assumes a trusted local experiment directory. It rejects manifest path
+traversal and copied symlinks but does not defend against another process racing
+local filesystem operations. It is not a safe-export implementation to copy into
+the application.
+
+## Safe first application export
+
+Scope: save one regular file from the current scan to the computer. No folders,
+uploads, custom protocol, APK, or Android OS changes in this step.
+
+| Boundary | Required behavior |
+| --- | --- |
+| Frontend → Rust | Accept the current generation, revision, and node ID; resolve the exact path and regular-file kind in the Rust catalog. Never accept a frontend-supplied device path or destination path. Preserve Unicode, whitespace, and punctuation exactly. |
+| Session ownership | Bind an operation to the device serial and session identity before opening the native save picker; recheck after the picker and before publishing. Reconnect, rescan, deletion, disconnect, or cancellation invalidates stale work. Coordinate with session teardown without holding a lock that prevents cancellation. |
+| Privilege | Start with ordinary shell-readable shared storage. Never invoke `adb root`, `su`, or change permissions to make a download work. Root-only paths remain unsupported until their read-access policy is explicitly designed. |
+| Destination authority | Rust owns the native save picker result and collision decision. A filename from the device is only a suggested basename, never a local relative path. An unconfirmed collision cannot truncate or replace an existing file. |
+| Staging and commit | Download into a private, exclusively created staging location on the destination filesystem. Verify completion and close handles before publishing. The final commit must enforce the confirmed collision policy under races, including a destination appearing after the picker. Preserve existing destination bytes on every pre-commit failure; clean up only this operation's staging files. Define and test platform-specific commit semantics rather than assuming ordinary rename means no-clobber. |
+| Source identity | A scanned path is a snapshot, not a durable handle. Decide whether a changed file is rejected; do not claim source confinement or snapshot identity from a preflight `stat` followed by `adb pull`. Symlink replacement and source mutation require explicit handling. |
+| Progress and cancellation | Bound progress event frequency and payload. Bind every event/cancel request to an operation ID. Kill and reap only its child process, close handles, and remove its staging files. Timeout, unplug, user cancel, and stale-session errors cannot publish success. Define the commit point: cancellation before it aborts; after commit report that the file was saved. |
+| Integrity and errors | Check subprocess/protocol completion, actual bytes written, and the agreed source-change policy before commit. Do not label a size check as a hash check or promise original creation-time preservation. Surface actionable failure reasons without exposing session tokens. |
+
+The current scan catalog's scoped IDs are a useful foundation, but they do not
+yet provide an export operation. Session lifecycle changes should fit the work
+tracked in [#37](https://github.com/VishnuSrivatsava/SocketSweep/issues/37).
+
+### Backend decision and acceptance
+
+Prefer ADB if measured performance is adequate **and** its behavior can satisfy
+the agreed access/identity contract. A speed win cannot justify bypassing source
+policy. If securely opening a file beneath an approved root cannot be guaranteed
+through ADB, evaluate a narrowly scoped authenticated daemon read using an
+anchored file descriptor and no-follow traversal, not the fork's prefix checks.
+That is a separate implementation decision after this baseline.
+
+Before shipping, test the actual chosen backend with fake-process/host fixtures
+for existing-target preservation, collision races, cancellation before and after
+commit, timeout/unplug, stale generation/session, source change, symlinks,
+zero-byte files, exact unusual names, and Windows/macOS/Linux destination rules.
+Then manually validate picker, progress, cancel, and byte integrity on a connected
+device. Neither the benchmark's mocked ADB tests nor a production build proves
+those application behaviors. Record the device evidence in #59 and open a focused
+implementation issue after choosing the backend and resolving these contracts.
diff --git a/tests/benchmark_transfer.py b/tests/benchmark_transfer.py
new file mode 100644
index 0000000..02c9954
--- /dev/null
+++ b/tests/benchmark_transfer.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python3
+"""Disposable ADB/MTP download baseline. Nothing contacts a device on import.
+
+Only `pull` invokes ADB. Fixture upload and cleanup are manual. This is a
+trusted-local-filesystem experiment, not the application's export implementation.
+"""
+import argparse
+import hashlib
+import json
+import math
+import os
+from pathlib import Path
+import re
+import stat
+import subprocess
+import sys
+import time
+import uuid
+
+MIB = 1024 * 1024
+WORKLOADS = ("large", "small")
+
+
+def write_json(path, value):
+ with path.open("x", encoding="utf-8") as stream:
+ json.dump(value, stream, indent=2, allow_nan=False)
+ stream.write("\n")
+
+
+def prepare(workspace, large_mib=64, small_count=1000):
+ if not 1 <= large_mib <= 1024 or not 1 <= small_count <= 5000:
+ raise ValueError("Use 1–1024 large MiB and 1–5000 small files")
+ workspace.mkdir() # Never reuse or overwrite an existing experiment.
+ name = "SocketSweep-benchmark-" + uuid.uuid4().hex
+ root = workspace / name
+ records = {}
+ for workload in WORKLOADS:
+ (root / workload).mkdir(parents=True)
+ sizes = [large_mib * MIB] if workload == "large" else [4096] * small_count
+ for index, size in enumerate(sizes):
+ relative = f"{workload}/file-{index:06d}.bin"
+ digest = hashlib.sha256()
+ with (root / relative).open("xb") as stream:
+ remaining = size
+ while remaining:
+ block = os.urandom(min(MIB, remaining))
+ stream.write(block)
+ digest.update(block)
+ remaining -= len(block)
+ records[relative] = {"bytes": size, "sha256": digest.hexdigest()}
+ manifest = {"version": 1, "fixture": name, "files": records}
+ write_json(workspace / "manifest.json", manifest)
+ return manifest
+
+
+def load_manifest(workspace):
+ with (workspace / "manifest.json").open("rb") as stream:
+ encoded = stream.read(2 * MIB + 1)
+ if len(encoded) > 2 * MIB:
+ raise ValueError("Manifest exceeds 2 MiB")
+ manifest = json.loads(encoded)
+ if not isinstance(manifest, dict) or manifest.get("version") != 1:
+ raise ValueError("Unsupported manifest")
+ if not re.fullmatch(r"SocketSweep-benchmark-[0-9a-f]{32}", str(manifest.get("fixture"))):
+ raise ValueError("Invalid fixture name")
+ files = manifest.get("files")
+ if not isinstance(files, dict) or not 2 <= len(files) <= 5001:
+ raise ValueError("Invalid file count")
+ for path, entry in files.items():
+ if not re.fullmatch(r"(?:large|small)/file-[0-9]{6}\.bin", path):
+ raise ValueError("Invalid fixture path")
+ if not isinstance(entry, dict):
+ raise ValueError("Invalid file record")
+ size = entry.get("bytes")
+ if type(size) is not int or not 1 <= size <= 1024 * MIB:
+ raise ValueError("Invalid file size")
+ if not re.fullmatch(r"[0-9a-f]{64}", str(entry.get("sha256"))):
+ raise ValueError("Invalid SHA-256")
+ large = {path for path in files if path.startswith("large/")}
+ small = sorted(path for path in files if path.startswith("small/"))
+ if (large != {"large/file-000000.bin"} or not small or
+ small != [f"small/file-{i:06d}.bin" for i in range(len(small))] or
+ any(files[path]["bytes"] != 4096 for path in small)):
+ raise ValueError("Invalid workload layout")
+ return manifest
+
+
+def verify_copy(manifest, workload, copy):
+ """Require exact contents, regular files only, and matching sizes/hashes."""
+ if workload not in WORKLOADS:
+ raise ValueError("Unknown workload")
+ if copy.is_symlink() or not copy.is_dir():
+ raise ValueError("Copy must be a real workload directory")
+ expected = {path.split("/", 1)[1]: entry for path, entry in manifest["files"].items()
+ if path.startswith(workload + "/")}
+ if {path.name for path in copy.iterdir()} != set(expected):
+ raise ValueError("Copy has missing or unexpected entries")
+ total = 0
+ for name, entry in expected.items():
+ path = copy / name
+ info = path.lstat()
+ if not stat.S_ISREG(info.st_mode) or info.st_size != entry["bytes"]:
+ raise ValueError(f"Wrong file type or size: {name}")
+ digest = hashlib.sha256()
+ with path.open("rb") as stream:
+ for block in iter(lambda: stream.read(MIB), b""):
+ digest.update(block)
+ if digest.hexdigest() != entry["sha256"]:
+ raise ValueError(f"SHA-256 mismatch: {name}")
+ total += info.st_size
+ return len(expected), total
+
+
+def result(manifest, workload, copy, seconds, backend, compression):
+ if not math.isfinite(seconds) or seconds <= 0:
+ raise ValueError("Transfer seconds must be finite and positive")
+ start = time.perf_counter()
+ count, size = verify_copy(manifest, workload, copy)
+ return {"fixture": manifest["fixture"], "workload": workload,
+ "backend": backend, "compression": compression, "verified": True,
+ "files": count, "bytes": size, "transfer_seconds": seconds,
+ "verification_seconds": time.perf_counter() - start,
+ "mib_per_second": size / MIB / seconds}
+
+
+def pull(workspace, serial, workload, output, compression="none", adb="adb"):
+ manifest = load_manifest(workspace)
+ if workload not in WORKLOADS or compression not in ("none", "any"):
+ raise ValueError("Invalid workload or compression")
+ if not serial or serial.strip() != serial or any(ord(c) < 33 for c in serial):
+ raise ValueError("An explicit device serial is required")
+ # Check that the local reference still agrees with its manifest before
+ # contacting the device. This read is outside the timed transfer.
+ verify_copy(manifest, workload, workspace / manifest["fixture"] / workload)
+ output.mkdir()
+ payload = output / "payload"
+ payload.mkdir()
+ remote = f"/sdcard/Download/{manifest['fixture']}/{workload}"
+ command = [adb, "-s", serial, "pull"]
+ command += ["-Z"] if compression == "none" else ["-z", "any"]
+ command += [remote, str(payload.resolve())]
+ start = time.perf_counter()
+ # Inherit progress/errors: no unbounded captured output or shell quoting.
+ # subprocess.run kills and waits for its client on timeout/interrupt.
+ subprocess.run(command, check=True, timeout=600, stdin=subprocess.DEVNULL)
+ seconds = time.perf_counter() - start
+ report = result(manifest, workload, payload / workload, seconds, "adb", compression)
+ write_json(output / "result.json", report)
+ return report
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest="command", required=True)
+ make = commands.add_parser("prepare", help="Create new local random fixtures; no ADB")
+ make.add_argument("workspace", type=Path)
+ make.add_argument("--large-mib", type=int, default=64)
+ make.add_argument("--small-count", type=int, default=1000)
+ download = commands.add_parser("pull", help="Download one staged fixture using ADB")
+ download.add_argument("workspace", type=Path)
+ download.add_argument("--serial", required=True)
+ download.add_argument("--workload", choices=WORKLOADS, required=True)
+ download.add_argument("--output", type=Path, required=True, help="New directory; parent must exist")
+ download.add_argument("--compression", choices=("none", "any"), default="none")
+ download.add_argument("--adb", default="adb", help="ADB executable path")
+ check = commands.add_parser("verify", help="Verify a manually copied workload; no ADB")
+ check.add_argument("workspace", type=Path)
+ check.add_argument("--workload", choices=WORKLOADS, required=True)
+ check.add_argument("--copy", type=Path, required=True, help="Copied large/ or small/ directory")
+ check.add_argument("--seconds", type=float, required=True, help="Manually measured copy duration")
+ check.add_argument("--backend", choices=("mtp", "local-control"), required=True)
+ args = parser.parse_args()
+ try:
+ if args.command == "prepare":
+ report = prepare(args.workspace, args.large_mib, args.small_count)
+ report = {"fixture": report["fixture"], "files": len(report["files"]),
+ "bytes": sum(entry["bytes"] for entry in report["files"].values())}
+ elif args.command == "pull":
+ report = pull(args.workspace, args.serial, args.workload, args.output,
+ args.compression, args.adb)
+ else:
+ report = result(load_manifest(args.workspace), args.workload, args.copy,
+ args.seconds, args.backend, "not-controlled")
+ print(json.dumps(report, indent=2, allow_nan=False))
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
+ parser.exit(1, f"Benchmark failed: {error}\nNo verified result was recorded.\n")
+ except KeyboardInterrupt:
+ parser.exit(130, "Benchmark cancelled. No verified result was recorded.\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_transfer_benchmark.py b/tests/test_transfer_benchmark.py
new file mode 100644
index 0000000..3480be8
--- /dev/null
+++ b/tests/test_transfer_benchmark.py
@@ -0,0 +1,181 @@
+"""Offline transfer-fixture tests. ADB calls are mocked; no device is used."""
+import copy
+import json
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import benchmark_transfer as benchmark
+
+
+class TransferBenchmarkTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.workspace = self.root / "fixture"
+ self.manifest = benchmark.prepare(self.workspace, large_mib=1, small_count=3)
+ self.source = self.workspace / self.manifest["fixture"]
+ self.output = self.root / "run"
+
+ def test_generated_workloads_match_and_do_not_overwrite(self):
+ self.assertEqual(benchmark.load_manifest(self.workspace), self.manifest)
+ self.assertEqual(benchmark.verify_copy(self.manifest, "large", self.source / "large"),
+ (1, benchmark.MIB))
+ self.assertEqual(benchmark.verify_copy(self.manifest, "small", self.source / "small"),
+ (3, 3 * 4096))
+ with self.assertRaises(FileExistsError):
+ benchmark.prepare(self.workspace, 1, 3)
+ self.assertEqual(benchmark.load_manifest(self.workspace), self.manifest)
+
+ def test_bounds_rejected_before_creating_workspace(self):
+ for large, small in [(0, 1), (1025, 1), (1, 0), (1, 5001)]:
+ with self.assertRaises(ValueError):
+ benchmark.prepare(self.root / "absent", large, small)
+ self.assertFalse((self.root / "absent").exists())
+
+ def test_corruption_missing_extra_directory_and_symlink_are_rejected(self):
+ target = self.root / "copy"
+ for change in ("hash", "size", "missing", "extra", "directory", "symlink"):
+ with self.subTest(change=change):
+ shutil.copytree(self.source / "small", target)
+ path = target / "file-000000.bin"
+ if change == "hash":
+ with path.open("r+b") as stream:
+ first = stream.read(1)
+ stream.seek(0)
+ stream.write(bytes([first[0] ^ 1]))
+ elif change == "size":
+ path.write_bytes(b"short")
+ elif change == "missing":
+ path.unlink()
+ elif change == "extra":
+ (target / "unexpected").touch()
+ elif change == "directory":
+ path.unlink()
+ path.mkdir()
+ else:
+ path.unlink()
+ try:
+ path.symlink_to(self.source / "small" / path.name)
+ except OSError:
+ shutil.rmtree(target)
+ continue # Some Windows environments deny symlink creation.
+ with self.assertRaises(ValueError):
+ benchmark.verify_copy(self.manifest, "small", target)
+ shutil.rmtree(target)
+
+ def test_manifest_rejects_traversal_bad_hash_size_and_layout(self):
+ for change in ("traversal", "absolute", "fixture", "hash", "size", "empty", "layout"):
+ manifest = copy.deepcopy(self.manifest)
+ files = manifest["files"]
+ if change in ("traversal", "absolute"):
+ files["../escape" if change == "traversal" else "/escape"] = files.pop("large/file-000000.bin")
+ elif change == "fixture":
+ manifest["fixture"] = "../escape"
+ elif change == "hash":
+ files["large/file-000000.bin"]["sha256"] = "not-a-hash"
+ elif change == "size":
+ files["large/file-000000.bin"]["bytes"] = True
+ elif change == "empty":
+ manifest["files"] = {}
+ else:
+ del files["small/file-000001.bin"]
+ (self.workspace / "manifest.json").write_text(json.dumps(manifest))
+ with self.subTest(change=change), self.assertRaises(ValueError):
+ benchmark.load_manifest(self.workspace)
+
+ def fake_copy(self, command, **kwargs):
+ workload = command[-2].rsplit("/", 1)[1]
+ shutil.copytree(self.source / workload, Path(command[-1]) / workload)
+ self.assertTrue(kwargs["check"])
+ self.assertEqual(kwargs["timeout"], 600)
+ self.assertEqual(kwargs["stdin"], subprocess.DEVNULL)
+
+ def test_pull_pins_device_and_compression_and_writes_verified_report(self):
+ for compression, flags in (("none", ["-Z"]), ("any", ["-z", "any"])):
+ output = self.root / compression
+ with patch.object(benchmark.subprocess, "run", side_effect=self.fake_copy) as run, \
+ patch.object(benchmark.time, "perf_counter", side_effect=[100, 102, 200, 203]):
+ report = benchmark.pull(self.workspace, "phone:1234", "small", output,
+ compression, "adb with spaces")
+ command = run.call_args.args[0]
+ self.assertEqual(command[:4], ["adb with spaces", "-s", "phone:1234", "pull"])
+ self.assertEqual(command[4:-2], flags)
+ self.assertEqual(command[-2], f"/sdcard/Download/{self.manifest['fixture']}/small")
+ self.assertTrue(report["verified"])
+ self.assertEqual(report["bytes"], 12288)
+ self.assertEqual(report["transfer_seconds"], 2)
+ self.assertEqual(report["verification_seconds"], 3)
+ self.assertNotIn("phone:1234", json.dumps(report))
+ self.assertEqual(json.loads((output / "result.json").read_text()), report)
+
+ def test_oversized_manifest_and_symlink_copy_root_are_rejected(self):
+ (self.workspace / "manifest.json").write_bytes(b" " * (2 * benchmark.MIB + 1))
+ with self.assertRaisesRegex(ValueError, "exceeds"):
+ benchmark.load_manifest(self.workspace)
+ link = self.root / "link"
+ try:
+ link.symlink_to(self.source / "small", target_is_directory=True)
+ except OSError:
+ self.skipTest("Symlink creation unavailable")
+ with self.assertRaisesRegex(ValueError, "real workload directory"):
+ benchmark.verify_copy(self.manifest, "small", link)
+
+ def test_failed_timed_out_cancelled_or_corrupt_pull_has_no_success_report(self):
+ failures = [subprocess.CalledProcessError(1, "fake-adb"),
+ subprocess.TimeoutExpired("fake-adb", 600), KeyboardInterrupt()]
+ for index, error in enumerate(failures):
+ output = self.root / f"failed-{index}"
+ with patch.object(benchmark.subprocess, "run", side_effect=error):
+ with self.assertRaises(type(error)):
+ benchmark.pull(self.workspace, "device", "small", output)
+ self.assertFalse((output / "result.json").exists())
+ with patch.object(benchmark.subprocess, "run"):
+ with self.assertRaises(ValueError):
+ benchmark.pull(self.workspace, "device", "small", self.output)
+ self.assertFalse((self.output / "result.json").exists())
+
+ def test_bad_serial_existing_destination_or_corrupt_source_never_calls_adb(self):
+ with patch.object(benchmark.subprocess, "run") as run:
+ for serial in ("", " device", "device\n", "dev\x00ice"):
+ with self.assertRaises(ValueError):
+ benchmark.pull(self.workspace, serial, "small", self.output)
+ self.output.mkdir()
+ sentinel = self.output / "keep"
+ sentinel.write_text("keep")
+ with self.assertRaises(FileExistsError):
+ benchmark.pull(self.workspace, "device", "small", self.output)
+ self.assertEqual(sentinel.read_text(), "keep")
+ (self.source / "small" / "file-000000.bin").write_bytes(b"broken")
+ with self.assertRaises(ValueError):
+ benchmark.pull(self.workspace, "device", "small", self.root / "unused")
+ run.assert_not_called()
+
+ def test_manual_timing_reports_only_verified_bytes_and_finite_positive_time(self):
+ for seconds in (0, -1, float("nan"), float("inf")):
+ with self.assertRaises(ValueError):
+ benchmark.result(self.manifest, "large", self.source / "large", seconds, "mtp", "unknown")
+ report = benchmark.result(self.manifest, "large", self.source / "large", 2, "mtp", "unknown")
+ self.assertEqual(report["mib_per_second"], 0.5)
+
+ def test_offline_cli_verification_success_and_failure(self):
+ command = [sys.executable, str(Path(benchmark.__file__)), "verify", str(self.workspace),
+ "--workload", "small", "--copy", str(self.source / "small"),
+ "--seconds", "1", "--backend", "local-control"]
+ completed = subprocess.run(command, capture_output=True, text=True, timeout=10)
+ self.assertEqual(completed.returncode, 0, completed.stderr)
+ self.assertTrue(json.loads(completed.stdout)["verified"])
+ (self.source / "small" / "file-000000.bin").unlink()
+ completed = subprocess.run(command, capture_output=True, text=True, timeout=10)
+ self.assertEqual(completed.returncode, 1)
+ self.assertEqual(completed.stdout, "")
+ self.assertIn("No verified result", completed.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()