Skip to content

Commit dfcd2fb

Browse files
committed
feat: invoke with exception
1 parent 80695fc commit dfcd2fb

File tree

6 files changed

+46
-24
lines changed

6 files changed

+46
-24
lines changed

hmdriver2/_client.py

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,18 @@
66
import os
77
import typing
88
import subprocess
9-
import atexit
109
import hashlib
1110
from datetime import datetime
1211
from functools import cached_property
1312

1413
from . import logger
1514
from .hdc import HdcWrapper
1615
from .proto import HypiumResponse, DriverData
16+
from .exception import InvokeHypiumError
1717

1818

19-
UITEST_SERICE_PORT = 8012
20-
SOCKET_TIMEOUT = 60
19+
UITEST_SERVICE_PORT = 8012
20+
SOCKET_TIMEOUT = 30
2121

2222

2323
class HMClient:
@@ -35,11 +35,11 @@ def local_port(self):
3535
fports = self.hdc.list_fport()
3636
logger.debug(fports) if fports else None
3737

38-
return self.hdc.forward_port(UITEST_SERICE_PORT)
38+
return self.hdc.forward_port(UITEST_SERVICE_PORT)
3939

4040
def _rm_local_port(self):
4141
logger.debug("rm fport local port")
42-
self.hdc.rm_forward(self.local_port, UITEST_SERICE_PORT)
42+
self.hdc.rm_forward(self.local_port, UITEST_SERVICE_PORT)
4343

4444
def _connect_sock(self):
4545
"""Create socket and connect to the uiTEST server."""
@@ -81,6 +81,20 @@ def _recv_msg(self, buff_size: int = 1024, decode=False) -> typing.Union[bytearr
8181
return bytearray()
8282

8383
def invoke(self, api: str, this: str = "Driver#0", args: typing.List = []) -> HypiumResponse:
84+
"""
85+
Invokes a given API method with the specified arguments and handles exceptions.
86+
87+
Args:
88+
api (str): The name of the API method to invoke.
89+
args (List, optional): A list of arguments to pass to the API method. Default is an empty list.
90+
91+
Returns:
92+
HypiumResponse: The response from the API call.
93+
94+
Raises:
95+
InvokeHypiumError: If the API call returns an exception in the response.
96+
"""
97+
8498
msg = {
8599
"module": "com.ohos.devicetest.hypiumApiHelper",
86100
"method": "callHypiumApi",
@@ -93,11 +107,11 @@ def invoke(self, api: str, this: str = "Driver#0", args: typing.List = []) -> Hy
93107
"request_id": datetime.now().strftime("%Y%m%d%H%M%S%f")
94108
}
95109
self._send_msg(msg)
96-
result = self._recv_msg(decode=True)
97-
# TODO handle exception
98-
# {"exception":{"code":401,"message":"(PreProcessing: APiCallInfoChecker)Illegal argument count"}}
99-
100-
return HypiumResponse(**(json.loads(result)))
110+
raw_data = self._recv_msg(decode=True)
111+
data = HypiumResponse(**(json.loads(raw_data)))
112+
if data.exception:
113+
raise InvokeHypiumError(data.exception)
114+
return data
101115

102116
def start(self):
103117
logger.info("Start client connection")

hmdriver2/_toast.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55

66
class ToastWatcher:
7-
def __init__(self, session: "Driver"): # type: ignore
8-
self.session = session
7+
def __init__(self, driver: "Driver"): # type: ignore
8+
self.driver = driver
99

1010
def start(self) -> bool:
1111
"""
@@ -15,10 +15,10 @@ def start(self) -> bool:
1515
bool: True if the observer starts successfully, else False.
1616
"""
1717
api = "Driver.uiEventObserverOnce"
18-
resp: HypiumResponse = self.session._invoke(api, args=["toastShow"])
18+
resp: HypiumResponse = self.driver._invoke(api, args=["toastShow"])
1919
return resp.result
2020

21-
def get(self, timeout: int = 5) -> str:
21+
def get(self, timeout: int = 3) -> str:
2222
"""
2323
Read the latest toast message content from the recent period.
2424
@@ -29,7 +29,7 @@ def get(self, timeout: int = 5) -> str:
2929
str: The content of the latest toast message.
3030
"""
3131
api = "Driver.getRecentUiEvent"
32-
resp: HypiumResponse = self.session._invoke(api, args=[timeout])
32+
resp: HypiumResponse = self.driver._invoke(api, args=[timeout])
3333
if resp.result:
3434
return resp.result.get("text")
3535
return None

hmdriver2/driver.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010
except ImportError:
1111
from cached_property import cached_property
1212

13-
from .exception import DeviceNotFoundError
1413
from ._client import HMClient
1514
from ._uiobject import UiObject
1615
from .hdc import list_devices
1716
from ._toast import ToastWatcher
17+
from .exception import DeviceNotFoundError
1818
from .proto import HypiumResponse, KeyCode, Point, DisplayRotation, DeviceInfo
1919

2020

@@ -50,6 +50,9 @@ def _is_device_online(self):
5050
_serials = list_devices()
5151
return True if self.serial in _serials else False
5252

53+
def _invoke(self, api: str, args: List = []) -> HypiumResponse:
54+
return self._client.invoke(api, this=self._this_driver, args=args)
55+
5356
def start_app(self, package_name: str, page_name: str = "MainAbility"):
5457
self.unlock()
5558
self.hdc.start_app(package_name, page_name)
@@ -103,9 +106,6 @@ def unlock(self):
103106
self.hdc.swipe(0.5 * w, 0.8 * h, 0.5 * w, 0.2 * h)
104107
time.sleep(.5)
105108

106-
def _invoke(self, api: str, args: List = []) -> HypiumResponse:
107-
return self._client.invoke(api, this=self._this_driver, args=args)
108-
109109
@cached_property
110110
def display_size(self) -> Tuple[int, int]:
111111
api = "Driver.getDisplaySize"

hmdriver2/exception.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,17 @@ class ElementFoundTimeout(Exception):
88
pass
99

1010

11-
class HDriverError(Exception):
11+
class HmDriverError(Exception):
1212
pass
1313

1414

1515
class DeviceNotFoundError(Exception):
1616
pass
1717

1818

19-
class HDCException(Exception):
19+
class HdcError(Exception):
2020
pass
2121

2222

23-
class AttributeException(Exception):
23+
class InvokeHypiumError(Exception):
2424
pass

hmdriver2/hdc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def forward_port(self, rport: int) -> int:
7676
def rm_forward(self, lport: int, rport: int) -> int:
7777
result = _execute_command(f"hdc -t {self.serial} fport rm tcp:{lport} tcp:{rport}")
7878
if result.exit_code != 0:
79-
raise RuntimeError("HDC forward port error", result.output)
79+
raise RuntimeError("HDC rm forward error", result.output)
8080
return lport
8181

8282
def list_fport(self) -> List:

hmdriver2/proto.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,15 @@ class DeviceInfo:
4141

4242
@dataclass
4343
class HypiumResponse:
44-
result: Union[List, bool, str, None] # {"result":"Driver#0"}
44+
"""
45+
Example:
46+
{"result":"On#1"}
47+
{"result":null}
48+
{"result":null,"exception":"Can not connect to AAMS, RET_ERR_CONNECTION_EXIST"}
49+
{"exception":{"code":401,"message":"(PreProcessing: APiCallInfoChecker)Illegal argument count"}}
50+
"""
51+
result: Union[List, bool, str, None] = None
52+
exception: Union[List, bool, str, None] = None
4553

4654

4755
@dataclass

0 commit comments

Comments
 (0)