Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

tools: a failed tv.py --pull leaves the local file as it was

Jernej Pangersic54db366ef8c3
diff --git a/tests/test_tv_pull_failure.py b/tests/test_tv_pull_failure.py
new file mode 100644
index 000000000..d47117eb3
--- /dev/null
+++ b/tests/test_tv_pull_failure.py
@@ -0,0 +1,178 @@
+"""tools/tv.py --pull leaves the local file as it was when the pull fails.
+
+adb_shell 0.4.4 opens the local path for writing before it asks the TV for the file, so a pull of a path
+the TV does not have (AdbCommandFailureException: "No such file or directory") or one the TV dropped
+halfway truncated the file that was already there to 0 bytes, or left a 0-byte file where there was
+none, and then ended in a traceback. A `--pull /sdcard/notes.txt work/notes.txt` with a typo in the
+remote path cost the reader the copy they had.
+
+The pull now goes into a file of its own beside the target, which replaces the target only once the
+pull is done; a failed pull removes it, says what failed in words and exits 1. The runs here use a stub
+adb_shell (as tests/test_tv_transfer_paths.py does) that opens the local file the way the library does
+and then fails the way the library does.
+
+Run from the repository root: python3 -m unittest discover -s tests -v
+"""
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRIPT = ROOT / "tools" / "tv.py"
+STUB_EXCEPTIONS = '''\
+class AdbCommandFailureException(Exception):
+ pass
+
+
+class AdbConnectionError(Exception):
+ pass
+
+
+class AdbTimeoutError(Exception):
+ pass
+
+
+class InvalidCommandError(Exception):
+ pass
+
+
+class TcpTimeoutException(Exception):
+ pass
+'''
+STUB_DEVICE = '''\
+import os
+
+from adb_shell.exceptions import AdbCommandFailureException
+
+
+class AdbDeviceTcp:
+ """Pulls the way adb_shell 0.4.4 does: the local file is opened for writing first, then the TV is
+ asked. STUB_PULL picks the TV's answer: ok, missing (no such file), drop (the connection resets
+ after part of the file) or bug (an error that is not the TV's)."""
+
+ def __init__(self, host, port, **kwargs):
+ pass
+
+ def connect(self, **kwargs):
+ pass
+
+ def pull(self, remote, local, **kwargs):
+ with open(local, "wb") as stream:
+ how = os.environ.get("STUB_PULL", "ok")
+ if how == "missing":
+ raise AdbCommandFailureException("Command failed: No such file or directory")
+ if how == "drop":
+ stream.write(b"half of the")
+ raise ConnectionResetError(104, "Connection reset by peer")
+ if how == "bug":
+ raise RuntimeError("a bug in the client")
+ stream.write(b"new contents from the TV")
+
+ def shell(self, command, **kwargs):
+ return ""
+
+ def close(self):
+ pass
+'''
+STUB_KEYGEN = "def keygen(path):\n pass\n"
+STUB_SIGNER = "class PythonRSASigner:\n def __init__(self, pub, priv):\n pass\n"
+OLD = b"the copy that was already here"
+
+
+class PullFailureTest(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls._tmp = tempfile.TemporaryDirectory()
+ base = Path(cls._tmp.name) / "stub"
+ (base / "adb_shell" / "auth").mkdir(parents=True)
+ (base / "adb_shell" / "__init__.py").write_text("", encoding="utf-8")
+ (base / "adb_shell" / "exceptions.py").write_text(STUB_EXCEPTIONS, encoding="utf-8")
+ (base / "adb_shell" / "adb_device.py").write_text(STUB_DEVICE, encoding="utf-8")
+ (base / "adb_shell" / "auth" / "__init__.py").write_text("", encoding="utf-8")
+ (base / "adb_shell" / "auth" / "keygen.py").write_text(STUB_KEYGEN, encoding="utf-8")
+ (base / "adb_shell" / "auth" / "sign_pythonrsa.py").write_text(STUB_SIGNER, encoding="utf-8")
+ cls.base = base
+ # A stock ADB key in the temporary HOME, so neither tools/adbkey nor the real ~/.android is used.
+ home = Path(cls._tmp.name) / "home"
+ (home / ".android").mkdir(parents=True)
+ (home / ".android" / "adbkey").write_text("PRIVATE", encoding="utf-8")
+ (home / ".android" / "adbkey.pub").write_text("PUBLIC", encoding="utf-8")
+ cls.home = home
+
+ @classmethod
+ def tearDownClass(cls):
+ cls._tmp.cleanup()
+
+ def setUp(self):
+ self.folder = Path(tempfile.mkdtemp(dir=self._tmp.name))
+ self.target = self.folder / "notes.txt"
+
+ def run_pull(self, how):
+ env = {k: v for k, v in os.environ.items() if k not in ("TV_HOST", "TV_PORT", "PYTHONPATH",
+ "TV_ADB_BINARY")}
+ env["HOME"] = str(self.home)
+ if os.name == "nt":
+ env["USERPROFILE"] = str(self.home)
+ env["PYTHONPATH"] = str(self.base)
+ env["TV_HOST"] = "192.0.2.1" # TEST-NET-1: the stub answers, so no socket is opened
+ env["STUB_PULL"] = how
+ return subprocess.run([sys.executable, str(SCRIPT), "--pull", "/sdcard/notes.txt", str(self.target)],
+ cwd=str(ROOT), env=env, capture_output=True, text=True)
+
+ def assertFailedInWords(self, r):
+ self.assertEqual(1, r.returncode, r.stderr)
+ self.assertNotIn("Traceback", r.stderr)
+ self.assertIn("/sdcard/notes.txt", r.stderr)
+ self.assertNotIn("pulled", r.stdout)
+
+ def test_a_missing_file_on_the_tv_leaves_the_local_copy_as_it_was(self):
+ self.target.write_bytes(OLD)
+ r = self.run_pull("missing")
+ self.assertFailedInWords(r)
+ self.assertIn("No such file or directory", r.stderr)
+ self.assertIn(f"{self.target} was left as it was", r.stderr)
+ self.assertEqual(OLD, self.target.read_bytes(), "a failed pull must not empty the file that was there")
+ self.assertEqual(["notes.txt"], os.listdir(self.folder), "nothing is left beside it")
+
+ def test_a_missing_file_on_the_tv_leaves_no_empty_file_behind(self):
+ r = self.run_pull("missing")
+ self.assertFailedInWords(r)
+ self.assertIn(f"{self.target} was not written", r.stderr)
+ self.assertEqual([], os.listdir(self.folder), "a failed pull must not leave a 0-byte file")
+
+ def test_a_dropped_connection_leaves_the_local_copy_as_it_was(self):
+ self.target.write_bytes(OLD)
+ r = self.run_pull("drop")
+ self.assertFailedInWords(r)
+ self.assertIn("ConnectionResetError", r.stderr)
+ self.assertEqual(OLD, self.target.read_bytes(), "half a file must not replace the whole one")
+ self.assertEqual(["notes.txt"], os.listdir(self.folder))
+
+ def test_an_error_that_is_not_the_tvs_keeps_its_traceback_and_the_file(self):
+ self.target.write_bytes(OLD)
+ r = self.run_pull("bug")
+ self.assertNotEqual(0, r.returncode)
+ self.assertIn("Traceback", r.stderr, "a bug in the client shows where it is")
+ self.assertEqual(OLD, self.target.read_bytes())
+ self.assertEqual(["notes.txt"], os.listdir(self.folder))
+
+ def test_a_pull_that_works_replaces_the_file(self):
+ self.target.write_bytes(OLD)
+ r = self.run_pull("ok")
+ self.assertEqual(0, r.returncode, r.stderr)
+ self.assertIn(f"pulled /sdcard/notes.txt -> {self.target}", r.stdout)
+ self.assertEqual(b"new contents from the TV", self.target.read_bytes())
+ self.assertEqual(["notes.txt"], os.listdir(self.folder))
+
+ def test_a_pull_that_works_writes_a_new_file(self):
+ r = self.run_pull("ok")
+ self.assertEqual(0, r.returncode, r.stderr)
+ self.assertEqual(b"new contents from the TV", self.target.read_bytes())
+ self.assertEqual(["notes.txt"], os.listdir(self.folder))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_tv_transfer_paths.py b/tests/test_tv_transfer_paths.py
index 25eb569cb..b02e2c4ad 100644
--- a/tests/test_tv_transfer_paths.py
+++ b/tests/test_tv_transfer_paths.py
@@ -225,8 +225,12 @@ class TransferPathsTest(unittest.TestCase):
status, out, err, opened, sent = self.run_tv(["--pull", "/sdcard/s.png", str(target)])
self.assertEqual(0, status, err)
self.assertEqual("192.0.2.1:5555", opened)
- self.assertEqual([f"pull /sdcard/s.png -> {target}"], sent)
+ self.assertEqual(1, len(sent), sent)
+ # The pull goes into a file of its own beside the target, which replaces it once the pull is done
+ # (tests/test_tv_pull_failure.py).
+ self.assertTrue(sent[0].startswith(f"pull /sdcard/s.png -> {target.parent}"), sent)
self.assertTrue(target.exists(), "the stub wrote the file where the run was told to")
+ self.assertEqual(["s.png"], os.listdir(target.parent))
def test_the_judgement_runs_before_the_connection_is_made(self):
source = SCRIPT.read_text(encoding="utf-8")
diff --git a/tools/tv.py b/tools/tv.py
index 3ca9f3099..6fc0de5e2 100755
--- a/tools/tv.py
+++ b/tools/tv.py
@@ -13,7 +13,8 @@ Set TV_HOST to the TV's IP (or IP:port). Usage:
tv.py --help this text; needs neither the venv nor a TV
Exit status: 0 the command ran (the TV's own answer is in its output), 1 the screenshot came back
-empty or failed, or a command's answer was lost when the TV dropped the connection,
+empty or failed, a pull the TV did not send (the local file is left as it was), or a command's answer
+was lost when the TV dropped the connection,
2 it was refused before anything ran on the TV - a flag it does not have, one of its own with the wrong
number of words, a local path that cannot be used, a port it could not open, or a TV_HOST that is a URL
or a path instead of the TV's address. A flag and its count are
@@ -25,6 +26,7 @@ Set TV_ADB_BINARY to the Google adb executable to use an already connected, pair
import errno
import os
import re
+import shutil
import subprocess
import sys
import time
@@ -636,6 +638,39 @@ def screenshot(dev, local, keys=(), wait=0.0):
return 0
+def pull(dev, remote, local):
+ """Pull `remote` into `local`, which is replaced only once the whole file has come back. Returns 0,
+ or 1 when the TV did not send the file.
+
+ adb_shell opens the local path for writing before it asks the TV for the file, so a path the TV does
+ not have, or a connection that dropped halfway, emptied the copy that was there (or left a 0-byte
+ file where there was none) and then ended in a traceback. The pull goes into a file of its own in
+ the same folder, so the os.replace() that puts it in place stays on one filesystem."""
+ folder, name = os.path.split(os.path.abspath(local))
+ part = os.path.join(folder, f".{name}.{os.getpid()}.part")
+ try:
+ dev.pull(remote, part, transport_timeout_s=300.0, read_timeout_s=300.0)
+ if os.path.exists(local):
+ shutil.copymode(local, part)
+ os.replace(part, local)
+ except Exception as e:
+ try:
+ os.remove(part)
+ except OSError:
+ pass
+ # Imported here, as lost_connection() does, so a stub adb_shell without exceptions still loads.
+ from adb_shell.exceptions import (AdbCommandFailureException, AdbConnectionError, AdbTimeoutError,
+ TcpTimeoutException)
+ if not isinstance(e, (OSError, NativeAdbError, AdbCommandFailureException, AdbConnectionError,
+ AdbTimeoutError, TcpTimeoutException)):
+ raise
+ kept = "was left as it was" if os.path.exists(local) else "was not written"
+ print(f"could not pull {remote}: {type(e).__name__}: {e}\n{local} {kept}.", file=sys.stderr)
+ return 1
+ print(f"pulled {remote} -> {local}")
+ return 0
+
+
def main():
args = sys.argv[1:]
check_arity(args)
@@ -668,8 +703,7 @@ def main():
dev.push(args[1], args[2], transport_timeout_s=300.0, read_timeout_s=300.0)
print(f"pushed {args[1]} -> {args[2]}")
elif args[0] == "--pull" and len(args) == 3:
- dev.pull(args[1], args[2], transport_timeout_s=300.0, read_timeout_s=300.0)
- print(f"pulled {args[1]} -> {args[2]}")
+ status = pull(dev, args[1], args[2])
elif args[0] == "--batch":
# one shell command per stdin line, each run separately on the same connection.
# utf-8-sig drops the BOM Windows PowerShell may prepend to piped stdin.