Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add push to dir support, close #101 #117

Merged
merged 1 commit into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion adbutils/_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@
@deprecated(deprecated_in="2.6.0", removed_in="3.0.0", current_version=__version__, details="use sync.push instead")
def push(self, local: str, remote: str):
""" alias for sync.push """
self.sync.push(local, remote)
return self.sync.push(local, remote)

Check warning on line 345 in adbutils/_device.py

View check run for this annotation

Codecov / codecov/patch

adbutils/_device.py#L345

Added line #L345 was not covered by tests

def create_connection(
self, network: Network, address: Union[int, str]
Expand Down
6 changes: 5 additions & 1 deletion adbutils/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,8 @@
self.output = output

def __str__(self):
return self.output
return self.output

Check warning on line 38 in adbutils/errors.py

View check run for this annotation

Codecov / codecov/patch

adbutils/errors.py#L38

Added line #L38 was not covered by tests


class AdbSyncError(AdbError):
""" sync error """
38 changes: 32 additions & 6 deletions adbutils/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""


import logging
import struct
import datetime
import typing
Expand All @@ -17,8 +18,9 @@
from adbutils._adb import BaseClient, AdbError
from adbutils._proto import FileInfo
from adbutils._utils import append_path
from adbutils.errors import AdbSyncError


logger = logging.getLogger(__name__)

_OKAY = "OKAY"
_FAIL = "FAIL"
Expand Down Expand Up @@ -80,10 +82,36 @@
def list(self, path: str) -> typing.List[str]:
return list(self.iter_directory(path))

def push(
def push(self, src: typing.Union[pathlib.Path, str, bytes, bytearray, typing.BinaryIO],
dst: typing.Union[pathlib.Path, str],
mode: int = 0o755,
check: bool = False) -> int:
"""
Push file from local:src to device:dst

Args:
src: source file path
dst: destination file path or directory path
mode: file mode
check: check if push size is correct

Returns:
total file size pushed
"""
if isinstance(dst, pathlib.Path):
dst = dst.as_posix()
finfo = self.stat(dst)

Check warning on line 103 in adbutils/sync.py

View check run for this annotation

Codecov / codecov/patch

adbutils/sync.py#L102-L103

Added lines #L102 - L103 were not covered by tests
if finfo.mode & stat.S_IFDIR != 0:
if not isinstance(src, (pathlib.Path, str)):
raise AdbSyncError("src should be a file path when dst is a directory")
dst = append_path(dst, pathlib.Path(src).name)
logger.debug("dst is a directory, update dst to %s", dst)
return self._push_file(src, dst, mode, check)

Check warning on line 109 in adbutils/sync.py

View check run for this annotation

Codecov / codecov/patch

adbutils/sync.py#L106-L109

Added lines #L106 - L109 were not covered by tests

def _push_file(
self,
src: typing.Union[pathlib.Path, str, bytes, bytearray, typing.BinaryIO],
dst: typing.Union[pathlib.Path, str],
dst: str,
mode: int = 0o755,
check: bool = False) -> int: # yapf: disable
# IFREG: File Regular
Expand All @@ -98,15 +126,13 @@
if not hasattr(src, "read"):
raise TypeError("Invalid src type: %s" % type(src))

if isinstance(dst, pathlib.Path):
dst = dst.as_posix()
path = dst + "," + str(stat.S_IFREG | mode)
total_size = 0
with self._prepare_sync(path, "SEND") as c:
r = src if hasattr(src, "read") else open(src, "rb")
try:
while True:
chunk = r.read(4096)
chunk = r.read(4096) # should not >64k

Check warning on line 135 in adbutils/sync.py

View check run for this annotation

Codecov / codecov/patch

adbutils/sync.py#L135

Added line #L135 was not covered by tests
if not chunk:
mtime = int(datetime.datetime.now().timestamp())
c.conn.send(b"DONE" + struct.pack("<I", mtime))
Expand Down
9 changes: 9 additions & 0 deletions test_real_device/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ def device_tmp_path(device: AdbDevice):
yield tmp_path
device.remove(tmp_path)


@pytest.fixture
def device_tmp_dir(device: AdbDevice):
tmp_path = "/data/local/tmp/adbutils-test"
device.shell("mkdir -p {}".format(tmp_path))
yield tmp_path
device.rmtree(tmp_path)


@pytest.fixture
def device_tmp_dir_path(device: AdbDevice):
tmp_dir_path = "/sdcard/test_d"
Expand Down
17 changes: 16 additions & 1 deletion test_real_device/test_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
import re
import time
import filecmp
import uuid

import pytest

import adbutils
from adbutils import AdbDevice, Network
from adbutils.errors import AdbSyncError


def test_shell(device: AdbDevice):
Expand Down Expand Up @@ -168,6 +170,17 @@ def test_sync_pull_file_push(device: AdbDevice, device_tmp_path, tmp_path: pathl
assert b"Hello Android" == data


def test_sync_push_to_dir(device: AdbDevice, device_tmp_dir, tmp_path: pathlib.Path):
random_data = str(uuid.uuid4()).encode()
src = io.BytesIO(random_data)
with pytest.raises(AdbSyncError):
device.sync.push(src, device_tmp_dir)
src_path = tmp_path.joinpath("random.txt")
src_path.write_bytes(random_data)
assert device.sync.push(src_path, device_tmp_dir) == len(random_data)
assert random_data == device.sync.read_bytes(device_tmp_dir + "/random.txt")


def test_screenshot(device: AdbDevice):
im = device.screenshot()
assert im.mode == "RGB"
Expand Down Expand Up @@ -269,7 +282,9 @@ def are_dir_trees_equal(dir1, dir2):
local_src_out_dir1 = tmp_path / 'dir1'
local_src_out_dir2 = tmp_path / 'dir2'

device.push(local_src_in_dir, device_tmp_dir_path)
# TODO: push src support dir
# device.push(local_src_in_dir, device_tmp_dir_path)
device.adb_output("push", str(local_src_in_dir), device_tmp_dir_path)

device.sync.pull_dir(device_tmp_dir_path, local_src_out_dir1)

Expand Down
Loading