utils.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # coding: utf-8
  2. #
  3. import six
  4. import functools
  5. from ssat_sdk.uiautomator2.exceptions import (
  6. SessionBrokenError,
  7. UiObjectNotFoundError)
  8. def U(x):
  9. if six.PY3:
  10. return x
  11. return x.decode('utf-8') if type(x) is str else x
  12. def E(x):
  13. if six.PY3:
  14. return x
  15. return x.encode('utf-8') if type(x) is unicode else x
  16. def check_alive(fn):
  17. @functools.wraps(fn)
  18. def inner(self, *args, **kwargs):
  19. if not self.running():
  20. raise SessionBrokenError(self._pkg_name)
  21. return fn(self, *args, **kwargs)
  22. return inner
  23. def hooks_wrap(fn):
  24. @functools.wraps(fn)
  25. def inner(self, *args, **kwargs):
  26. name = fn.__name__.lstrip('_')
  27. self.server.hooks_apply("before", name, args, kwargs, None)
  28. ret = fn(self, *args, **kwargs)
  29. self.server.hooks_apply("after", name, args, kwargs, ret)
  30. return inner
  31. # Will be removed in the future
  32. def wrap_wait_exists(fn):
  33. @functools.wraps(fn)
  34. def inner(self, *args, **kwargs):
  35. timeout = kwargs.pop('timeout', self.wait_timeout)
  36. if not self.wait(timeout=timeout):
  37. raise UiObjectNotFoundError({
  38. 'code': -32002,
  39. 'message': E(self.selector.__str__())
  40. })
  41. return fn(self, *args, **kwargs)
  42. return inner
  43. def intersect(rect1, rect2):
  44. top = rect1["top"] if rect1["top"] > rect2["top"] else rect2["top"]
  45. bottom = rect1["bottom"] if rect1["bottom"] < rect2["bottom"] else rect2[
  46. "bottom"]
  47. left = rect1["left"] if rect1["left"] > rect2["left"] else rect2["left"]
  48. right = rect1["right"] if rect1["right"] < rect2["right"] else rect2[
  49. "right"]
  50. return left, top, right, bottom
  51. class Exists(object):
  52. """Exists object with magic methods."""
  53. def __init__(self, uiobject):
  54. self.uiobject = uiobject
  55. def __nonzero__(self):
  56. """Magic method for bool(self) python2 """
  57. return self.uiobject.jsonrpc.exist(self.uiobject.selector)
  58. def __bool__(self):
  59. """ Magic method for bool(self) python3 """
  60. return self.__nonzero__()
  61. def __call__(self, timeout=0):
  62. """Magic method for self(args).
  63. Args:
  64. timeout (float): exists in seconds
  65. """
  66. if timeout:
  67. return self.uiobject.wait(timeout=timeout)
  68. return bool(self)
  69. def __repr__(self):
  70. return str(bool(self))