refactor: NewADBDriver

This commit is contained in:
lilong.129
2025-02-06 21:39:17 +08:00
parent 94d3cb785c
commit f87d37d5c6
12 changed files with 164 additions and 167 deletions
+1 -1
View File
@@ -1 +1 @@
v5.0.0+2502062008 v5.0.0+2502062139
+5 -12
View File
@@ -175,15 +175,15 @@ func (dev *AndroidDevice) LogEnabled() bool {
} }
func (dev *AndroidDevice) NewDriver(opts ...option.DriverOption) (driverExt *DriverExt, err error) { func (dev *AndroidDevice) NewDriver(opts ...option.DriverOption) (driverExt *DriverExt, err error) {
driverOptions := option.NewDriverOptions(opts...) options := option.NewDriverOptions(opts...)
var driver IWebDriver var driver IWebDriver
if dev.UIA2 || dev.LogOn { if dev.UIA2 || dev.LogOn {
driver, err = dev.NewUSBDriver(driverOptions.Capabilities) driver, err = dev.NewUSBDriver(options.Capabilities)
} else if dev.STUB { } else if dev.STUB {
driver, err = dev.NewStubDriver(driverOptions.Capabilities) driver, err = dev.NewStubDriver(options.Capabilities)
} else { } else {
driver, err = dev.NewAdbDriver() driver, err = NewADBDriver(dev)
} }
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to init UIA driver") return nil, errors.Wrap(err, "failed to init UIA driver")
@@ -226,7 +226,7 @@ func (dev *AndroidDevice) NewUSBDriver(capabilities option.Capabilities) (driver
return uiaDriver, nil return uiaDriver, nil
} }
func (dev *AndroidDevice) NewStubDriver(capabilities option.Capabilities) (driver *stubAndroidDriver, err error) { func (dev *AndroidDevice) NewStubDriver(capabilities option.Capabilities) (driver *StubAndroidDriver, err error) {
socketLocalPort, err := dev.d.Forward(StubSocketName) socketLocalPort, err := dev.d.Forward(StubSocketName)
if err != nil { if err != nil {
return nil, errors.Wrap(code.DeviceConnectionError, return nil, errors.Wrap(code.DeviceConnectionError,
@@ -269,13 +269,6 @@ func (dev *AndroidDevice) NewHTTPDriver(capabilities option.Capabilities) (drive
return uiaDriver, nil return uiaDriver, nil
} }
func (dev *AndroidDevice) NewAdbDriver() (driver IWebDriver, err error) {
adbDriver := NewAdbDriver()
adbDriver.adbClient = dev.d
adbDriver.logcat = dev.logcat
return adbDriver, nil
}
func (dev *AndroidDevice) StartPerf() error { func (dev *AndroidDevice) StartPerf() error {
// TODO // TODO
return nil return nil
+79 -77
View File
@@ -32,21 +32,23 @@ const (
UnicodeImePackageName = "io.appium.settings/.UnicodeIME" UnicodeImePackageName = "io.appium.settings/.UnicodeIME"
) )
type adbDriver struct { func NewADBDriver(device *AndroidDevice, opts ...option.DriverOption) (*ADBDriver, error) {
log.Info().Interface("device", device).Msg("init android adb driver")
driver := &ADBDriver{}
driver.NewSession(nil)
driver.adbClient = device.d
driver.logcat = device.logcat
return driver, nil
}
type ADBDriver struct {
DriverClient DriverClient
adbClient *gadb.Device adbClient *gadb.Device
logcat *AdbLogcat logcat *AdbLogcat
} }
func NewAdbDriver() *adbDriver { func (ad *ADBDriver) runShellCommand(cmd string, args ...string) (output string, err error) {
log.Info().Msg("init adb driver")
driver := &adbDriver{}
driver.NewSession(nil)
return driver
}
func (ad *adbDriver) runShellCommand(cmd string, args ...string) (output string, err error) {
driverResult := &DriverResult{ driverResult := &DriverResult{
RequestMethod: "adb", RequestMethod: "adb",
RequestUrl: cmd, RequestUrl: cmd,
@@ -79,37 +81,37 @@ func (ad *adbDriver) runShellCommand(cmd string, args ...string) (output string,
return output, err return output, err
} }
func (ad *adbDriver) NewSession(capabilities option.Capabilities) (sessionInfo SessionInfo, err error) { func (ad *ADBDriver) NewSession(capabilities option.Capabilities) (sessionInfo SessionInfo, err error) {
ad.DriverClient.session.Reset() ad.DriverClient.session.Reset()
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) DeleteSession() (err error) { func (ad *ADBDriver) DeleteSession() (err error) {
return errDriverNotImplemented return errDriverNotImplemented
} }
func (ad *adbDriver) Status() (deviceStatus DeviceStatus, err error) { func (ad *ADBDriver) Status() (deviceStatus DeviceStatus, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) DeviceInfo() (deviceInfo DeviceInfo, err error) { func (ad *ADBDriver) DeviceInfo() (deviceInfo DeviceInfo, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) Location() (location Location, err error) { func (ad *ADBDriver) Location() (location Location, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) BatteryInfo() (batteryInfo BatteryInfo, err error) { func (ad *ADBDriver) BatteryInfo() (batteryInfo BatteryInfo, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) getWindowSize() (size Size, err error) { func (ad *ADBDriver) getWindowSize() (size Size, err error) {
// adb shell wm size // adb shell wm size
output, err := ad.runShellCommand("wm", "size") output, err := ad.runShellCommand("wm", "size")
if err != nil { if err != nil {
@@ -142,7 +144,7 @@ func (ad *adbDriver) getWindowSize() (size Size, err error) {
return return
} }
func (ad *adbDriver) WindowSize() (size Size, err error) { func (ad *ADBDriver) WindowSize() (size Size, err error) {
if !ad.windowSize.IsNil() { if !ad.windowSize.IsNil() {
// use cached window size // use cached window size
return ad.windowSize, nil return ad.windowSize, nil
@@ -168,16 +170,16 @@ func (ad *adbDriver) WindowSize() (size Size, err error) {
return size, nil return size, nil
} }
func (ad *adbDriver) Screen() (screen Screen, err error) { func (ad *ADBDriver) Screen() (screen Screen, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) Scale() (scale float64, err error) { func (ad *ADBDriver) Scale() (scale float64, err error) {
return 1, nil return 1, nil
} }
func (ad *adbDriver) GetTimestamp() (timestamp int64, err error) { func (ad *ADBDriver) GetTimestamp() (timestamp int64, err error) {
// adb shell date +%s // adb shell date +%s
output, err := ad.runShellCommand("date", "+%s") output, err := ad.runShellCommand("date", "+%s")
if err != nil { if err != nil {
@@ -193,7 +195,7 @@ func (ad *adbDriver) GetTimestamp() (timestamp int64, err error) {
} }
// PressBack simulates a short press on the BACK button. // PressBack simulates a short press on the BACK button.
func (ad *adbDriver) PressBack(opts ...option.ActionOption) (err error) { func (ad *ADBDriver) PressBack(opts ...option.ActionOption) (err error) {
// adb shell input keyevent 4 // adb shell input keyevent 4
_, err = ad.runShellCommand("input", "keyevent", fmt.Sprintf("%d", KCBack)) _, err = ad.runShellCommand("input", "keyevent", fmt.Sprintf("%d", KCBack))
if err != nil { if err != nil {
@@ -202,7 +204,7 @@ func (ad *adbDriver) PressBack(opts ...option.ActionOption) (err error) {
return nil return nil
} }
func (ad *adbDriver) StartCamera() (err error) { func (ad *ADBDriver) StartCamera() (err error) {
if _, err = ad.runShellCommand("rm", "-r", "/sdcard/DCIM/Camera"); err != nil { if _, err = ad.runShellCommand("rm", "-r", "/sdcard/DCIM/Camera"); err != nil {
return errors.Wrap(err, "remove /sdcard/DCIM/Camera failed") return errors.Wrap(err, "remove /sdcard/DCIM/Camera failed")
} }
@@ -236,7 +238,7 @@ func (ad *adbDriver) StartCamera() (err error) {
} }
} }
func (ad *adbDriver) StopCamera() (err error) { func (ad *ADBDriver) StopCamera() (err error) {
err = ad.PressBack() err = ad.PressBack()
if err != nil { if err != nil {
return err return err
@@ -257,7 +259,7 @@ func (ad *adbDriver) StopCamera() (err error) {
return return
} }
func (ad *adbDriver) Orientation() (orientation Orientation, err error) { func (ad *ADBDriver) Orientation() (orientation Orientation, err error) {
output, err := ad.runShellCommand("dumpsys", "input", "|", "grep", "'SurfaceOrientation'") output, err := ad.runShellCommand("dumpsys", "input", "|", "grep", "'SurfaceOrientation'")
if err != nil { if err != nil {
return return
@@ -275,11 +277,11 @@ func (ad *adbDriver) Orientation() (orientation Orientation, err error) {
return return
} }
func (ad *adbDriver) Homescreen() (err error) { func (ad *ADBDriver) Homescreen() (err error) {
return ad.PressKeyCodes(KCHome, KMEmpty) return ad.PressKeyCodes(KCHome, KMEmpty)
} }
func (ad *adbDriver) Unlock() (err error) { func (ad *ADBDriver) Unlock() (err error) {
// Notice: brighten should be executed before unlock // Notice: brighten should be executed before unlock
// brighten android device screen // brighten android device screen
if err := ad.PressKeyCodes(KCWakeup, KMEmpty); err != nil { if err := ad.PressKeyCodes(KCWakeup, KMEmpty); err != nil {
@@ -294,7 +296,7 @@ func (ad *adbDriver) Unlock() (err error) {
return ad.Swipe(500, 1500, 500, 500) return ad.Swipe(500, 1500, 500, 500)
} }
func (ad *adbDriver) Backspace(count int, opts ...option.ActionOption) (err error) { func (ad *ADBDriver) Backspace(count int, opts ...option.ActionOption) (err error) {
if count == 0 { if count == 0 {
return nil return nil
} }
@@ -309,7 +311,7 @@ func (ad *adbDriver) Backspace(count int, opts ...option.ActionOption) (err erro
return ad.combinationKey(keyArray) return ad.combinationKey(keyArray)
} }
func (ad *adbDriver) combinationKey(keyCodes []KeyCode) (err error) { func (ad *ADBDriver) combinationKey(keyCodes []KeyCode) (err error) {
if len(keyCodes) == 1 { if len(keyCodes) == 1 {
return ad.PressKeyCode(keyCodes[0]) return ad.PressKeyCode(keyCodes[0])
} }
@@ -322,11 +324,11 @@ func (ad *adbDriver) combinationKey(keyCodes []KeyCode) (err error) {
return return
} }
func (ad *adbDriver) PressKeyCode(keyCode KeyCode) (err error) { func (ad *ADBDriver) PressKeyCode(keyCode KeyCode) (err error) {
return ad.PressKeyCodes(keyCode, KMEmpty) return ad.PressKeyCodes(keyCode, KMEmpty)
} }
func (ad *adbDriver) PressKeyCodes(keyCode KeyCode, metaState KeyMeta) (err error) { func (ad *ADBDriver) PressKeyCodes(keyCode KeyCode, metaState KeyMeta) (err error) {
// adb shell input keyevent [--longpress] KEYCODE [METASTATE] // adb shell input keyevent [--longpress] KEYCODE [METASTATE]
if metaState != KMEmpty { if metaState != KMEmpty {
// press key with metastate, e.g. KMShiftOn/KMCtrlOn // press key with metastate, e.g. KMShiftOn/KMCtrlOn
@@ -342,7 +344,7 @@ func (ad *adbDriver) PressKeyCodes(keyCode KeyCode, metaState KeyMeta) (err erro
return return
} }
func (ad *adbDriver) AppLaunch(packageName string) (err error) { func (ad *ADBDriver) AppLaunch(packageName string) (err error) {
// 不指定 Activity 名称启动(启动主 Activity // 不指定 Activity 名称启动(启动主 Activity
// adb shell monkey -p <packagename> -c android.intent.category.LAUNCHER 1 // adb shell monkey -p <packagename> -c android.intent.category.LAUNCHER 1
sOutput, err := ad.runShellCommand( sOutput, err := ad.runShellCommand(
@@ -359,7 +361,7 @@ func (ad *adbDriver) AppLaunch(packageName string) (err error) {
return nil return nil
} }
func (ad *adbDriver) AppTerminate(packageName string) (successful bool, err error) { func (ad *ADBDriver) AppTerminate(packageName string) (successful bool, err error) {
// 强制停止应用,停止 <packagename> 相关的进程 // 强制停止应用,停止 <packagename> 相关的进程
// adb shell am force-stop <packagename> // adb shell am force-stop <packagename>
_, err = ad.runShellCommand("am", "force-stop", packageName) _, err = ad.runShellCommand("am", "force-stop", packageName)
@@ -370,7 +372,7 @@ func (ad *adbDriver) AppTerminate(packageName string) (successful bool, err erro
return true, nil return true, nil
} }
func (ad *adbDriver) Tap(x, y float64, opts ...option.ActionOption) error { func (ad *ADBDriver) Tap(x, y float64, opts ...option.ActionOption) error {
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
if len(actionOptions.Offset) == 2 { if len(actionOptions.Offset) == 2 {
@@ -391,7 +393,7 @@ func (ad *adbDriver) Tap(x, y float64, opts ...option.ActionOption) error {
return nil return nil
} }
func (ad *adbDriver) DoubleTap(x, y float64, opts ...option.ActionOption) error { func (ad *ADBDriver) DoubleTap(x, y float64, opts ...option.ActionOption) error {
// adb shell input tap x y // adb shell input tap x y
xStr := fmt.Sprintf("%.1f", x) xStr := fmt.Sprintf("%.1f", x)
yStr := fmt.Sprintf("%.1f", y) yStr := fmt.Sprintf("%.1f", y)
@@ -409,7 +411,7 @@ func (ad *adbDriver) DoubleTap(x, y float64, opts ...option.ActionOption) error
return nil return nil
} }
func (ad *adbDriver) TouchAndHold(x, y float64, opts ...option.ActionOption) (err error) { func (ad *ADBDriver) TouchAndHold(x, y float64, opts ...option.ActionOption) (err error) {
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
if len(actionOptions.Offset) == 2 { if len(actionOptions.Offset) == 2 {
@@ -435,7 +437,7 @@ func (ad *adbDriver) TouchAndHold(x, y float64, opts ...option.ActionOption) (er
return nil return nil
} }
func (ad *adbDriver) Drag(fromX, fromY, toX, toY float64, opts ...option.ActionOption) (err error) { func (ad *ADBDriver) Drag(fromX, fromY, toX, toY float64, opts ...option.ActionOption) (err error) {
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
if len(actionOptions.Offset) == 4 { if len(actionOptions.Offset) == 4 {
@@ -469,7 +471,7 @@ func (ad *adbDriver) Drag(fromX, fromY, toX, toY float64, opts ...option.ActionO
return nil return nil
} }
func (ad *adbDriver) Swipe(fromX, fromY, toX, toY float64, opts ...option.ActionOption) error { func (ad *ADBDriver) Swipe(fromX, fromY, toX, toY float64, opts ...option.ActionOption) error {
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
if len(actionOptions.Offset) == 4 { if len(actionOptions.Offset) == 4 {
@@ -495,26 +497,26 @@ func (ad *adbDriver) Swipe(fromX, fromY, toX, toY float64, opts ...option.Action
return nil return nil
} }
func (ad *adbDriver) ForceTouch(x, y int, pressure float64, second ...float64) error { func (ad *ADBDriver) ForceTouch(x, y int, pressure float64, second ...float64) error {
return ad.ForceTouchFloat(float64(x), float64(y), pressure, second...) return ad.ForceTouchFloat(float64(x), float64(y), pressure, second...)
} }
func (ad *adbDriver) ForceTouchFloat(x, y, pressure float64, second ...float64) (err error) { func (ad *ADBDriver) ForceTouchFloat(x, y, pressure float64, second ...float64) (err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) SetPasteboard(contentType PasteboardType, content string) (err error) { func (ad *ADBDriver) SetPasteboard(contentType PasteboardType, content string) (err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) GetPasteboard(contentType PasteboardType) (raw *bytes.Buffer, err error) { func (ad *ADBDriver) GetPasteboard(contentType PasteboardType) (raw *bytes.Buffer, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) SendKeys(text string, opts ...option.ActionOption) (err error) { func (ad *ADBDriver) SendKeys(text string, opts ...option.ActionOption) (err error) {
err = ad.SendUnicodeKeys(text, opts...) err = ad.SendUnicodeKeys(text, opts...)
if err == nil { if err == nil {
return return
@@ -523,7 +525,7 @@ func (ad *adbDriver) SendKeys(text string, opts ...option.ActionOption) (err err
return return
} }
func (ad *adbDriver) InputText(text string, opts ...option.ActionOption) error { func (ad *ADBDriver) InputText(text string, opts ...option.ActionOption) error {
// adb shell input text <text> // adb shell input text <text>
_, err := ad.runShellCommand("input", "text", text) _, err := ad.runShellCommand("input", "text", text)
if err != nil { if err != nil {
@@ -532,7 +534,7 @@ func (ad *adbDriver) InputText(text string, opts ...option.ActionOption) error {
return nil return nil
} }
func (ad *adbDriver) SendUnicodeKeys(text string, opts ...option.ActionOption) (err error) { func (ad *ADBDriver) SendUnicodeKeys(text string, opts ...option.ActionOption) (err error) {
// If the Unicode IME is not installed, fall back to the old interface. // If the Unicode IME is not installed, fall back to the old interface.
// There might be differences in the tracking schemes across different phones, and it is pending further verification. // There might be differences in the tracking schemes across different phones, and it is pending further verification.
// In release version: without the Unicode IME installed, the test cannot execute. // In release version: without the Unicode IME installed, the test cannot execute.
@@ -562,7 +564,7 @@ func (ad *adbDriver) SendUnicodeKeys(text string, opts ...option.ActionOption) (
return return
} }
func (ad *adbDriver) IsAdbKeyBoardInstalled() bool { func (ad *ADBDriver) IsAdbKeyBoardInstalled() bool {
output, err := ad.runShellCommand("ime", "list", "-a") output, err := ad.runShellCommand("ime", "list", "-a")
if err != nil { if err != nil {
return false return false
@@ -570,7 +572,7 @@ func (ad *adbDriver) IsAdbKeyBoardInstalled() bool {
return strings.Contains(output, AdbKeyBoardPackageName) return strings.Contains(output, AdbKeyBoardPackageName)
} }
func (ad *adbDriver) IsUnicodeIMEInstalled() bool { func (ad *ADBDriver) IsUnicodeIMEInstalled() bool {
output, err := ad.runShellCommand("ime", "list", "-s") output, err := ad.runShellCommand("ime", "list", "-s")
if err != nil { if err != nil {
return false return false
@@ -578,7 +580,7 @@ func (ad *adbDriver) IsUnicodeIMEInstalled() bool {
return strings.Contains(output, UnicodeImePackageName) return strings.Contains(output, UnicodeImePackageName)
} }
func (ad *adbDriver) ListIme() []string { func (ad *ADBDriver) ListIme() []string {
output, err := ad.runShellCommand("ime", "list", "-s") output, err := ad.runShellCommand("ime", "list", "-s")
if err != nil { if err != nil {
return []string{} return []string{}
@@ -586,7 +588,7 @@ func (ad *adbDriver) ListIme() []string {
return strings.Split(output, "\n") return strings.Split(output, "\n")
} }
func (ad *adbDriver) SendKeysByAdbKeyBoard(text string) (err error) { func (ad *ADBDriver) SendKeysByAdbKeyBoard(text string) (err error) {
defer func() { defer func() {
// Reset to default, don't care which keyboard was chosen before switch: // Reset to default, don't care which keyboard was chosen before switch:
if _, resetErr := ad.runShellCommand("ime", "reset"); resetErr != nil { if _, resetErr := ad.runShellCommand("ime", "reset"); resetErr != nil {
@@ -619,11 +621,11 @@ func (ad *adbDriver) SendKeysByAdbKeyBoard(text string) (err error) {
return return
} }
func (ad *adbDriver) Input(text string, opts ...option.ActionOption) (err error) { func (ad *ADBDriver) Input(text string, opts ...option.ActionOption) (err error) {
return ad.SendKeys(text, opts...) return ad.SendKeys(text, opts...)
} }
func (ad *adbDriver) Clear(packageName string) error { func (ad *ADBDriver) Clear(packageName string) error {
if _, err := ad.runShellCommand("pm", "clear", packageName); err != nil { if _, err := ad.runShellCommand("pm", "clear", packageName); err != nil {
log.Error().Str("packageName", packageName).Err(err).Msg("failed to clear package cache") log.Error().Str("packageName", packageName).Err(err).Msg("failed to clear package cache")
return err return err
@@ -632,22 +634,22 @@ func (ad *adbDriver) Clear(packageName string) error {
return nil return nil
} }
func (ad *adbDriver) PressButton(devBtn DeviceButton) (err error) { func (ad *ADBDriver) PressButton(devBtn DeviceButton) (err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) Rotation() (rotation Rotation, err error) { func (ad *ADBDriver) Rotation() (rotation Rotation, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) SetRotation(rotation Rotation) (err error) { func (ad *ADBDriver) SetRotation(rotation Rotation) (err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) Screenshot() (raw *bytes.Buffer, err error) { func (ad *ADBDriver) Screenshot() (raw *bytes.Buffer, err error) {
resp, err := ad.runShellCommand("screencap", "-p") resp, err := ad.runShellCommand("screencap", "-p")
if err != nil { if err != nil {
return nil, errors.Wrap(err, "adb screencap failed") return nil, errors.Wrap(err, "adb screencap failed")
@@ -656,7 +658,7 @@ func (ad *adbDriver) Screenshot() (raw *bytes.Buffer, err error) {
return bytes.NewBuffer([]byte(resp)), nil return bytes.NewBuffer([]byte(resp)), nil
} }
func (ad *adbDriver) Source(srcOpt ...option.SourceOption) (source string, err error) { func (ad *ADBDriver) Source(srcOpt ...option.SourceOption) (source string, err error) {
_, err = ad.runShellCommand("rm", "-rf", "/sdcard/window_dump.xml") _, err = ad.runShellCommand("rm", "-rf", "/sdcard/window_dump.xml")
if err != nil { if err != nil {
return return
@@ -673,15 +675,15 @@ func (ad *adbDriver) Source(srcOpt ...option.SourceOption) (source string, err e
return return
} }
func (ad *adbDriver) LoginNoneUI(packageName, phoneNumber string, captcha, password string) (info AppLoginInfo, err error) { func (ad *ADBDriver) LoginNoneUI(packageName, phoneNumber string, captcha, password string) (info AppLoginInfo, err error) {
return info, errDriverNotImplemented return info, errDriverNotImplemented
} }
func (ad *adbDriver) LogoutNoneUI(packageName string) error { func (ad *ADBDriver) LogoutNoneUI(packageName string) error {
return errDriverNotImplemented return errDriverNotImplemented
} }
func (ad *adbDriver) sourceTree(srcOpt ...option.SourceOption) (sourceTree *Hierarchy, err error) { func (ad *ADBDriver) sourceTree(srcOpt ...option.SourceOption) (sourceTree *Hierarchy, err error) {
source, err := ad.Source() source, err := ad.Source()
if err != nil { if err != nil {
return return
@@ -694,7 +696,7 @@ func (ad *adbDriver) sourceTree(srcOpt ...option.SourceOption) (sourceTree *Hier
return return
} }
func (ad *adbDriver) TapByText(text string, opts ...option.ActionOption) error { func (ad *ADBDriver) TapByText(text string, opts ...option.ActionOption) error {
sourceTree, err := ad.sourceTree() sourceTree, err := ad.sourceTree()
if err != nil { if err != nil {
return err return err
@@ -702,7 +704,7 @@ func (ad *adbDriver) TapByText(text string, opts ...option.ActionOption) error {
return ad.tapByTextUsingHierarchy(sourceTree, text, opts...) return ad.tapByTextUsingHierarchy(sourceTree, text, opts...)
} }
func (ad *adbDriver) tapByTextUsingHierarchy(hierarchy *Hierarchy, text string, opts ...option.ActionOption) error { func (ad *ADBDriver) tapByTextUsingHierarchy(hierarchy *Hierarchy, text string, opts ...option.ActionOption) error {
bounds := ad.searchNodes(hierarchy.Layout, text, opts...) bounds := ad.searchNodes(hierarchy.Layout, text, opts...)
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
if len(bounds) == 0 { if len(bounds) == 0 {
@@ -722,7 +724,7 @@ func (ad *adbDriver) tapByTextUsingHierarchy(hierarchy *Hierarchy, text string,
return nil return nil
} }
func (ad *adbDriver) TapByTexts(actions ...TapTextAction) error { func (ad *ADBDriver) TapByTexts(actions ...TapTextAction) error {
sourceTree, err := ad.sourceTree() sourceTree, err := ad.sourceTree()
if err != nil { if err != nil {
return err return err
@@ -737,7 +739,7 @@ func (ad *adbDriver) TapByTexts(actions ...TapTextAction) error {
return nil return nil
} }
func (ad *adbDriver) searchNodes(nodes []Layout, text string, opts ...option.ActionOption) []Bounds { func (ad *ADBDriver) searchNodes(nodes []Layout, text string, opts ...option.ActionOption) []Bounds {
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
var results []Bounds var results []Bounds
for _, node := range nodes { for _, node := range nodes {
@@ -762,32 +764,32 @@ func (ad *adbDriver) searchNodes(nodes []Layout, text string, opts ...option.Act
return results return results
} }
func (ad *adbDriver) AccessibleSource() (source string, err error) { func (ad *ADBDriver) AccessibleSource() (source string, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) HealthCheck() (err error) { func (ad *ADBDriver) HealthCheck() (err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) GetAppiumSettings() (settings map[string]interface{}, err error) { func (ad *ADBDriver) GetAppiumSettings() (settings map[string]interface{}, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) SetAppiumSettings(settings map[string]interface{}) (ret map[string]interface{}, err error) { func (ad *ADBDriver) SetAppiumSettings(settings map[string]interface{}) (ret map[string]interface{}, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) IsHealthy() (healthy bool, err error) { func (ad *ADBDriver) IsHealthy() (healthy bool, err error) {
err = errDriverNotImplemented err = errDriverNotImplemented
return return
} }
func (ad *adbDriver) StartCaptureLog(identifier ...string) (err error) { func (ad *ADBDriver) StartCaptureLog(identifier ...string) (err error) {
log.Info().Msg("start adb log recording") log.Info().Msg("start adb log recording")
// start logcat // start logcat
err = ad.logcat.CatchLogcat("iesqaMonitor:V") err = ad.logcat.CatchLogcat("iesqaMonitor:V")
@@ -799,7 +801,7 @@ func (ad *adbDriver) StartCaptureLog(identifier ...string) (err error) {
return nil return nil
} }
func (ad *adbDriver) StopCaptureLog() (result interface{}, err error) { func (ad *ADBDriver) StopCaptureLog() (result interface{}, err error) {
defer func() { defer func() {
log.Info().Msg("stop adb log recording") log.Info().Msg("stop adb log recording")
err = ad.logcat.Stop() err = ad.logcat.Stop()
@@ -862,15 +864,15 @@ func (ad *adbDriver) StopCaptureLog() (result interface{}, err error) {
return pointRes, nil return pointRes, nil
} }
func (ad *adbDriver) GetSession() *DriverSession { func (ad *ADBDriver) GetSession() *DriverSession {
return &ad.DriverClient.session return &ad.DriverClient.session
} }
func (ad *adbDriver) GetDriverResults() []*DriverResult { func (ad *ADBDriver) GetDriverResults() []*DriverResult {
return nil return nil
} }
func (ad *adbDriver) GetForegroundApp() (app AppInfo, err error) { func (ad *ADBDriver) GetForegroundApp() (app AppInfo, err error) {
packageInfo, err := ad.runShellCommand( packageInfo, err := ad.runShellCommand(
"CLASSPATH=/data/local/tmp/evalite", "app_process", "/", "CLASSPATH=/data/local/tmp/evalite", "app_process", "/",
"com.bytedance.iesqa.eval_process.PackageService", "2>/dev/null") "com.bytedance.iesqa.eval_process.PackageService", "2>/dev/null")
@@ -884,7 +886,7 @@ func (ad *adbDriver) GetForegroundApp() (app AppInfo, err error) {
return return
} }
func (ad *adbDriver) SetIme(imeRegx string) error { func (ad *ADBDriver) SetIme(imeRegx string) error {
imeList := ad.ListIme() imeList := ad.ListIme()
ime := "" ime := ""
for _, imeName := range imeList { for _, imeName := range imeList {
@@ -930,7 +932,7 @@ func (ad *adbDriver) SetIme(imeRegx string) error {
return nil return nil
} }
func (ad *adbDriver) GetIme() (ime string, err error) { func (ad *ADBDriver) GetIme() (ime string, err error) {
currentIme, err := ad.runShellCommand("settings", "get", "secure", "default_input_method") currentIme, err := ad.runShellCommand("settings", "get", "secure", "default_input_method")
if err != nil { if err != nil {
log.Warn().Err(err).Msgf("get default ime failed") log.Warn().Err(err).Msgf("get default ime failed")
@@ -940,7 +942,7 @@ func (ad *adbDriver) GetIme() (ime string, err error) {
return currentIme, nil return currentIme, nil
} }
func (ad *adbDriver) AssertForegroundApp(packageName string, activityType ...string) error { func (ad *ADBDriver) AssertForegroundApp(packageName string, activityType ...string) error {
log.Debug().Str("package_name", packageName). log.Debug().Str("package_name", packageName).
Strs("activity_type", activityType). Strs("activity_type", activityType).
Msg("assert android foreground package and activity") Msg("assert android foreground package and activity")
@@ -1036,7 +1038,7 @@ var androidActivities = map[string]map[string][]string{
// TODO: SPH, XHS // TODO: SPH, XHS
} }
func (ad *adbDriver) RecordScreen(folderPath string, duration time.Duration) (videoPath string, err error) { func (ad *ADBDriver) RecordScreen(folderPath string, duration time.Duration) (videoPath string, err error) {
// 获取当前时间戳 // 获取当前时间戳
timestamp := time.Now().Format("20060102_150405") + fmt.Sprintf("_%03d", time.Now().UnixNano()/1e6%1000) timestamp := time.Now().Format("20060102_150405") + fmt.Sprintf("_%03d", time.Now().UnixNano()/1e6%1000)
// 创建文件名 // 创建文件名
@@ -1093,6 +1095,6 @@ func (ad *adbDriver) RecordScreen(folderPath string, duration time.Duration) (vi
return filepath.Abs(fileName) return filepath.Abs(fileName)
} }
func (ad *adbDriver) TearDown() error { func (ad *ADBDriver) TearDown() error {
return nil return nil
} }
+17 -17
View File
@@ -16,11 +16,11 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/option" "github.com/httprunner/httprunner/v5/pkg/uixt/option"
) )
type stubAndroidDriver struct { type StubAndroidDriver struct {
socket net.Conn socket net.Conn
seq int seq int
timeout time.Duration timeout time.Duration
adbDriver ADBDriver
} }
const StubSocketName = "com.bytest.device" const StubSocketName = "com.bytest.device"
@@ -33,7 +33,7 @@ type AppLoginInfo struct {
// newStubAndroidDriver // newStubAndroidDriver
// 创建stub Driver address为forward后的端口格式127.0.0.1:${port} // 创建stub Driver address为forward后的端口格式127.0.0.1:${port}
func newStubAndroidDriver(address string, urlPrefix string, readTimeout ...time.Duration) (*stubAndroidDriver, error) { func newStubAndroidDriver(address string, urlPrefix string, readTimeout ...time.Duration) (*StubAndroidDriver, error) {
timeout := 10 * time.Second timeout := 10 * time.Second
if len(readTimeout) > 0 { if len(readTimeout) > 0 {
timeout = readTimeout[0] timeout = readTimeout[0]
@@ -45,7 +45,7 @@ func newStubAndroidDriver(address string, urlPrefix string, readTimeout ...time.
return nil, err return nil, err
} }
driver := &stubAndroidDriver{ driver := &StubAndroidDriver{
socket: conn, socket: conn,
timeout: timeout, timeout: timeout,
} }
@@ -58,7 +58,7 @@ func newStubAndroidDriver(address string, urlPrefix string, readTimeout ...time.
return driver, nil return driver, nil
} }
func (sad *stubAndroidDriver) httpGET(pathElem ...string) (rawResp rawResponse, err error) { func (sad *StubAndroidDriver) httpGET(pathElem ...string) (rawResp rawResponse, err error) {
var localPort int var localPort int
{ {
tmpURL, _ := url.Parse(sad.urlPrefix.String()) tmpURL, _ := url.Parse(sad.urlPrefix.String())
@@ -76,7 +76,7 @@ func (sad *stubAndroidDriver) httpGET(pathElem ...string) (rawResp rawResponse,
return sad.Request(http.MethodGet, sad.concatURL(nil, pathElem...), nil) return sad.Request(http.MethodGet, sad.concatURL(nil, pathElem...), nil)
} }
func (sad *stubAndroidDriver) httpPOST(data interface{}, pathElem ...string) (rawResp rawResponse, err error) { func (sad *StubAndroidDriver) httpPOST(data interface{}, pathElem ...string) (rawResp rawResponse, err error) {
var localPort int var localPort int
{ {
tmpURL, _ := url.Parse(sad.urlPrefix.String()) tmpURL, _ := url.Parse(sad.urlPrefix.String())
@@ -101,12 +101,12 @@ func (sad *stubAndroidDriver) httpPOST(data interface{}, pathElem ...string) (ra
return sad.Request(http.MethodPost, sad.concatURL(nil, pathElem...), bsJSON) return sad.Request(http.MethodPost, sad.concatURL(nil, pathElem...), bsJSON)
} }
func (sad *stubAndroidDriver) NewSession(capabilities option.Capabilities) (SessionInfo, error) { func (sad *StubAndroidDriver) NewSession(capabilities option.Capabilities) (SessionInfo, error) {
sad.DriverClient.session.Reset() sad.DriverClient.session.Reset()
return SessionInfo{}, errDriverNotImplemented return SessionInfo{}, errDriverNotImplemented
} }
func (sad *stubAndroidDriver) sendCommand(packageName string, cmdType string, params map[string]interface{}, readTimeout ...time.Duration) (interface{}, error) { func (sad *StubAndroidDriver) sendCommand(packageName string, cmdType string, params map[string]interface{}, readTimeout ...time.Duration) (interface{}, error) {
sad.seq++ sad.seq++
packet := map[string]interface{}{ packet := map[string]interface{}{
"Seq": sad.seq, "Seq": sad.seq,
@@ -139,18 +139,18 @@ func (sad *stubAndroidDriver) sendCommand(packageName string, cmdType string, pa
return resultMap["Result"], nil return resultMap["Result"], nil
} }
func (sad *stubAndroidDriver) DeleteSession() error { func (sad *StubAndroidDriver) DeleteSession() error {
return sad.close() return sad.close()
} }
func (sad *stubAndroidDriver) close() error { func (sad *StubAndroidDriver) close() error {
if sad.socket != nil { if sad.socket != nil {
return sad.socket.Close() return sad.socket.Close()
} }
return nil return nil
} }
func (sad *stubAndroidDriver) Status() (DeviceStatus, error) { func (sad *StubAndroidDriver) Status() (DeviceStatus, error) {
app, err := sad.GetForegroundApp() app, err := sad.GetForegroundApp()
if err != nil { if err != nil {
return DeviceStatus{}, err return DeviceStatus{}, err
@@ -163,7 +163,7 @@ func (sad *stubAndroidDriver) Status() (DeviceStatus, error) {
return DeviceStatus{}, nil return DeviceStatus{}, nil
} }
func (sad *stubAndroidDriver) Source(srcOpt ...option.SourceOption) (source string, err error) { func (sad *StubAndroidDriver) Source(srcOpt ...option.SourceOption) (source string, err error) {
app, err := sad.GetForegroundApp() app, err := sad.GetForegroundApp()
if err != nil { if err != nil {
return "", err return "", err
@@ -181,7 +181,7 @@ func (sad *stubAndroidDriver) Source(srcOpt ...option.SourceOption) (source stri
return res.(string), nil return res.(string), nil
} }
func (sad *stubAndroidDriver) LoginNoneUI(packageName, phoneNumber string, captcha, password string) (info AppLoginInfo, err error) { func (sad *StubAndroidDriver) LoginNoneUI(packageName, phoneNumber string, captcha, password string) (info AppLoginInfo, err error) {
params := map[string]interface{}{ params := map[string]interface{}{
"phone": phoneNumber, "phone": phoneNumber,
} }
@@ -214,7 +214,7 @@ func (sad *stubAndroidDriver) LoginNoneUI(packageName, phoneNumber string, captc
return info, nil return info, nil
} }
func (sad *stubAndroidDriver) LogoutNoneUI(packageName string) error { func (sad *StubAndroidDriver) LogoutNoneUI(packageName string) error {
resp, err := sad.httpGET("/host", "/logout") resp, err := sad.httpGET("/host", "/logout")
if err != nil { if err != nil {
return err return err
@@ -237,7 +237,7 @@ func (sad *stubAndroidDriver) LogoutNoneUI(packageName string) error {
return nil return nil
} }
func (sad *stubAndroidDriver) LoginNoneUIDynamic(packageName, phoneNumber string, captcha string) error { func (sad *StubAndroidDriver) LoginNoneUIDynamic(packageName, phoneNumber string, captcha string) error {
params := map[string]interface{}{ params := map[string]interface{}{
"ClassName": "qe.python.test.LoginUtil", "ClassName": "qe.python.test.LoginUtil",
"Method": "loginSync", "Method": "loginSync",
@@ -252,7 +252,7 @@ func (sad *stubAndroidDriver) LoginNoneUIDynamic(packageName, phoneNumber string
return nil return nil
} }
func (sad *stubAndroidDriver) SetHDTStatus(status bool) error { func (sad *StubAndroidDriver) SetHDTStatus(status bool) error {
_, err := sad.adbClient.RunShellCommand("settings", "put", "global", "feedbacker_sso_bypass_token", "default_sso_bypass_token") _, err := sad.adbClient.RunShellCommand("settings", "put", "global", "feedbacker_sso_bypass_token", "default_sso_bypass_token")
if err != nil { if err != nil {
log.Warn().Msg(fmt.Sprintf("failed to disable sso, error: %v", err)) log.Warn().Msg(fmt.Sprintf("failed to disable sso, error: %v", err))
@@ -271,7 +271,7 @@ func (sad *stubAndroidDriver) SetHDTStatus(status bool) error {
return nil return nil
} }
func (sad *stubAndroidDriver) getLoginAppInfo(packageName string) (info AppLoginInfo, err error) { func (sad *StubAndroidDriver) getLoginAppInfo(packageName string) (info AppLoginInfo, err error) {
resp, err := sad.httpGET("/host", "/app", "/info") resp, err := sad.httpGET("/host", "/app", "/info")
if err != nil { if err != nil {
return info, err return info, err
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/option" "github.com/httprunner/httprunner/v5/pkg/uixt/option"
) )
var androidStubDriver *stubAndroidDriver var androidStubDriver *StubAndroidDriver
func setupStubDriver(t *testing.T) { func setupStubDriver(t *testing.T) {
device, err := NewAndroidDevice() device, err := NewAndroidDevice()
+43 -43
View File
@@ -22,17 +22,17 @@ import (
var errDriverNotImplemented = errors.New("driver method not implemented") var errDriverNotImplemented = errors.New("driver method not implemented")
type uiaDriver struct { type UIA2Driver struct {
adbDriver ADBDriver
} }
func NewUIADriver(capabilities option.Capabilities, urlPrefix string) (driver *uiaDriver, err error) { func NewUIADriver(capabilities option.Capabilities, urlPrefix string) (driver *UIA2Driver, err error) {
log.Info().Msg("init uiautomator2 driver") log.Info().Msg("init uiautomator2 driver")
if capabilities == nil { if capabilities == nil {
capabilities = option.NewCapabilities() capabilities = option.NewCapabilities()
capabilities.WithWaitForIdleTimeout(0) capabilities.WithWaitForIdleTimeout(0)
} }
driver = new(uiaDriver) driver = new(UIA2Driver)
if driver.urlPrefix, err = url.Parse(urlPrefix); err != nil { if driver.urlPrefix, err = url.Parse(urlPrefix); err != nil {
return nil, err return nil, err
} }
@@ -85,7 +85,7 @@ func (bs BatteryStatus) String() string {
} }
} }
func (ud *uiaDriver) resetDriver() error { func (ud *UIA2Driver) resetDriver() error {
newUIADriver, err := NewUIADriver(option.NewCapabilities(), ud.urlPrefix.String()) newUIADriver, err := NewUIADriver(option.NewCapabilities(), ud.urlPrefix.String())
if err != nil { if err != nil {
return err return err
@@ -95,7 +95,7 @@ func (ud *uiaDriver) resetDriver() error {
return nil return nil
} }
func (ud *uiaDriver) httpRequest(method string, rawURL string, rawBody []byte) (rawResp rawResponse, err error) { func (ud *UIA2Driver) httpRequest(method string, rawURL string, rawBody []byte) (rawResp rawResponse, err error) {
for retryCount := 1; retryCount <= 5; retryCount++ { for retryCount := 1; retryCount <= 5; retryCount++ {
rawResp, err = ud.DriverClient.Request(method, rawURL, rawBody) rawResp, err = ud.DriverClient.Request(method, rawURL, rawBody)
if err == nil { if err == nil {
@@ -116,11 +116,11 @@ func (ud *uiaDriver) httpRequest(method string, rawURL string, rawBody []byte) (
return return
} }
func (ud *uiaDriver) httpGET(pathElem ...string) (rawResp rawResponse, err error) { func (ud *UIA2Driver) httpGET(pathElem ...string) (rawResp rawResponse, err error) {
return ud.httpRequest(http.MethodGet, ud.concatURL(nil, pathElem...), nil) return ud.httpRequest(http.MethodGet, ud.concatURL(nil, pathElem...), nil)
} }
func (ud *uiaDriver) httpPOST(data interface{}, pathElem ...string) (rawResp rawResponse, err error) { func (ud *UIA2Driver) httpPOST(data interface{}, pathElem ...string) (rawResp rawResponse, err error) {
var bsJSON []byte = nil var bsJSON []byte = nil
if data != nil { if data != nil {
if bsJSON, err = json.Marshal(data); err != nil { if bsJSON, err = json.Marshal(data); err != nil {
@@ -130,11 +130,11 @@ func (ud *uiaDriver) httpPOST(data interface{}, pathElem ...string) (rawResp raw
return ud.httpRequest(http.MethodPost, ud.concatURL(nil, pathElem...), bsJSON) return ud.httpRequest(http.MethodPost, ud.concatURL(nil, pathElem...), bsJSON)
} }
func (ud *uiaDriver) httpDELETE(pathElem ...string) (rawResp rawResponse, err error) { func (ud *UIA2Driver) httpDELETE(pathElem ...string) (rawResp rawResponse, err error) {
return ud.httpRequest(http.MethodDelete, ud.concatURL(nil, pathElem...), nil) return ud.httpRequest(http.MethodDelete, ud.concatURL(nil, pathElem...), nil)
} }
func (ud *uiaDriver) NewSession(capabilities option.Capabilities) (sessionInfo SessionInfo, err error) { func (ud *UIA2Driver) NewSession(capabilities option.Capabilities) (sessionInfo SessionInfo, err error) {
// register(postHandler, new NewSession("/wd/hub/session")) // register(postHandler, new NewSession("/wd/hub/session"))
var rawResp rawResponse var rawResp rawResponse
data := make(map[string]interface{}) data := make(map[string]interface{})
@@ -157,7 +157,7 @@ func (ud *uiaDriver) NewSession(capabilities option.Capabilities) (sessionInfo S
return SessionInfo{SessionId: sessionID}, nil return SessionInfo{SessionId: sessionID}, nil
} }
func (ud *uiaDriver) DeleteSession() (err error) { func (ud *UIA2Driver) DeleteSession() (err error) {
if ud.session.ID == "" { if ud.session.ID == "" {
return nil return nil
} }
@@ -168,7 +168,7 @@ func (ud *uiaDriver) DeleteSession() (err error) {
return err return err
} }
func (ud *uiaDriver) Status() (deviceStatus DeviceStatus, err error) { func (ud *UIA2Driver) Status() (deviceStatus DeviceStatus, err error) {
// register(getHandler, new Status("/wd/hub/status")) // register(getHandler, new Status("/wd/hub/status"))
var rawResp rawResponse var rawResp rawResponse
// Notice: use Driver.GET instead of httpGET to avoid loop calling // Notice: use Driver.GET instead of httpGET to avoid loop calling
@@ -187,7 +187,7 @@ func (ud *uiaDriver) Status() (deviceStatus DeviceStatus, err error) {
return DeviceStatus{Ready: true}, nil return DeviceStatus{Ready: true}, nil
} }
func (ud *uiaDriver) DeviceInfo() (deviceInfo DeviceInfo, err error) { func (ud *UIA2Driver) DeviceInfo() (deviceInfo DeviceInfo, err error) {
// register(getHandler, new GetDeviceInfo("/wd/hub/session/:sessionId/appium/device/info")) // register(getHandler, new GetDeviceInfo("/wd/hub/session/:sessionId/appium/device/info"))
var rawResp rawResponse var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.session.ID, "appium/device/info"); err != nil { if rawResp, err = ud.httpGET("/session", ud.session.ID, "appium/device/info"); err != nil {
@@ -201,7 +201,7 @@ func (ud *uiaDriver) DeviceInfo() (deviceInfo DeviceInfo, err error) {
return return
} }
func (ud *uiaDriver) BatteryInfo() (batteryInfo BatteryInfo, err error) { func (ud *UIA2Driver) BatteryInfo() (batteryInfo BatteryInfo, err error) {
// register(getHandler, new GetBatteryInfo("/wd/hub/session/:sessionId/appium/device/battery_info")) // register(getHandler, new GetBatteryInfo("/wd/hub/session/:sessionId/appium/device/battery_info"))
var rawResp rawResponse var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.session.ID, "appium/device/battery_info"); err != nil { if rawResp, err = ud.httpGET("/session", ud.session.ID, "appium/device/battery_info"); err != nil {
@@ -218,7 +218,7 @@ func (ud *uiaDriver) BatteryInfo() (batteryInfo BatteryInfo, err error) {
return return
} }
func (ud *uiaDriver) WindowSize() (size Size, err error) { func (ud *UIA2Driver) WindowSize() (size Size, err error) {
// register(getHandler, new GetDeviceSize("/wd/hub/session/:sessionId/window/:windowHandle/size")) // register(getHandler, new GetDeviceSize("/wd/hub/session/:sessionId/window/:windowHandle/size"))
if !ud.windowSize.IsNil() { if !ud.windowSize.IsNil() {
// use cached window size // use cached window size
@@ -250,21 +250,21 @@ func (ud *uiaDriver) WindowSize() (size Size, err error) {
} }
// PressBack simulates a short press on the BACK button. // PressBack simulates a short press on the BACK button.
func (ud *uiaDriver) PressBack(opts ...option.ActionOption) (err error) { func (ud *UIA2Driver) PressBack(opts ...option.ActionOption) (err error) {
// register(postHandler, new PressBack("/wd/hub/session/:sessionId/back")) // register(postHandler, new PressBack("/wd/hub/session/:sessionId/back"))
_, err = ud.httpPOST(nil, "/session", ud.session.ID, "back") _, err = ud.httpPOST(nil, "/session", ud.session.ID, "back")
return return
} }
func (ud *uiaDriver) Homescreen() (err error) { func (ud *UIA2Driver) Homescreen() (err error) {
return ud.PressKeyCodes(KCHome, KMEmpty) return ud.PressKeyCodes(KCHome, KMEmpty)
} }
func (ud *uiaDriver) PressKeyCode(keyCode KeyCode) (err error) { func (ud *UIA2Driver) PressKeyCode(keyCode KeyCode) (err error) {
return ud.PressKeyCodes(keyCode, KMEmpty) return ud.PressKeyCodes(keyCode, KMEmpty)
} }
func (ud *uiaDriver) PressKeyCodes(keyCode KeyCode, metaState KeyMeta, flags ...KeyFlag) (err error) { func (ud *UIA2Driver) PressKeyCodes(keyCode KeyCode, metaState KeyMeta, flags ...KeyFlag) (err error) {
// register(postHandler, new PressKeyCodeAsync("/wd/hub/session/:sessionId/appium/device/press_keycode")) // register(postHandler, new PressKeyCodeAsync("/wd/hub/session/:sessionId/appium/device/press_keycode"))
data := map[string]interface{}{ data := map[string]interface{}{
"keycode": keyCode, "keycode": keyCode,
@@ -279,7 +279,7 @@ func (ud *uiaDriver) PressKeyCodes(keyCode KeyCode, metaState KeyMeta, flags ...
return return
} }
func (ud *uiaDriver) Orientation() (orientation Orientation, err error) { func (ud *UIA2Driver) Orientation() (orientation Orientation, err error) {
// [[FBRoute GET:@"/orientation"] respondWithTarget:self action:@selector(handleGetOrientation:)] // [[FBRoute GET:@"/orientation"] respondWithTarget:self action:@selector(handleGetOrientation:)]
var rawResp rawResponse var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.session.ID, "/orientation"); err != nil { if rawResp, err = ud.httpGET("/session", ud.session.ID, "/orientation"); err != nil {
@@ -293,11 +293,11 @@ func (ud *uiaDriver) Orientation() (orientation Orientation, err error) {
return return
} }
func (ud *uiaDriver) DoubleTap(x, y float64, opts ...option.ActionOption) error { func (ud *UIA2Driver) DoubleTap(x, y float64, opts ...option.ActionOption) error {
return ud.DoubleFloatTap(x, y) return ud.DoubleFloatTap(x, y)
} }
func (ud *uiaDriver) DoubleFloatTap(x, y float64) error { func (ud *UIA2Driver) DoubleFloatTap(x, y float64) error {
data := map[string]interface{}{ data := map[string]interface{}{
"actions": []interface{}{ "actions": []interface{}{
map[string]interface{}{ map[string]interface{}{
@@ -319,7 +319,7 @@ func (ud *uiaDriver) DoubleFloatTap(x, y float64) error {
return err return err
} }
func (ud *uiaDriver) Tap(x, y float64, opts ...option.ActionOption) (err error) { func (ud *UIA2Driver) Tap(x, y float64, opts ...option.ActionOption) (err error) {
// register(postHandler, new Tap("/wd/hub/session/:sessionId/appium/tap")) // register(postHandler, new Tap("/wd/hub/session/:sessionId/appium/tap"))
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
@@ -357,7 +357,7 @@ func (ud *uiaDriver) Tap(x, y float64, opts ...option.ActionOption) (err error)
return err return err
} }
func (ud *uiaDriver) TouchAndHold(x, y float64, opts ...option.ActionOption) (err error) { func (ud *UIA2Driver) TouchAndHold(x, y float64, opts ...option.ActionOption) (err error) {
actionOpts := option.NewActionOptions(opts...) actionOpts := option.NewActionOptions(opts...)
duration := actionOpts.Duration duration := actionOpts.Duration
if duration == 0 { if duration == 0 {
@@ -379,7 +379,7 @@ func (ud *uiaDriver) TouchAndHold(x, y float64, opts ...option.ActionOption) (er
// the smoothness and speed of the swipe by specifying the number of steps. // the smoothness and speed of the swipe by specifying the number of steps.
// Each step execution is throttled to 5 milliseconds per step, so for a 100 // Each step execution is throttled to 5 milliseconds per step, so for a 100
// steps, the swipe will take around 0.5 seconds to complete. // steps, the swipe will take around 0.5 seconds to complete.
func (ud *uiaDriver) Drag(fromX, fromY, toX, toY float64, opts ...option.ActionOption) (err error) { func (ud *UIA2Driver) Drag(fromX, fromY, toX, toY float64, opts ...option.ActionOption) (err error) {
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
if len(actionOptions.Offset) == 4 { if len(actionOptions.Offset) == 4 {
fromX += float64(actionOptions.Offset[0]) fromX += float64(actionOptions.Offset[0])
@@ -412,7 +412,7 @@ func (ud *uiaDriver) Drag(fromX, fromY, toX, toY float64, opts ...option.ActionO
// per step. So for a 100 steps, the swipe will take about 1/2 second to complete. // per step. So for a 100 steps, the swipe will take about 1/2 second to complete.
// //
// `steps` is the number of move steps sent to the system // `steps` is the number of move steps sent to the system
func (ud *uiaDriver) Swipe(fromX, fromY, toX, toY float64, opts ...option.ActionOption) error { func (ud *UIA2Driver) Swipe(fromX, fromY, toX, toY float64, opts ...option.ActionOption) error {
// register(postHandler, new Swipe("/wd/hub/session/:sessionId/touch/perform")) // register(postHandler, new Swipe("/wd/hub/session/:sessionId/touch/perform"))
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
if len(actionOptions.Offset) == 4 { if len(actionOptions.Offset) == 4 {
@@ -453,7 +453,7 @@ func (ud *uiaDriver) Swipe(fromX, fromY, toX, toY float64, opts ...option.Action
return err return err
} }
func (ud *uiaDriver) SetPasteboard(contentType PasteboardType, content string) (err error) { func (ud *UIA2Driver) SetPasteboard(contentType PasteboardType, content string) (err error) {
lbl := content lbl := content
const defaultLabelLen = 10 const defaultLabelLen = 10
@@ -471,7 +471,7 @@ func (ud *uiaDriver) SetPasteboard(contentType PasteboardType, content string) (
return return
} }
func (ud *uiaDriver) GetPasteboard(contentType PasteboardType) (raw *bytes.Buffer, err error) { func (ud *UIA2Driver) GetPasteboard(contentType PasteboardType) (raw *bytes.Buffer, err error) {
if len(contentType) == 0 { if len(contentType) == 0 {
contentType = PasteboardTypePlaintext contentType = PasteboardTypePlaintext
} }
@@ -497,7 +497,7 @@ func (ud *uiaDriver) GetPasteboard(contentType PasteboardType) (raw *bytes.Buffe
} }
// SendKeys Android input does not support setting frequency. // SendKeys Android input does not support setting frequency.
func (ud *uiaDriver) SendKeys(text string, opts ...option.ActionOption) (err error) { func (ud *UIA2Driver) SendKeys(text string, opts ...option.ActionOption) (err error) {
// register(postHandler, new SendKeysToElement("/wd/hub/session/:sessionId/keys")) // register(postHandler, new SendKeysToElement("/wd/hub/session/:sessionId/keys"))
// https://github.com/appium/appium-uiautomator2-server/blob/master/app/src/main/java/io/appium/uiautomator2/handler/SendKeysToElement.java#L76-L85 // https://github.com/appium/appium-uiautomator2-server/blob/master/app/src/main/java/io/appium/uiautomator2/handler/SendKeysToElement.java#L76-L85
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
@@ -515,22 +515,22 @@ func (ud *uiaDriver) SendKeys(text string, opts ...option.ActionOption) (err err
return return
} }
func (ud *uiaDriver) SendUnicodeKeys(text string, opts ...option.ActionOption) (err error) { func (ud *UIA2Driver) SendUnicodeKeys(text string, opts ...option.ActionOption) (err error) {
// If the Unicode IME is not installed, fall back to the old interface. // If the Unicode IME is not installed, fall back to the old interface.
// There might be differences in the tracking schemes across different phones, and it is pending further verification. // There might be differences in the tracking schemes across different phones, and it is pending further verification.
// In release version: without the Unicode IME installed, the test cannot execute. // In release version: without the Unicode IME installed, the test cannot execute.
if !ud.IsUnicodeIMEInstalled() { if !ud.IsUnicodeIMEInstalled() {
return fmt.Errorf("appium unicode ime not installed") return fmt.Errorf("appium unicode ime not installed")
} }
currentIme, err := ud.adbDriver.GetIme() currentIme, err := ud.ADBDriver.GetIme()
if err != nil { if err != nil {
return return
} }
if currentIme != UnicodeImePackageName { if currentIme != UnicodeImePackageName {
defer func() { defer func() {
_ = ud.adbDriver.SetIme(currentIme) _ = ud.ADBDriver.SetIme(currentIme)
}() }()
err = ud.adbDriver.SetIme(UnicodeImePackageName) err = ud.ADBDriver.SetIme(UnicodeImePackageName)
if err != nil { if err != nil {
log.Warn().Err(err).Msgf("set Unicode Ime failed") log.Warn().Err(err).Msgf("set Unicode Ime failed")
return return
@@ -545,7 +545,7 @@ func (ud *uiaDriver) SendUnicodeKeys(text string, opts ...option.ActionOption) (
return return
} }
func (ud *uiaDriver) SendActionKey(text string, opts ...option.ActionOption) (err error) { func (ud *UIA2Driver) SendActionKey(text string, opts ...option.ActionOption) (err error) {
actionOptions := option.NewActionOptions(opts...) actionOptions := option.NewActionOptions(opts...)
var actions []interface{} var actions []interface{}
for i, c := range text { for i, c := range text {
@@ -572,11 +572,11 @@ func (ud *uiaDriver) SendActionKey(text string, opts ...option.ActionOption) (er
return return
} }
func (ud *uiaDriver) Input(text string, opts ...option.ActionOption) (err error) { func (ud *UIA2Driver) Input(text string, opts ...option.ActionOption) (err error) {
return ud.SendKeys(text, opts...) return ud.SendKeys(text, opts...)
} }
func (ud *uiaDriver) Rotation() (rotation Rotation, err error) { func (ud *UIA2Driver) Rotation() (rotation Rotation, err error) {
// register(getHandler, new GetRotation("/wd/hub/session/:sessionId/rotation")) // register(getHandler, new GetRotation("/wd/hub/session/:sessionId/rotation"))
var rawResp rawResponse var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.session.ID, "rotation"); err != nil { if rawResp, err = ud.httpGET("/session", ud.session.ID, "rotation"); err != nil {
@@ -591,13 +591,13 @@ func (ud *uiaDriver) Rotation() (rotation Rotation, err error) {
return return
} }
func (ud *uiaDriver) Screenshot() (raw *bytes.Buffer, err error) { func (ud *UIA2Driver) Screenshot() (raw *bytes.Buffer, err error) {
// https://bytedance.larkoffice.com/docx/C8qEdmSHnoRvMaxZauocMiYpnLh // https://bytedance.larkoffice.com/docx/C8qEdmSHnoRvMaxZauocMiYpnLh
// ui2截图受内存影响,改为adb截图 // ui2截图受内存影响,改为adb截图
return ud.adbDriver.Screenshot() return ud.ADBDriver.Screenshot()
} }
func (ud *uiaDriver) Source(srcOpt ...option.SourceOption) (source string, err error) { func (ud *UIA2Driver) Source(srcOpt ...option.SourceOption) (source string, err error) {
// register(getHandler, new Source("/wd/hub/session/:sessionId/source")) // register(getHandler, new Source("/wd/hub/session/:sessionId/source"))
var rawResp rawResponse var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.session.ID, "source"); err != nil { if rawResp, err = ud.httpGET("/session", ud.session.ID, "source"); err != nil {
@@ -612,7 +612,7 @@ func (ud *uiaDriver) Source(srcOpt ...option.SourceOption) (source string, err e
return return
} }
func (ud *uiaDriver) sourceTree(srcOpt ...option.SourceOption) (sourceTree *Hierarchy, err error) { func (ud *UIA2Driver) sourceTree(srcOpt ...option.SourceOption) (sourceTree *Hierarchy, err error) {
source, err := ud.Source() source, err := ud.Source()
if err != nil { if err != nil {
return return
@@ -625,7 +625,7 @@ func (ud *uiaDriver) sourceTree(srcOpt ...option.SourceOption) (sourceTree *Hier
return return
} }
func (ud *uiaDriver) TapByText(text string, opts ...option.ActionOption) error { func (ud *UIA2Driver) TapByText(text string, opts ...option.ActionOption) error {
sourceTree, err := ud.sourceTree() sourceTree, err := ud.sourceTree()
if err != nil { if err != nil {
return err return err
@@ -633,7 +633,7 @@ func (ud *uiaDriver) TapByText(text string, opts ...option.ActionOption) error {
return ud.tapByTextUsingHierarchy(sourceTree, text, opts...) return ud.tapByTextUsingHierarchy(sourceTree, text, opts...)
} }
func (ud *uiaDriver) TapByTexts(actions ...TapTextAction) error { func (ud *UIA2Driver) TapByTexts(actions ...TapTextAction) error {
sourceTree, err := ud.sourceTree() sourceTree, err := ud.sourceTree()
if err != nil { if err != nil {
return err return err
@@ -648,7 +648,7 @@ func (ud *uiaDriver) TapByTexts(actions ...TapTextAction) error {
return nil return nil
} }
func (ud *uiaDriver) GetDriverResults() []*DriverResult { func (ud *UIA2Driver) GetDriverResults() []*DriverResult {
defer func() { defer func() {
ud.DriverClient.driverResults = nil ud.DriverClient.driverResults = nil
}() }()
+2 -2
View File
@@ -477,7 +477,7 @@ func TestConvertPoints(t *testing.T) {
func TestDriver_ShellInputUnicode(t *testing.T) { func TestDriver_ShellInputUnicode(t *testing.T) {
device, _ := NewAndroidDevice() device, _ := NewAndroidDevice()
driver, err := device.NewAdbDriver() driver, err := NewADBDriver(device)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -530,7 +530,7 @@ func TestTapTexts(t *testing.T) {
func TestRecordVideo(t *testing.T) { func TestRecordVideo(t *testing.T) {
setupAndroidAdbDriver(t) setupAndroidAdbDriver(t)
path, err := driverExt.Driver.(*adbDriver).RecordScreen("", 5*time.Second) path, err := driverExt.Driver.(*ADBDriver).RecordScreen("", 5*time.Second)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
+4
View File
@@ -21,3 +21,7 @@ type IDevice interface {
// Teardown() error // Teardown() error
} }
func NewDriver(device IDevice, opts ...option.DriverOption) (driver IWebDriver, err error) {
return
}
+4 -4
View File
@@ -376,20 +376,20 @@ type DriverExt struct {
} }
func newDriverExt(device IDevice, driver IWebDriver, opts ...option.DriverOption) (dExt *DriverExt, err error) { func newDriverExt(device IDevice, driver IWebDriver, opts ...option.DriverOption) (dExt *DriverExt, err error) {
driverOptions := option.NewDriverOptions(opts...) options := option.NewDriverOptions(opts...)
dExt = &DriverExt{ dExt = &DriverExt{
Device: device, Device: device,
Driver: driver, Driver: driver,
plugin: driverOptions.Plugin, plugin: options.Plugin,
} }
if driverOptions.WithImageService { if options.WithImageService {
if dExt.ImageService, err = newVEDEMImageService(); err != nil { if dExt.ImageService, err = newVEDEMImageService(); err != nil {
return nil, err return nil, err
} }
} }
if driverOptions.WithResultFolder { if options.WithResultFolder {
// create results directory // create results directory
if err = builtin.EnsureFolderExists(config.ResultsPath); err != nil { if err = builtin.EnsureFolderExists(config.ResultsPath); err != nil {
return nil, errors.Wrap(err, "create results directory failed") return nil, errors.Wrap(err, "create results directory failed")
+2 -2
View File
@@ -261,10 +261,10 @@ func (dev *IOSDevice) getAppInfo(packageName string) (appInfo AppInfo, err error
} }
func (dev *IOSDevice) NewDriver(opts ...option.DriverOption) (driverExt *DriverExt, err error) { func (dev *IOSDevice) NewDriver(opts ...option.DriverOption) (driverExt *DriverExt, err error) {
driverOptions := option.NewDriverOptions() options := option.NewDriverOptions()
// init WDA driver // init WDA driver
capabilities := driverOptions.Capabilities capabilities := options.Capabilities
if capabilities == nil { if capabilities == nil {
capabilities = option.NewCapabilities() capabilities = option.NewCapabilities()
capabilities.WithDefaultAlertAction(option.AlertActionAccept) capabilities.WithDefaultAlertAction(option.AlertActionAccept)
+6
View File
@@ -38,6 +38,12 @@ func NewAndroidDeviceConfig(opts ...AndroidDeviceOption) *AndroidDeviceConfig {
type AndroidDeviceOption func(*AndroidDeviceConfig) type AndroidDeviceOption func(*AndroidDeviceConfig)
func WithDriverTypeADB() AndroidDeviceOption {
return func(device *AndroidDeviceConfig) {
device.STUB = false
}
}
func WithSerialNumber(serial string) AndroidDeviceOption { func WithSerialNumber(serial string) AndroidDeviceOption {
return func(device *AndroidDeviceConfig) { return func(device *AndroidDeviceConfig) {
device.SerialNumber = serial device.SerialNumber = serial
-8
View File
@@ -7,14 +7,12 @@ type DriverOptions struct {
Plugin funplugin.IPlugin Plugin funplugin.IPlugin
WithImageService bool WithImageService bool
WithResultFolder bool WithResultFolder bool
WithUIAction bool
} }
func NewDriverOptions(opts ...DriverOption) *DriverOptions { func NewDriverOptions(opts ...DriverOption) *DriverOptions {
driverOptions := &DriverOptions{ driverOptions := &DriverOptions{
WithImageService: true, WithImageService: true,
WithResultFolder: true, WithResultFolder: true,
WithUIAction: true,
} }
for _, option := range opts { for _, option := range opts {
option(driverOptions) option(driverOptions)
@@ -42,12 +40,6 @@ func WithDriverResultFolder(withResultFolder bool) DriverOption {
} }
} }
func WithUIAction(withUIAction bool) DriverOption {
return func(options *DriverOptions) {
options.WithUIAction = withUIAction
}
}
func WithDriverPlugin(plugin funplugin.IPlugin) DriverOption { func WithDriverPlugin(plugin funplugin.IPlugin) DriverOption {
return func(options *DriverOptions) { return func(options *DriverOptions) {
options.Plugin = plugin options.Plugin = plugin