fix: merge

This commit is contained in:
huangbin.beal@163.com
2025-02-19 21:02:57 +08:00
29 changed files with 568 additions and 385 deletions

39
cmd/ios/tunnel.go Normal file
View File

@@ -0,0 +1,39 @@
package ios
import (
"context"
"github.com/danielpaulus/go-ios/ios"
"github.com/httprunner/httprunner/v5/internal/sdk"
"github.com/httprunner/httprunner/v5/pkg/uixt"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"os"
"strings"
"time"
)
var tunnelCmd = &cobra.Command{
Use: "tunnel",
Short: "tunnel start",
RunE: func(cmd *cobra.Command, args []string) (err error) {
startTime := time.Now()
defer func() {
sdk.SendGA4Event("hrp_ios_tunnel", map[string]interface{}{
"args": strings.Join(args, "-"),
"success": err == nil,
"engagement_time_msec": time.Since(startTime).Milliseconds(),
})
}()
ctx := context.TODO()
err = uixt.StartTunnel(ctx, os.TempDir(), ios.HttpApiPort(), true)
if err != nil {
log.Error().Err(err).Msg("failed to start tunnel")
}
<-ctx.Done()
return err
},
}
func init() {
iosRootCmd.AddCommand(tunnelCmd)
}

View File

@@ -5,16 +5,13 @@ import (
"bytes"
"context"
"crypto/hmac"
"crypto/md5"
"crypto/sha256"
"encoding/csv"
builtinJSON "encoding/json"
"fmt"
"io"
"math"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
@@ -23,7 +20,6 @@ import (
"strings"
"time"
"github.com/BurntSushi/locker"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v3"
@@ -382,7 +378,7 @@ func GetCurrentDay() string {
return formattedDate
}
func fileExists(filepath string) bool {
func FileExists(filepath string) bool {
_, err := os.Stat(filepath)
if os.IsNotExist(err) {
return false // 文件不存在
@@ -390,61 +386,6 @@ func fileExists(filepath string) bool {
return err == nil // 文件存在,且没有其他错误
}
func DownloadFileByUrl(fileUrl string) (filePath string, err error) {
// 使用 UUID 生成唯一文件名
cwd, err := os.Getwd()
if err != nil {
return "", err
}
hash := md5.Sum([]byte(fileUrl))
fileName := fmt.Sprintf("%x", hash)
filePath = filepath.Join(cwd, fileName)
locker.Lock(filePath)
defer locker.Unlock(filePath)
if fileExists(filePath) {
return filePath, nil
}
fmt.Printf("Downloading file to %s from URL %s\n", filePath, fileUrl)
// Create an HTTP client with default settings.
client := &http.Client{}
// Build the HTTP GET request.
req, err := http.NewRequest("GET", fileUrl, nil)
if err != nil {
return "", err
}
// Perform the request.
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Check the HTTP status code.
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to download file: %s", resp.Status)
}
// Create the output file.
outFile, err := os.Create(fileName)
if err != nil {
return "", err
}
defer outFile.Close()
// Copy the response body to the file.
_, err = io.Copy(outFile, resp.Body)
if err != nil {
return "", err
}
fmt.Printf("File downloaded successfully: %s\n", fileName)
return filePath, nil
}
func RunCommand(cmdName string, args ...string) error {
cmd := exec.Command(cmdName, args...)
log.Info().Str("command", cmd.String()).Msg("exec command")

View File

@@ -12,6 +12,7 @@ import (
const (
ResultsDirName = "results"
DownloadsDirName = "downloads"
ScreenshotsDirName = "screenshots"
ActionLogDirName = "action_log"
)
@@ -20,6 +21,7 @@ var (
RootDir string
ResultsDir string
ResultsPath string
DownloadsPath string
ScreenShotsPath string
StartTime = time.Now()
StartTimeStr = StartTime.Format("20060102150405")
@@ -36,6 +38,7 @@ func init() {
ResultsDir = filepath.Join(ResultsDirName, StartTimeStr)
ResultsPath = filepath.Join(RootDir, ResultsDir)
DownloadsPath = filepath.Join(RootDir, filepath.Join(DownloadsDirName, StartTimeStr))
ScreenShotsPath = filepath.Join(ResultsPath, ScreenshotsDirName)
ActionLogFilePath = filepath.Join(ResultsDir, ActionLogDirName)
DeviceActionLogFilePath = "/sdcard/Android/data/io.appium.uiautomator2.server/files/hodor"

View File

@@ -1 +1 @@
v5.0.0+2502191055
v5.0.0+2502191738

View File

@@ -30,6 +30,10 @@ func NewUIA2Driver(device *AndroidDevice) (*UIA2Driver, error) {
if err := driver.Setup(); err != nil {
return nil, err
}
// register driver session reset handler
driver.Session.RegisterResetHandler(driver.Setup)
return driver, nil
}
@@ -117,7 +121,8 @@ func (ud *UIA2Driver) DeleteSession() (err error) {
if ud.Session.ID == "" {
return nil
}
if _, err = ud.Session.DELETE("/session", ud.Session.ID); err == nil {
urlStr := fmt.Sprintf("/session/%s", ud.Session.ID)
if _, err = ud.Session.DELETE(urlStr); err == nil {
ud.Session.ID = ""
}
@@ -146,7 +151,8 @@ func (ud *UIA2Driver) Status() (deviceStatus types.DeviceStatus, err error) {
func (ud *UIA2Driver) DeviceInfo() (deviceInfo types.DeviceInfo, err error) {
// register(getHandler, new GetDeviceInfo("/wd/hub/session/:sessionId/appium/device/info"))
var rawResp DriverRawResponse
if rawResp, err = ud.Session.GET("/session", ud.Session.ID, "appium/device/info"); err != nil {
urlStr := fmt.Sprintf("/session/%s/appium/device/info", ud.Session.ID)
if rawResp, err = ud.Session.GET(urlStr); err != nil {
return types.DeviceInfo{}, err
}
reply := new(struct{ Value struct{ types.DeviceInfo } })
@@ -160,7 +166,8 @@ func (ud *UIA2Driver) DeviceInfo() (deviceInfo types.DeviceInfo, err error) {
func (ud *UIA2Driver) BatteryInfo() (batteryInfo types.BatteryInfo, err error) {
// register(getHandler, new GetBatteryInfo("/wd/hub/session/:sessionId/appium/device/battery_info"))
var rawResp DriverRawResponse
if rawResp, err = ud.Session.GET("/session", ud.Session.ID, "appium/device/battery_info"); err != nil {
urlStr := fmt.Sprintf("/session/%s/appium/device/battery_info", ud.Session.ID)
if rawResp, err = ud.Session.GET(urlStr); err != nil {
return types.BatteryInfo{}, err
}
reply := new(struct{ Value struct{ types.BatteryInfo } })
@@ -182,7 +189,8 @@ func (ud *UIA2Driver) WindowSize() (size types.Size, err error) {
}
var rawResp DriverRawResponse
if rawResp, err = ud.Session.GET("/session", ud.Session.ID, "window/:windowHandle/size"); err != nil {
urlStr := fmt.Sprintf("/session/%s/window/:windowHandle/size", ud.Session.ID)
if rawResp, err = ud.Session.GET(urlStr); err != nil {
return types.Size{}, errors.Wrap(err, "get window size failed by UIA2 request")
}
reply := new(struct{ Value struct{ types.Size } })
@@ -208,7 +216,8 @@ func (ud *UIA2Driver) WindowSize() (size types.Size, err error) {
// Back simulates a short press on the BACK button.
func (ud *UIA2Driver) Back() (err error) {
// register(postHandler, new PressBack("/wd/hub/session/:sessionId/back"))
_, err = ud.Session.POST(nil, "/session", ud.Session.ID, "back")
urlStr := fmt.Sprintf("/session/%s/back", ud.Session.ID)
_, err = ud.Session.POST(nil, urlStr)
return
}
@@ -223,14 +232,16 @@ func (ud *UIA2Driver) PressKeyCodes(keyCode KeyCode, metaState KeyMeta, flags ..
if len(flags) != 0 {
data["flags"] = flags[0]
}
_, err = ud.Session.POST(data, "/session", ud.Session.ID, "appium/device/press_keycode")
urlStr := fmt.Sprintf("/session/%s/appium/device/press_keycode", ud.Session.ID)
_, err = ud.Session.POST(data, urlStr)
return
}
func (ud *UIA2Driver) Orientation() (orientation types.Orientation, err error) {
// [[FBRoute GET:@"/orientation"] respondWithTarget:self action:@selector(handleGetOrientation:)]
var rawResp DriverRawResponse
if rawResp, err = ud.Session.GET("/session", ud.Session.ID, "/orientation"); err != nil {
urlStr := fmt.Sprintf("/session/%s/orientation", ud.Session.ID)
if rawResp, err = ud.Session.GET(urlStr); err != nil {
return "", err
}
reply := new(struct{ Value types.Orientation })
@@ -266,7 +277,8 @@ func (ud *UIA2Driver) DoubleTapXY(x, y float64, opts ...option.ActionOption) err
},
}
_, err = ud.Session.POST(data, "/session", ud.Session.ID, "actions/tap")
urlStr := fmt.Sprintf("/session/%s/actions/tap", ud.Session.ID)
_, err = ud.Session.POST(data, urlStr)
return err
}
@@ -305,7 +317,8 @@ func (ud *UIA2Driver) TapAbsXY(x, y float64, opts ...option.ActionOption) error
}
option.MergeOptions(data, opts...)
_, err := ud.Session.POST(data, "/session", ud.Session.ID, "actions/tap")
urlStr := fmt.Sprintf("/session/%s/actions/tap", ud.Session.ID)
_, err := ud.Session.POST(data, urlStr)
return err
}
@@ -324,7 +337,8 @@ func (ud *UIA2Driver) TouchAndHold(x, y float64, opts ...option.ActionOption) (e
"duration": int(duration * 1000),
},
}
_, err = ud.Session.POST(data, "/session", ud.Session.ID, "touch/longclick")
urlStr := fmt.Sprintf("/session/%s/touch/longclick", ud.Session.ID)
_, err = ud.Session.POST(data, urlStr)
return
}
@@ -350,7 +364,8 @@ func (ud *UIA2Driver) Drag(fromX, fromY, toX, toY float64, opts ...option.Action
option.MergeOptions(data, opts...)
// register(postHandler, new Drag("/wd/hub/session/:sessionId/touch/drag"))
_, err = ud.Session.POST(data, "/session", ud.Session.ID, "touch/drag")
urlStr := fmt.Sprintf("/session/%s/touch/drag", ud.Session.ID)
_, err = ud.Session.POST(data, urlStr)
return err
}
@@ -391,7 +406,8 @@ func (ud *UIA2Driver) Swipe(fromX, fromY, toX, toY float64, opts ...option.Actio
}
option.MergeOptions(data, opts...)
_, err = ud.Session.POST(data, "/session", ud.Session.ID, "actions/swipe")
urlStr := fmt.Sprintf("/session/%s/actions/swipe", ud.Session.ID)
_, err = ud.Session.POST(data, urlStr)
return err
}
@@ -409,7 +425,8 @@ func (ud *UIA2Driver) SetPasteboard(contentType types.PasteboardType, content st
"content": base64.StdEncoding.EncodeToString([]byte(content)),
}
// register(postHandler, new SetClipboard("/wd/hub/session/:sessionId/appium/device/set_clipboard"))
_, err = ud.Session.POST(data, "/session", ud.Session.ID, "appium/device/set_clipboard")
urlStr := fmt.Sprintf("/session/%s/appium/device/set_clipboard", ud.Session.ID)
_, err = ud.Session.POST(data, urlStr)
return
}
@@ -422,7 +439,8 @@ func (ud *UIA2Driver) GetPasteboard(contentType types.PasteboardType) (raw *byte
"contentType": contentType[0],
}
var rawResp DriverRawResponse
if rawResp, err = ud.Session.POST(data, "/session", ud.Session.ID, "appium/device/get_clipboard"); err != nil {
urlStr := fmt.Sprintf("/session/%s/appium/device/get_clipboard", ud.Session.ID)
if rawResp, err = ud.Session.POST(data, urlStr); err != nil {
return
}
reply := new(struct{ Value string })
@@ -451,7 +469,8 @@ func (ud *UIA2Driver) Input(text string, opts ...option.ActionOption) (err error
"text": text,
}
option.MergeOptions(data, opts...)
_, err = ud.Session.POST(data, "/session", ud.Session.ID, "/keys")
urlStr := fmt.Sprintf("/session/%s/keys", ud.Session.ID)
_, err = ud.Session.POST(data, urlStr)
return
}
@@ -506,14 +525,16 @@ func (ud *UIA2Driver) SendActionKey(text string, opts ...option.ActionOption) (e
}
option.MergeOptions(data, opts...)
_, err = ud.Session.POST(data, "/session", ud.Session.ID, "/actions/keys")
urlStr := fmt.Sprintf("/session/%s/actions/keys", ud.Session.ID)
_, err = ud.Session.POST(data, urlStr)
return
}
func (ud *UIA2Driver) Rotation() (rotation types.Rotation, err error) {
// register(getHandler, new GetRotation("/wd/hub/session/:sessionId/rotation"))
var rawResp DriverRawResponse
if rawResp, err = ud.Session.GET("/session", ud.Session.ID, "rotation"); err != nil {
urlStr := fmt.Sprintf("/session/%s/rotation", ud.Session.ID)
if rawResp, err = ud.Session.GET(urlStr); err != nil {
return types.Rotation{}, err
}
reply := new(struct{ Value types.Rotation })
@@ -534,7 +555,8 @@ func (ud *UIA2Driver) ScreenShot(opts ...option.ActionOption) (raw *bytes.Buffer
func (ud *UIA2Driver) Source(srcOpt ...option.SourceOption) (source string, err error) {
// register(getHandler, new Source("/wd/hub/session/:sessionId/source"))
var rawResp DriverRawResponse
if rawResp, err = ud.Session.GET("/session", ud.Session.ID, "source"); err != nil {
urlStr := fmt.Sprintf("/session/%s/source", ud.Session.ID)
if rawResp, err = ud.Session.GET(urlStr); err != nil {
return "", err
}
reply := new(struct{ Value string })

View File

@@ -96,3 +96,14 @@ type XTDriver struct {
// cache screenshot results
screenResults []*ScreenResult
}
func (dExt *XTDriver) GetIDriver() IDriver {
return dExt.IDriver
}
type IXTDriver interface {
IDriver
GetIDriver() IDriver
GetScreenResult(opts ...option.ActionOption) (screenResult *ScreenResult, err error)
DoAction(action MobileAction) (err error)
}

View File

@@ -45,6 +45,11 @@ func NewStubAndroidDriver(dev *uixt.AndroidDevice) (*StubAndroidDriver, error) {
ADBDriver: adbDriver,
}
// setup driver
if err := driver.Setup(); err != nil {
return nil, err
}
return driver, nil
}
@@ -55,10 +60,6 @@ func (sad *StubAndroidDriver) Setup() error {
fmt.Sprintf("forward port %d->%s failed: %v",
socketLocalPort, StubSocketName, err))
}
err = sad.Session.SetupPortForward(socketLocalPort)
if err != nil {
return err
}
douyinLocalPort, err := sad.Device.Forward(AndroidDouyinPort)
if err != nil {
@@ -272,11 +273,6 @@ func (sad *StubAndroidDriver) LogoutNoneUI(packageName string) error {
log.Err(err).Msgf("%v", res)
return err
}
fmt.Printf("%v", resp)
if err != nil {
return err
}
time.Sleep(3 * time.Second)
return nil
}

View File

@@ -4,7 +4,6 @@ import (
"fmt"
"time"
"github.com/httprunner/httprunner/v5/internal/builtin"
"github.com/httprunner/httprunner/v5/pkg/uixt"
"github.com/httprunner/httprunner/v5/pkg/uixt/ai"
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
@@ -34,7 +33,7 @@ type XTDriver struct {
}
func (dExt *XTDriver) InstallByUrl(url string, opts ...option.InstallOption) error {
appPath, err := builtin.DownloadFileByUrl(url)
appPath, err := uixt.DownloadFileByUrl(url)
if err != nil {
return err
}

View File

@@ -1,9 +1,11 @@
package driver_ext
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
"time"
"github.com/httprunner/httprunner/v5/code"
@@ -16,8 +18,8 @@ import (
)
type StubIOSDriver struct {
Session *uixt.DriverSession
*uixt.WDADriver
timeout time.Duration
douyinUrlPrefix string
douyinLiteUrlPrefix string
@@ -30,6 +32,9 @@ const (
)
func NewStubIOSDriver(dev *uixt.IOSDevice) (*StubIOSDriver, error) {
// lazy setup WDA
dev.Options.LazySetup = true
wdaDriver, err := uixt.NewWDADriver(dev)
if err != nil {
return nil, err
@@ -37,6 +42,7 @@ func NewStubIOSDriver(dev *uixt.IOSDevice) (*StubIOSDriver, error) {
driver := &StubIOSDriver{
WDADriver: wdaDriver,
timeout: 10 * time.Second,
Session: uixt.NewDriverSession(),
}
// setup driver
@@ -52,10 +58,6 @@ func (s *StubIOSDriver) Setup() error {
if err != nil {
return err
}
err = s.Session.SetupPortForward(localPort)
if err != nil {
return err
}
s.Session.SetBaseURL(fmt.Sprintf("http://127.0.0.1:%d", localPort))
localDouyinPort, err := builtin.GetFreePort()
@@ -104,7 +106,7 @@ func (s *StubIOSDriver) Source(srcOpt ...option.SourceOption) (string, error) {
return string(resp), nil
}
func (s *StubIOSDriver) OpenUrl(urlStr string, options ...option.ActionOption) (err error) {
func (s *StubIOSDriver) OpenUrl(urlStr string, opts ...option.ActionOption) (err error) {
targetUrl := fmt.Sprintf("/openURL?url=%s", url.QueryEscape(urlStr))
_, err = s.Session.GET(targetUrl)
if err != nil {
@@ -152,17 +154,12 @@ func (s *StubIOSDriver) LoginDouyin(packageName, phoneNumber string, captcha, pa
} else {
return info, fmt.Errorf("password and capcha is empty")
}
bsJSON, err := json.Marshal(params)
if err != nil {
return info, err
}
urlPrefix, err := s.getUrlPrefix(packageName)
if err != nil {
return info, err
}
fullUrl := urlPrefix + "/host/login/account/" + urlPrefix
resp, err := s.Session.POST(bsJSON, fullUrl)
fullUrl := urlPrefix + "/host/login/account/"
resp, err := s.Session.POST(params, fullUrl)
if err != nil {
return info, err
}
@@ -219,11 +216,7 @@ func (s *StubIOSDriver) EnableDevtool(packageName string, enable bool) (err erro
params := map[string]interface{}{
"enable": enable,
}
bsJSON, err := json.Marshal(params)
if err != nil {
return err
}
resp, err := s.Session.POST(bsJSON, fullUrl)
resp, err := s.Session.POST(params, fullUrl)
if err != nil {
return err
}
@@ -278,3 +271,10 @@ func (s *StubIOSDriver) getUrlPrefix(packageName string) (urlPrefix string, err
}
return urlPrefix, nil
}
func (s *StubIOSDriver) ScreenShot(opts ...option.ActionOption) (*bytes.Buffer, error) {
if os.Getenv("WINGS_LOCAL") == "true" {
return s.Device.ScreenShot()
}
return s.WDADriver.ScreenShot()
}

View File

@@ -0,0 +1,35 @@
package driver_ext
import (
"github.com/httprunner/httprunner/v5/pkg/uixt"
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
"testing"
)
var (
iOSStubDriver *StubIOSDriver
)
func checkErr(t *testing.T, err error, msg ...string) {
if err != nil {
if len(msg) == 0 {
t.Fatal(err)
} else {
t.Fatal(msg, err)
}
}
}
func setupIOSStubDriver(t *testing.T) {
iOSDevice, err := uixt.NewIOSDevice(option.WithWDAPort(8700), option.WithWDAMjpegPort(8800), option.WithResetHomeOnStartup(false))
checkErr(t, err)
iOSStubDriver, err = NewStubIOSDriver(iOSDevice)
checkErr(t, err)
}
func TestIOSStubDriver_LoginNoneUI(t *testing.T) {
setupIOSStubDriver(t)
info, err := iOSStubDriver.LoginNoneUI("com.ss.iphone.ugc.AwemeInhouse", "12343418541", "", "im112233")
checkErr(t, err)
t.Logf("login info: %+v", info)
}

View File

@@ -20,7 +20,6 @@ import (
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v5/internal/json"
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
)
type Attachments map[string]interface{}
@@ -61,38 +60,13 @@ type DriverSession struct {
timeout time.Duration
maxRetry int
// used to reset driver session when request failed
resetFn func() error
// cache driver request and response
requests []*DriverRequests
}
func (s *DriverSession) Init(capabilities option.Capabilities) (err error) {
data := make(map[string]interface{})
if len(capabilities) == 0 {
data["capabilities"] = make(map[string]interface{})
} else {
data["capabilities"] = map[string]interface{}{"alwaysMatch": capabilities}
}
var rawResp DriverRawResponse
if rawResp, err = s.POST(data, "/session"); err != nil {
return err
}
reply := new(struct{ Value struct{ SessionId string } })
if err = json.Unmarshal(rawResp, reply); err != nil {
return err
}
s.ID = reply.Value.SessionId
// WDA
// sessionInfo, err := rawResp.ValueConvertToSessionInfo()
// if err != nil {
// return err
// }
// // update session ID
// wd.Session.ID = sessionInfo.ID
return nil
}
func (s *DriverSession) Reset() {
s.requests = make([]*DriverRequests, 0)
}
@@ -101,6 +75,10 @@ func (s *DriverSession) SetBaseURL(baseUrl string) {
s.baseUrl = baseUrl
}
func (s *DriverSession) RegisterResetHandler(fn func() error) {
s.resetFn = fn
}
func (s *DriverSession) addRequestResult(driverResult *DriverRequests) {
s.requests = append(s.requests, driverResult)
}
@@ -109,8 +87,8 @@ func (s *DriverSession) History() []*DriverRequests {
return s.requests
}
func (s *DriverSession) concatURL(elem ...string) (string, error) {
if len(elem) == 0 {
func (s *DriverSession) concatURL(urlStr string) (string, error) {
if urlStr == "" || urlStr == "/" {
if s.baseUrl == "" {
return "", fmt.Errorf("base URL is empty")
}
@@ -118,14 +96,11 @@ func (s *DriverSession) concatURL(elem ...string) (string, error) {
}
// 处理完整 URL
if strings.HasPrefix(elem[0], "http://") || strings.HasPrefix(elem[0], "https://") {
u, err := url.Parse(elem[0])
if strings.HasPrefix(urlStr, "http://") || strings.HasPrefix(urlStr, "https://") {
u, err := url.Parse(urlStr)
if err != nil {
return "", fmt.Errorf("failed to parse URL: %w", err)
}
if len(elem) > 1 {
u.Path = path.Join(u.Path, path.Join(elem[1:]...))
}
return u.String(), nil
}
@@ -138,74 +113,70 @@ func (s *DriverSession) concatURL(elem ...string) (string, error) {
return "", fmt.Errorf("failed to parse base URL: %w", err)
}
// 保存原始查询参数
baseQuery := u.Query()
// 处理路径和查询参数
var paths []string
for i, e := range elem {
if i == len(elem)-1 {
// 处理最后一个元素的查询参数
parts := strings.SplitN(e, "?", 2)
paths = append(paths, parts[0])
if len(parts) > 1 {
newQuery, err := url.ParseQuery(parts[1])
if err != nil {
return "", fmt.Errorf("failed to parse query params: %w", err)
}
// 合并查询参数
for k, v := range newQuery {
baseQuery[k] = v
}
}
} else {
paths = append(paths, e)
parts := strings.SplitN(urlStr, "?", 2)
u.Path = path.Join(u.Path, parts[0])
if len(parts) > 1 {
query, err := url.ParseQuery(parts[1])
if err != nil {
return "", fmt.Errorf("failed to parse query params: %w", err)
}
}
// 合并路径
u.Path = path.Join(append([]string{u.Path}, paths...)...)
// 设置合并后的查询参数
if len(baseQuery) > 0 {
u.RawQuery = baseQuery.Encode()
u.RawQuery = query.Encode()
}
return u.String(), nil
}
func (s *DriverSession) GET(pathElem ...string) (rawResp DriverRawResponse, err error) {
urlStr, err := s.concatURL(pathElem...)
if err != nil {
return nil, err
}
return s.Request(http.MethodGet, urlStr, nil)
func (s *DriverSession) GET(urlStr string) (rawResp DriverRawResponse, err error) {
return s.RequestWithRetry(http.MethodGet, urlStr, nil)
}
func (s *DriverSession) POST(data interface{}, pathElem ...string) (rawResp DriverRawResponse, err error) {
urlStr, err := s.concatURL(pathElem...)
if err != nil {
return nil, err
}
func (s *DriverSession) POST(data interface{}, urlStr string) (rawResp DriverRawResponse, err error) {
var bsJSON []byte = nil
if data != nil {
if bsJSON, err = json.Marshal(data); err != nil {
return nil, err
}
}
return s.Request(http.MethodPost, urlStr, bsJSON)
return s.RequestWithRetry(http.MethodPost, urlStr, bsJSON)
}
func (s *DriverSession) DELETE(pathElem ...string) (rawResp DriverRawResponse, err error) {
urlStr, err := s.concatURL(pathElem...)
func (s *DriverSession) DELETE(urlStr string) (rawResp DriverRawResponse, err error) {
return s.RequestWithRetry(http.MethodDelete, urlStr, nil)
}
func (s *DriverSession) RequestWithRetry(method string, urlStr string, rawBody []byte) (
rawResp DriverRawResponse, err error) {
for count := 1; count <= s.maxRetry; count++ {
rawResp, err = s.Request(method, urlStr, rawBody)
if err == nil {
return
}
time.Sleep(3 * time.Second)
if s.resetFn != nil {
log.Warn().Msg("reset driver session")
if err2 := s.resetFn(); err2 != nil {
log.Error().Err(err2).Msgf(
"failed to reset session, try count %v", count)
} else {
log.Info().Msgf(
"reset session success, try count %v", count)
}
}
}
return
}
func (s *DriverSession) Request(method string, urlStr string, rawBody []byte) (
rawResp DriverRawResponse, err error) {
// concat url with base url
rawURL, err := s.concatURL(urlStr)
if err != nil {
return nil, err
}
return s.Request(http.MethodDelete, urlStr, nil)
}
func (s *DriverSession) Request(method string, rawURL string, rawBody []byte) (
rawResp DriverRawResponse, err error) {
driverResult := &DriverRequests{
RequestMethod: method,
RequestUrl: rawURL,
@@ -285,30 +256,6 @@ func (s *DriverSession) Request(method string, rawURL string, rawBody []byte) (
return
}
// TODO: FIXME
func (s *DriverSession) RequestWithRetry(method string, rawURL string, rawBody []byte) (
rawResp DriverRawResponse, err error) {
for count := 1; count <= s.maxRetry; count++ {
rawResp, err = s.Request(method, rawURL, rawBody)
if err == nil {
return
}
time.Sleep(3 * time.Second)
oldSessionID := s.ID
if err2 := s.Init(nil); err2 != nil {
log.Error().Err(err2).Msgf(
"failed to reset session, try count %v", count)
continue
}
log.Debug().Str("new session", s.ID).Str("old session", oldSessionID).Msgf(
"reset session successfully, try count %v", count)
if oldSessionID != "" {
rawURL = strings.Replace(rawURL, oldSessionID, s.ID, 1)
}
}
return
}
func (s *DriverSession) SetupPortForward(localPort int) error {
conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", localPort))
if err != nil {

View File

@@ -10,82 +10,101 @@ func TestDriverSession_concatURL(t *testing.T) {
tests := []struct {
name string
baseUrl string
elem []string
urlStr string
want string
wantErr bool
errMsg string
}{
{
name: "empty elements with empty base url",
name: "empty url with empty base url",
baseUrl: "",
elem: []string{},
urlStr: "",
wantErr: true,
errMsg: "base URL is empty",
},
{
name: "empty elements with valid base url",
name: "empty url with valid base url",
baseUrl: "http://localhost:8080",
elem: []string{},
urlStr: "",
want: "http://localhost:8080",
},
{
name: "absolute url in first element",
name: "root path with empty base url",
baseUrl: "",
urlStr: "/",
wantErr: true,
errMsg: "base URL is empty",
},
{
name: "root path with valid base url",
baseUrl: "http://localhost:8080",
elem: []string{"https://example.com/api", "users"},
want: "https://example.com/api/users",
urlStr: "/",
want: "http://localhost:8080",
},
{
name: "absolute http url",
baseUrl: "http://localhost:8080",
urlStr: "http://example.com/api",
want: "http://example.com/api",
},
{
name: "absolute https url",
baseUrl: "http://localhost:8080",
urlStr: "https://example.com/api",
want: "https://example.com/api",
},
{
name: "invalid absolute url",
baseUrl: "http://localhost:8080",
elem: []string{"http://[invalid-url", "users"},
urlStr: "http://[invalid-url",
wantErr: true,
errMsg: "failed to parse URL",
},
{
name: "relative path with empty base url",
baseUrl: "",
elem: []string{"api", "users"},
urlStr: "api/users",
wantErr: true,
errMsg: "base URL is empty",
},
{
name: "relative path with invalid base url",
baseUrl: "http://[invalid-url",
elem: []string{"api", "users"},
urlStr: "api/users",
wantErr: true,
errMsg: "failed to parse base URL",
},
{
name: "relative path with valid base url",
baseUrl: "http://localhost:8080",
urlStr: "api/users",
want: "http://localhost:8080/api/users",
},
{
name: "relative path with query params",
baseUrl: "http://localhost:8080",
elem: []string{"api", "users?id=1&name=test"},
urlStr: "api/users?id=1&name=test",
want: "http://localhost:8080/api/users?id=1&name=test",
},
{
name: "base url with query params",
baseUrl: "http://localhost:8080?token=123",
elem: []string{"api", "users?id=1"},
want: "http://localhost:8080/api/users?id=1&token=123",
urlStr: "api/users?id=1",
want: "http://localhost:8080/api/users?id=1",
},
{
name: "invalid query params",
baseUrl: "http://localhost:8080",
elem: []string{"api", "users?id=%invalid"},
urlStr: "api/users?id=%invalid",
wantErr: true,
errMsg: "failed to parse query params",
},
{
name: "multiple path segments",
baseUrl: "http://localhost:8080",
elem: []string{"api", "v1", "users", "profile"},
want: "http://localhost:8080/api/v1/users/profile",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &DriverSession{baseUrl: tt.baseUrl}
got, err := s.concatURL(tt.elem...)
got, err := s.concatURL(tt.urlStr)
if tt.wantErr {
assert.Error(t, err)

View File

@@ -1,9 +1,17 @@
package uixt
import (
"crypto/md5"
"fmt"
"github.com/BurntSushi/locker"
"github.com/httprunner/httprunner/v5/internal/builtin"
"github.com/httprunner/httprunner/v5/internal/config"
"io"
"math"
"math/rand/v2"
"net/http"
"os"
"path/filepath"
"time"
"github.com/pkg/errors"
@@ -259,3 +267,53 @@ func sleepStrict(startTime time.Time, strictMilliseconds int64) {
Msg("sleep remaining duration time")
time.Sleep(time.Duration(dur) * time.Millisecond)
}
func DownloadFileByUrl(fileUrl string) (filePath string, err error) {
hash := md5.Sum([]byte(fileUrl))
fileName := fmt.Sprintf("%x", hash)
filePath = filepath.Join(config.DownloadsPath, fileName)
locker.Lock(filePath)
defer locker.Unlock(filePath)
if builtin.FileExists(filePath) {
return filePath, nil
}
fmt.Printf("Downloading file to %s from URL %s\n", filePath, fileUrl)
// Create an HTTP client with default settings.
client := &http.Client{}
// Build the HTTP GET request.
req, err := http.NewRequest("GET", fileUrl, nil)
if err != nil {
return "", err
}
// Perform the request.
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Check the HTTP status code.
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to download file: %s", resp.Status)
}
// Create the output file.
outFile, err := os.Create(fileName)
if err != nil {
return "", err
}
defer outFile.Close()
// Copy the response body to the file.
_, err = io.Copy(outFile, resp.Body)
if err != nil {
return "", err
}
fmt.Printf("File downloaded successfully: %s\n", fileName)
return filePath, nil
}

View File

@@ -1,6 +1,7 @@
package uixt
import (
"bytes"
"context"
"encoding/json"
"fmt"
@@ -27,7 +28,7 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/types"
)
func StartTunnel(recordsPath string, tunnelInfoPort int, userspaceTUN bool) (err error) {
func StartTunnel(ctx context.Context, recordsPath string, tunnelInfoPort int, userspaceTUN bool) (err error) {
pm, err := tunnel.NewPairRecordManager(recordsPath)
if err != nil {
return err
@@ -37,7 +38,7 @@ func StartTunnel(recordsPath string, tunnelInfoPort int, userspaceTUN bool) (err
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
err := tm.UpdateTunnels(context.Background())
err := tm.UpdateTunnels(ctx)
if err != nil {
log.Error().Err(err).Msg("failed to update tunnels")
}
@@ -61,7 +62,7 @@ func RebootTunnel() (err error) {
if tunnelManager != nil {
_ = tunnelManager.Close()
}
return StartTunnel(os.TempDir(), ios.HttpApiPort(), true)
return StartTunnel(context.Background(), os.TempDir(), ios.HttpApiPort(), true)
}
func NewIOSDevice(opts ...option.IOSDeviceOption) (device *IOSDevice, err error) {
@@ -166,6 +167,28 @@ func (dev *IOSDevice) Setup() error {
}
}
if version.GreaterThan(semver.MustParse("17.4.0")) {
info, err := tunnel.TunnelInfoForDevice(dev.DeviceEntry.Properties.SerialNumber, ios.HttpApiHost(), ios.HttpApiPort())
if err != nil {
return err
}
dev.DeviceEntry.UserspaceTUNPort = info.UserspaceTUNPort
dev.DeviceEntry.UserspaceTUN = info.UserspaceTUN
rsdService, err := ios.NewWithAddrPortDevice(info.Address, info.RsdPort, dev.DeviceEntry)
defer rsdService.Close()
rsdProvider, err := rsdService.Handshake()
if err != nil {
return err
}
device, err := ios.GetDeviceWithAddress(dev.DeviceEntry.Properties.SerialNumber, info.Address, rsdProvider)
if err != nil {
return err
}
device.UserspaceTUN = dev.DeviceEntry.UserspaceTUN
device.UserspaceTUNPort = dev.DeviceEntry.UserspaceTUNPort
dev.DeviceEntry = device
}
return nil
}
@@ -326,6 +349,22 @@ func (dev *IOSDevice) ListApps(appType ApplicationType) (apps []installationprox
return apps, nil
}
func (dev *IOSDevice) ScreenShot() (*bytes.Buffer, error) {
screenshotService, err := instruments.NewScreenshotService(dev.DeviceEntry)
if err != nil {
log.Error().Err(err).Msg("Starting screenshot service failed")
return nil, err
}
defer screenshotService.Close()
imageBytes, err := screenshotService.TakeScreenshot()
if err != nil {
log.Error().Err(err).Msg("failed to task screenshot")
return nil, err
}
return bytes.NewBuffer(imageBytes), nil
}
func (dev *IOSDevice) GetAppInfo(packageName string) (appInfo installationproxy.AppInfo, err error) {
svc, _ := installationproxy.New(dev.DeviceEntry)
defer svc.Close()

View File

@@ -37,11 +37,16 @@ func NewWDADriver(device *IOSDevice) (*WDADriver, error) {
Session: NewDriverSession(),
}
// setup driver
if err := driver.Setup(); err != nil {
return nil, err
if !device.Options.LazySetup {
// setup driver
if err := driver.Setup(); err != nil {
return nil, err
}
}
// register driver session reset handler
driver.Session.RegisterResetHandler(driver.Setup)
return driver, nil
}
@@ -182,7 +187,8 @@ func (wd *WDADriver) DeleteSession() (err error) {
}
// [[FBRoute DELETE:@""] respondWithTarget:self action:@selector(handleDeleteSession:)]
_, err = wd.Session.DELETE("/session", wd.Session.ID)
urlStr := fmt.Sprintf("/session/%s", wd.Session.ID)
_, err = wd.Session.DELETE(urlStr)
wd.Session.ID = ""
wd.Session.client.CloseIdleConnections()
return
@@ -211,7 +217,8 @@ func (wd *WDADriver) DeviceInfo() (deviceInfo types.DeviceInfo, err error) {
// [[FBRoute GET:@"/wda/device/info"] respondWithTarget:self action:@selector(handleGetDeviceInfo:)]
// [[FBRoute GET:@"/wda/device/info"].withoutSession
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/wda/device/info"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/device/info", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return types.DeviceInfo{}, err
}
reply := new(struct{ Value struct{ types.DeviceInfo } })
@@ -226,7 +233,8 @@ func (wd *WDADriver) Location() (location types.Location, err error) {
// [[FBRoute GET:@"/wda/device/location"] respondWithTarget:self action:@selector(handleGetLocation:)]
// [[FBRoute GET:@"/wda/device/location"].withoutSession
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/wda/device/location"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/device/location", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return types.Location{}, err
}
reply := new(struct{ Value struct{ types.Location } })
@@ -240,7 +248,8 @@ func (wd *WDADriver) Location() (location types.Location, err error) {
func (wd *WDADriver) BatteryInfo() (batteryInfo types.BatteryInfo, err error) {
// [[FBRoute GET:@"/wda/batteryInfo"] respondWithTarget:self action:@selector(handleGetBatteryInfo:)]
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/wda/batteryInfo"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/batteryInfo", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return types.BatteryInfo{}, err
}
reply := new(struct{ Value struct{ types.BatteryInfo } })
@@ -259,7 +268,8 @@ func (wd *WDADriver) WindowSize() (size types.Size, err error) {
}
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/window/size"); err != nil {
urlStr := fmt.Sprintf("/session/%s/window/size", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return types.Size{}, errors.Wrap(err, "get window size failed by WDA request")
}
reply := new(struct{ Value struct{ types.Size } })
@@ -298,7 +308,8 @@ type Screen struct {
func (wd *WDADriver) Screen() (screen Screen, err error) {
// [[FBRoute GET:@"/wda/screen"] respondWithTarget:self action:@selector(handleGetScreen:)]
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/wda/screen"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/screen", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return Screen{}, err
}
reply := new(struct{ Value struct{ Screen } })
@@ -312,7 +323,8 @@ func (wd *WDADriver) Screen() (screen Screen, err error) {
func (wd *WDADriver) ScreenShot(opts ...option.ActionOption) (raw *bytes.Buffer, err error) {
// [[FBRoute GET:@"/screenshot"] respondWithTarget:self action:@selector(handleGetScreenshot:)]
// [[FBRoute GET:@"/screenshot"].withoutSession respondWithTarget:self action:@selector(handleGetScreenshot:)]
rawResp, err := wd.Session.GET("/session", wd.Session.ID, "/screenshot")
urlStr := fmt.Sprintf("/session/%s/screenshot", wd.Session.ID)
rawResp, err := wd.Session.GET(urlStr)
if err != nil {
return nil, errors.Wrap(code.DeviceScreenShotError,
fmt.Sprintf("WDA screenshot failed %v", err))
@@ -345,7 +357,8 @@ func (wd *WDADriver) ActiveAppInfo() (info types.AppInfo, err error) {
// [[FBRoute GET:@"/wda/activeAppInfo"] respondWithTarget:self action:@selector(handleActiveAppInfo:)]
// [[FBRoute GET:@"/wda/activeAppInfo"].withoutSession
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/wda/activeAppInfo"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/activeAppInfo", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return types.AppInfo{}, err
}
reply := new(struct{ Value struct{ types.AppInfo } })
@@ -359,7 +372,8 @@ func (wd *WDADriver) ActiveAppInfo() (info types.AppInfo, err error) {
func (wd *WDADriver) ActiveAppsList() (appsList []types.AppBaseInfo, err error) {
// [[FBRoute GET:@"/wda/apps/list"] respondWithTarget:self action:@selector(handleGetActiveAppsList:)]
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/wda/apps/list"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/apps/list", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return nil, err
}
reply := new(struct{ Value []types.AppBaseInfo })
@@ -374,7 +388,8 @@ func (wd *WDADriver) AppState(bundleId string) (runState types.AppState, err err
// [[FBRoute POST:@"/wda/apps/state"] respondWithTarget:self action:@selector(handleSessionAppState:)]
data := map[string]interface{}{"bundleId": bundleId}
var rawResp DriverRawResponse
if rawResp, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/apps/state"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/apps/state", wd.Session.ID)
if rawResp, err = wd.Session.POST(data, urlStr); err != nil {
return 0, err
}
reply := new(struct{ Value types.AppState })
@@ -390,7 +405,8 @@ func (wd *WDADriver) IsLocked() (locked bool, err error) {
// [[FBRoute GET:@"/wda/locked"] respondWithTarget:self action:@selector(handleIsLocked:)]
// [[FBRoute GET:@"/wda/locked"].withoutSession
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/wda/locked"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/locked", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return false, err
}
if locked, err = rawResp.ValueConvertToBool(); err != nil {
@@ -402,14 +418,16 @@ func (wd *WDADriver) IsLocked() (locked bool, err error) {
func (wd *WDADriver) Unlock() (err error) {
// [[FBRoute POST:@"/wda/unlock"] respondWithTarget:self action:@selector(handleUnlock:)]
// [[FBRoute POST:@"/wda/unlock"].withoutSession
_, err = wd.Session.POST(nil, "/session", wd.Session.ID, "/wda/unlock")
urlStr := fmt.Sprintf("/session/%s/wda/unlock", wd.Session.ID)
_, err = wd.Session.POST(nil, urlStr)
return
}
func (wd *WDADriver) Lock() (err error) {
// [[FBRoute POST:@"/wda/lock"] respondWithTarget:self action:@selector(handleLock:)]
// [[FBRoute POST:@"/wda/lock"].withoutSession
_, err = wd.Session.POST(nil, "/session", wd.Session.ID, "/wda/lock")
urlStr := fmt.Sprintf("/session/%s/wda/lock", wd.Session.ID)
_, err = wd.Session.POST(nil, urlStr)
return
}
@@ -423,7 +441,8 @@ func (wd *WDADriver) AlertText() (text string, err error) {
// [[FBRoute GET:@"/alert/text"] respondWithTarget:self action:@selector(handleAlertGetTextCommand:)]
// [[FBRoute GET:@"/alert/text"].withoutSession
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/alert/text"); err != nil {
urlStr := fmt.Sprintf("/session/%s/alert/text", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return "", err
}
if text, err = rawResp.ValueConvertToString(); err != nil {
@@ -435,7 +454,8 @@ func (wd *WDADriver) AlertText() (text string, err error) {
func (wd *WDADriver) AlertButtons() (btnLabels []string, err error) {
// [[FBRoute GET:@"/wda/alert/buttons"] respondWithTarget:self action:@selector(handleGetAlertButtonsCommand:)]
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/wda/alert/buttons"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/alert/buttons", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return nil, err
}
reply := new(struct{ Value []string })
@@ -471,7 +491,8 @@ func (wd *WDADriver) AlertDismiss(label ...string) (err error) {
func (wd *WDADriver) AlertSendKeys(text string) (err error) {
// [[FBRoute POST:@"/alert/text"] respondWithTarget:self action:@selector(handleAlertSetTextCommand:)]
data := map[string]interface{}{"value": strings.Split(text, "")}
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/alert/text")
urlStr := fmt.Sprintf("/session/%s/alert/text", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
return
}
@@ -482,7 +503,8 @@ func (wd *WDADriver) AppLaunch(bundleId string) (err error) {
data["environment"] = map[string]interface{}{
"SHOW_EXPLORER": "NO",
}
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/apps/launch")
urlStr := fmt.Sprintf("/session/%s/wda/apps/launch", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
if err != nil {
return errors.Wrap(code.MobileUILaunchAppError,
fmt.Sprintf("wda launch failed: %v", err))
@@ -505,7 +527,8 @@ func (wd *WDADriver) AppTerminate(bundleId string) (successful bool, err error)
// [[FBRoute POST:@"/wda/apps/terminate"] respondWithTarget:self action:@selector(handleSessionAppTerminate:)]
data := map[string]interface{}{"bundleId": bundleId}
var rawResp DriverRawResponse
if rawResp, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/apps/terminate"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/apps/terminate", wd.Session.ID)
if rawResp, err = wd.Session.POST(data, urlStr); err != nil {
return false, err
}
if successful, err = rawResp.ValueConvertToBool(); err != nil {
@@ -517,7 +540,8 @@ func (wd *WDADriver) AppTerminate(bundleId string) (successful bool, err error)
func (wd *WDADriver) AppActivate(bundleId string) (err error) {
// [[FBRoute POST:@"/wda/apps/activate"] respondWithTarget:self action:@selector(handleSessionAppActivate:)]
data := map[string]interface{}{"bundleId": bundleId}
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/apps/activate")
urlStr := fmt.Sprintf("/session/%s/wda/apps/activate", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
return
}
@@ -527,7 +551,8 @@ func (wd *WDADriver) AppDeactivate(second float64) (err error) {
second = 3.0
}
data := map[string]interface{}{"duration": second}
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/deactivateApp")
urlStr := fmt.Sprintf("/session/%s/wda/deactivateApp", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
return
}
@@ -574,7 +599,8 @@ func (wd *WDADriver) TapAbsXY(x, y float64, opts ...option.ActionOption) error {
}
option.MergeOptions(data, opts...)
_, err := wd.Session.POST(data, "/session", wd.Session.ID, "/wda/tap/0")
urlStr := fmt.Sprintf("/session/%s/wda/tap/0", wd.Session.ID)
_, err := wd.Session.POST(data, urlStr)
return err
}
@@ -593,7 +619,8 @@ func (wd *WDADriver) DoubleTapXY(x, y float64, opts ...option.ActionOption) erro
"x": x,
"y": y,
}
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/doubleTap")
urlStr := fmt.Sprintf("/session/%s/wda/doubleTap", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
return err
}
@@ -629,7 +656,8 @@ func (wd *WDADriver) Drag(fromX, fromY, toX, toY float64, opts ...option.ActionO
}
option.MergeOptions(data, opts...)
// wda 43 version
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/dragfromtoforduration")
urlStr := fmt.Sprintf("/session/%s/wda/dragfromtoforduration", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
// _, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/drag")
return err
}
@@ -644,7 +672,8 @@ func (wd *WDADriver) SetPasteboard(contentType types.PasteboardType, content str
"contentType": contentType,
"content": base64.StdEncoding.EncodeToString([]byte(content)),
}
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/setPasteboard")
urlStr := fmt.Sprintf("/session/%s/wda/setPasteboard", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
return
}
@@ -652,7 +681,8 @@ func (wd *WDADriver) GetPasteboard(contentType types.PasteboardType) (raw *bytes
// [[FBRoute POST:@"/wda/getPasteboard"] respondWithTarget:self action:@selector(handleGetPasteboard:)]
data := map[string]interface{}{"contentType": contentType}
var rawResp DriverRawResponse
if rawResp, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/getPasteboard"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/getPasteboard", wd.Session.ID)
if rawResp, err = wd.Session.POST(data, urlStr); err != nil {
return nil, err
}
if raw, err = rawResp.ValueDecodeAsBase64(); err != nil {
@@ -669,7 +699,8 @@ func (wd *WDADriver) Input(text string, opts ...option.ActionOption) (err error)
// [[FBRoute POST:@"/wda/keys"] respondWithTarget:self action:@selector(handleKeys:)]
data := map[string]interface{}{"value": strings.Split(text, "")}
option.MergeOptions(data, opts...)
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/keys")
urlStr := fmt.Sprintf("/session/%s/wda/keys", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
return
}
@@ -689,37 +720,22 @@ func (wd *WDADriver) AppClear(packageName string) error {
// Back simulates a short press on the BACK button.
func (wd *WDADriver) Back() (err error) {
windowSize, err := wd.WindowSize()
if err != nil {
return
}
fromX := wd.toScale(float64(windowSize.Width) * 0)
fromY := wd.toScale(float64(windowSize.Height) * 0.5)
toX := wd.toScale(float64(windowSize.Width) * 0.6)
toY := wd.toScale(float64(windowSize.Height) * 0.5)
data := map[string]interface{}{
"fromX": fromX,
"fromY": fromY,
"toX": toX,
"toY": toY,
}
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/dragfromtoforduration")
return
return wd.Swipe(0, 0.5, 0.6, 0.5)
}
func (wd *WDADriver) PressButton(devBtn types.DeviceButton) (err error) {
// [[FBRoute POST:@"/wda/pressButton"] respondWithTarget:self action:@selector(handlePressButtonCommand:)]
data := map[string]interface{}{"name": devBtn}
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/wda/pressButton")
urlStr := fmt.Sprintf("/session/%s/wda/pressButton", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
return
}
func (wd *WDADriver) Orientation() (orientation types.Orientation, err error) {
// [[FBRoute GET:@"/orientation"] respondWithTarget:self action:@selector(handleGetOrientation:)]
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/orientation"); err != nil {
urlStr := fmt.Sprintf("/session/%s/orientation", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return "", err
}
reply := new(struct{ Value types.Orientation })
@@ -733,14 +749,16 @@ func (wd *WDADriver) Orientation() (orientation types.Orientation, err error) {
func (wd *WDADriver) SetOrientation(orientation types.Orientation) (err error) {
// [[FBRoute POST:@"/orientation"] respondWithTarget:self action:@selector(handleSetOrientation:)]
data := map[string]interface{}{"orientation": orientation}
_, err = wd.Session.POST(data, "/session", wd.Session.ID, "/orientation")
urlStr := fmt.Sprintf("/session/%s/orientation", wd.Session.ID)
_, err = wd.Session.POST(data, urlStr)
return
}
func (wd *WDADriver) Rotation() (rotation types.Rotation, err error) {
// [[FBRoute GET:@"/rotation"] respondWithTarget:self action:@selector(handleGetRotation:)]
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/rotation"); err != nil {
urlStr := fmt.Sprintf("/session/%s/rotation", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return types.Rotation{}, err
}
reply := new(struct{ Value types.Rotation })
@@ -753,7 +771,8 @@ func (wd *WDADriver) Rotation() (rotation types.Rotation, err error) {
func (wd *WDADriver) SetRotation(rotation types.Rotation) (err error) {
// [[FBRoute POST:@"/rotation"] respondWithTarget:self action:@selector(handleSetRotation:)]
_, err = wd.Session.POST(rotation, "/session", wd.Session.ID, "/rotation")
urlStr := fmt.Sprintf("/session/%s/rotation", wd.Session.ID)
_, err = wd.Session.POST(rotation, urlStr)
return
}
@@ -793,7 +812,8 @@ func (wd *WDADriver) AccessibleSource() (source string, err error) {
// [[FBRoute GET:@"/wda/accessibleSource"] respondWithTarget:self action:@selector(handleGetAccessibleSourceCommand:)]
// [[FBRoute GET:@"/wda/accessibleSource"].withoutSession
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/wda/accessibleSource"); err != nil {
urlStr := fmt.Sprintf("/session/%s/wda/accessibleSource", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return "", err
}
var jr builtinJSON.RawMessage
@@ -824,7 +844,8 @@ func (wd *WDADriver) IsHealthy() (healthy bool, err error) {
func (wd *WDADriver) GetAppiumSettings() (settings map[string]interface{}, err error) {
// [[FBRoute GET:@"/appium/settings"] respondWithTarget:self action:@selector(handleGetSettings:)]
var rawResp DriverRawResponse
if rawResp, err = wd.Session.GET("/session", wd.Session.ID, "/appium/settings"); err != nil {
urlStr := fmt.Sprintf("/session/%s/appium/settings", wd.Session.ID)
if rawResp, err = wd.Session.GET(urlStr); err != nil {
return nil, err
}
reply := new(struct{ Value map[string]interface{} })
@@ -839,7 +860,8 @@ func (wd *WDADriver) SetAppiumSettings(settings map[string]interface{}) (ret map
// [[FBRoute POST:@"/appium/settings"] respondWithTarget:self action:@selector(handleSetSettings:)]
data := map[string]interface{}{"settings": settings}
var rawResp DriverRawResponse
if rawResp, err = wd.Session.POST(data, "/session", wd.Session.ID, "/appium/settings"); err != nil {
urlStr := fmt.Sprintf("/session/%s/appium/settings", wd.Session.ID)
if rawResp, err = wd.Session.POST(data, urlStr); err != nil {
return nil, err
}
reply := new(struct{ Value map[string]interface{} })

View File

@@ -33,6 +33,20 @@ func TestDevice_IOS_Install(t *testing.T) {
assert.Nil(t, err)
}
func TestDriver_WDA_LazySetup(t *testing.T) {
device, err := NewIOSDevice(
option.WithWDAPort(8700),
option.WithWDAMjpegPort(8800),
option.WithLazySetup(true))
require.Nil(t, err)
driver, err := NewWDADriver(device)
require.Nil(t, err)
err = driver.PressButton(types.DeviceButtonHome)
assert.Nil(t, err)
err = driver.TapXY(0.5, 0.5)
assert.Nil(t, err)
}
func TestDevice_IOS_New(t *testing.T) {
device, err := NewIOSDevice(
option.WithWDAPort(8700),

View File

@@ -5,6 +5,7 @@ type IOSDeviceOptions struct {
WDAPort int `json:"port,omitempty" yaml:"port,omitempty"` // WDA remote port
WDAMjpegPort int `json:"mjpeg_port,omitempty" yaml:"mjpeg_port,omitempty"` // WDA remote MJPEG port
LogOn bool `json:"log_on,omitempty" yaml:"log_on,omitempty"`
LazySetup bool `json:"lazy_setup,omitempty" yaml:"lazy_setup,omitempty"` // lazy setup WDA
// switch to iOS springboard before init WDA session
ResetHomeOnStartup bool `json:"reset_home_on_startup,omitempty" yaml:"reset_home_on_startup,omitempty"`
@@ -28,6 +29,9 @@ func (dev *IOSDeviceOptions) Options() (deviceOptions []IOSDeviceOption) {
if dev.LogOn {
deviceOptions = append(deviceOptions, WithWDALogOn(true))
}
if dev.LazySetup {
deviceOptions = append(deviceOptions, WithLazySetup(true))
}
if dev.ResetHomeOnStartup {
deviceOptions = append(deviceOptions, WithResetHomeOnStartup(true))
}
@@ -86,10 +90,6 @@ func NewIOSDeviceOptions(opts ...IOSDeviceOption) *IOSDeviceOptions {
config.DismissAlertButtonSelector = dismissAlertButtonSelector
}
// switch to iOS springboard before init WDA session
// avoid getting stuck when some super app is active such as douyin or wexin
config.ResetHomeOnStartup = true
return config
}
@@ -119,6 +119,12 @@ func WithWDALogOn(logOn bool) IOSDeviceOption {
}
}
func WithLazySetup(lazySetup bool) IOSDeviceOption {
return func(device *IOSDeviceOptions) {
device.LazySetup = lazySetup
}
}
func WithResetHomeOnStartup(reset bool) IOSDeviceOption {
return func(device *IOSDeviceOptions) {
device.ResetHomeOnStartup = reset

View File

@@ -5,8 +5,8 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt"
)
func foregroundAppHandler(c *gin.Context) {
driver, err := GetDriver(c)
func (r *Router) foregroundAppHandler(c *gin.Context) {
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -18,7 +18,7 @@ func foregroundAppHandler(c *gin.Context) {
RenderSuccess(c, appInfo)
}
func appInfoHandler(c *gin.Context) {
func (r *Router) appInfoHandler(c *gin.Context) {
var appInfoReq AppInfoRequest
if err := c.ShouldBindQuery(&appInfoReq); err != nil {
RenderErrorValidateRequest(c, err)
@@ -47,18 +47,18 @@ func appInfoHandler(c *gin.Context) {
}
}
func clearAppHandler(c *gin.Context) {
func (r *Router) clearAppHandler(c *gin.Context) {
var appClearReq AppClearRequest
if err := c.ShouldBindJSON(&appClearReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
err = driver.IDriver.(*uixt.ADBDriver).AppClear(appClearReq.PackageName)
err = driver.GetIDriver().(*uixt.ADBDriver).AppClear(appClearReq.PackageName)
if err != nil {
RenderError(c, err)
return
@@ -66,13 +66,13 @@ func clearAppHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func launchAppHandler(c *gin.Context) {
func (r *Router) launchAppHandler(c *gin.Context) {
var appLaunchReq AppLaunchRequest
if err := c.ShouldBindJSON(&appLaunchReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -84,13 +84,13 @@ func launchAppHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func terminalAppHandler(c *gin.Context) {
func (r *Router) terminalAppHandler(c *gin.Context) {
var appTerminalReq AppTerminalRequest
if err := c.ShouldBindJSON(&appTerminalReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -102,13 +102,13 @@ func terminalAppHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func uninstallAppHandler(c *gin.Context) {
func (r *Router) uninstallAppHandler(c *gin.Context) {
var appUninstallReq AppUninstallRequest
if err := c.ShouldBindJSON(&appUninstallReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}

View File

@@ -14,7 +14,7 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
)
func GetDriver(c *gin.Context) (driverExt *uixt.XTDriver, err error) {
func (p RouterBaseMethod) GetDriver(c *gin.Context) (driverExt uixt.IXTDriver, err error) {
deviceObj, exists := c.Get("device")
var device uixt.IDevice
var driver uixt.IDriver
@@ -54,7 +54,6 @@ func GetDevice(c *gin.Context) (device uixt.IDevice, err error) {
RenderErrorInitDriver(c, err)
return
}
_ = device.Setup()
case "ios":
device, err = uixt.NewIOSDevice(
option.WithUDID(serial),
@@ -76,6 +75,10 @@ func GetDevice(c *gin.Context) (device uixt.IDevice, err error) {
err = fmt.Errorf("[%s]: invalid platform", c.HandlerName())
return
}
err = device.Setup()
if err != nil {
log.Error().Err(err).Msg("setup device failed")
}
c.Set("device", device)
return device, nil
}

View File

@@ -7,14 +7,13 @@ import (
"github.com/Masterminds/semver"
"github.com/danielpaulus/go-ios/ios"
"github.com/gin-gonic/gin"
"github.com/httprunner/httprunner/v5/internal/builtin"
"github.com/httprunner/httprunner/v5/pkg/gadb"
"github.com/httprunner/httprunner/v5/pkg/uixt"
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
"github.com/rs/zerolog/log"
)
func listDeviceHandler(c *gin.Context) {
func (r *Router) listDeviceHandler(c *gin.Context) {
var deviceList []interface{}
client, err := gadb.NewClient()
if err == nil {
@@ -119,16 +118,17 @@ func deleteBrowserHandler(c *gin.Context) {
}
func pushImageHandler(c *gin.Context) {
func (r *Router) pushImageHandler(c *gin.Context) {
var pushMediaReq PushMediaRequest
if err := c.ShouldBindJSON(&pushMediaReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
imagePath, err := builtin.DownloadFileByUrl(pushMediaReq.ImageUrl)
imagePath, err := uixt.DownloadFileByUrl(pushMediaReq.ImageUrl)
if path.Ext(imagePath) == "" {
err = os.Rename(imagePath, imagePath+".png")
if err != nil {
@@ -152,8 +152,8 @@ func pushImageHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func clearImageHandler(c *gin.Context) {
driver, err := GetDriver(c)
func (r *Router) clearImageHandler(c *gin.Context) {
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -165,6 +165,6 @@ func clearImageHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func videoHandler(c *gin.Context) {
func (r *Router) videoHandler(c *gin.Context) {
RenderSuccess(c, "")
}

View File

@@ -2,26 +2,26 @@ package server_ext
import (
"fmt"
"github.com/httprunner/httprunner/v5/pkg/uixt/driver_ext"
"os"
"github.com/gin-gonic/gin"
"github.com/httprunner/httprunner/v5/internal/builtin"
"github.com/httprunner/httprunner/v5/pkg/uixt"
"github.com/httprunner/httprunner/v5/server"
)
func installAppHandler(c *gin.Context) {
func (r *RouterExt) installAppHandler(c *gin.Context) {
var appInstallReq AppInstallRequest
if err := c.ShouldBindJSON(&appInstallReq); err != nil {
server.RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
err = driver.InstallByUrl(appInstallReq.AppUrl)
err = driver.(*driver_ext.XTDriver).InstallByUrl(appInstallReq.AppUrl)
if err != nil {
server.RenderError(c, err)
return
@@ -32,7 +32,7 @@ func installAppHandler(c *gin.Context) {
server.RenderSuccess(c, true)
return
}
localMappingPath, err := builtin.DownloadFileByUrl(appInstallReq.MappingUrl)
localMappingPath, err := uixt.DownloadFileByUrl(appInstallReq.MappingUrl)
if err != nil {
server.RenderError(c, err)
}
@@ -45,7 +45,7 @@ func installAppHandler(c *gin.Context) {
server.RenderError(c, err)
return
}
localResourceMappingPath, err := builtin.DownloadFileByUrl(
localResourceMappingPath, err := uixt.DownloadFileByUrl(
appInstallReq.ResourceMappingUrl)
if err != nil {
server.RenderError(c, err)

View File

@@ -11,7 +11,7 @@ import (
"github.com/httprunner/httprunner/v5/server"
)
func GetDriver(c *gin.Context) (driverExt *driver_ext.XTDriver, err error) {
func (p RouterBaseMethodExt) GetDriver(c *gin.Context) (driverExt uixt.IXTDriver, err error) {
platform := c.Param("platform")
serial := c.Param("serial")
deviceObj, exists := c.Get("device")

View File

@@ -8,18 +8,18 @@ import (
"github.com/httprunner/httprunner/v5/server"
)
func loginHandler(c *gin.Context) {
func (r *RouterExt) loginHandler(c *gin.Context) {
var loginReq LoginRequest
if err := c.ShouldBindJSON(&loginReq); err != nil {
server.RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
info, err := driver.IDriver.(driver_ext.IStubDriver).
info, err := driver.GetIDriver().(driver_ext.IStubDriver).
LoginNoneUI(loginReq.PackageName, loginReq.PhoneNumber,
loginReq.Captcha, loginReq.Password)
if err != nil {
@@ -29,18 +29,18 @@ func loginHandler(c *gin.Context) {
server.RenderSuccess(c, info)
}
func logoutHandler(c *gin.Context) {
func (r *RouterExt) logoutHandler(c *gin.Context) {
var logoutReq LogoutRequest
if err := c.ShouldBindJSON(&logoutReq); err != nil {
server.RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
err = driver.IDriver.(driver_ext.IStubDriver).
err = driver.GetIDriver().(driver_ext.IStubDriver).
LogoutNoneUI(logoutReq.PackageName)
if err != nil {
server.RenderError(c, err)
@@ -49,8 +49,8 @@ func logoutHandler(c *gin.Context) {
server.RenderSuccess(c, true)
}
func sourceHandler(c *gin.Context) {
driver, err := GetDriver(c)
func (r *RouterExt) sourceHandler(c *gin.Context) {
driver, err := r.GetDriver(c)
if err != nil {
return
}

View File

@@ -1,16 +1,35 @@
package server_ext
import (
"github.com/gin-gonic/gin"
"github.com/httprunner/httprunner/v5/server"
)
func NewExtRouter() *server.Router {
router := server.NewRouter()
apiV1PlatformSerial := router.Group("/api/v1").Group("/:platform").Group("/:serial")
type RouterExt struct {
*server.Router
}
apiV1PlatformSerial.GET("/stub/source", sourceHandler)
apiV1PlatformSerial.POST("/stub/login", loginHandler)
apiV1PlatformSerial.POST("/stub/logout", logoutHandler)
apiV1PlatformSerial.POST("/app/install", installAppHandler)
type RouterBaseMethodExt struct {
server.RouterBaseMethod
}
func NewExtRouter() *RouterExt {
router := &RouterExt{
Router: &server.Router{
Engine: gin.Default(),
IRouterBaseMethod: &RouterBaseMethodExt{},
},
}
router.Init()
return router
}
func (r *RouterExt) Init() {
r.Router.Init()
apiV1PlatformSerial := r.Group("/api/v1").Group("/:platform").Group("/:serial")
apiV1PlatformSerial.GET("/stub/source", r.sourceHandler)
apiV1PlatformSerial.POST("/stub/login", r.loginHandler)
apiV1PlatformSerial.POST("/stub/logout", r.logoutHandler)
apiV1PlatformSerial.POST("/app/install", r.installAppHandler)
}

View File

@@ -6,8 +6,8 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt"
)
func unlockHandler(c *gin.Context) {
driver, err := GetDriver(c)
func (r *Router) unlockHandler(c *gin.Context) {
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -19,8 +19,8 @@ func unlockHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func homeHandler(c *gin.Context) {
driver, err := GetDriver(c)
func (r *Router) homeHandler(c *gin.Context) {
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -32,7 +32,7 @@ func homeHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func backspaceHandler(c *gin.Context) {
func (r *Router) backspaceHandler(c *gin.Context) {
var deleteReq DeleteRequest
if err := c.ShouldBindJSON(&deleteReq); err != nil {
RenderErrorValidateRequest(c, err)
@@ -41,7 +41,7 @@ func backspaceHandler(c *gin.Context) {
if deleteReq.Count == 0 {
deleteReq.Count = 20
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -53,18 +53,18 @@ func backspaceHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func keycodeHandler(c *gin.Context) {
func (r *Router) keycodeHandler(c *gin.Context) {
var keycodeReq KeycodeRequest
if err := c.ShouldBindJSON(&keycodeReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
// TODO FIXME
err = driver.IDriver.(*uixt.ADBDriver).
err = driver.GetIDriver().(*uixt.ADBDriver).
PressKeyCode(uixt.KeyCode(keycodeReq.Keycode), uixt.KMEmpty)
if err != nil {
RenderError(c, err)

View File

@@ -11,17 +11,27 @@ import (
)
func NewRouter() *Router {
router := &Router{}
router := &Router{
Engine: gin.Default(),
IRouterBaseMethod: &RouterBaseMethod{},
}
router.Init()
return router
}
type Router struct {
*gin.Engine
IRouterBaseMethod
}
type RouterBaseMethod struct {
}
type IRouterBaseMethod interface {
GetDriver(c *gin.Context) (driver uixt.IXTDriver, err error)
}
func (r *Router) Init() {
r.Engine = gin.Default()
r.Engine.Use(teardown())
r.Engine.GET("/ping", pingHandler)
r.Engine.GET("/", pingHandler)
@@ -42,18 +52,18 @@ func (r *Router) Init() {
apiV1PlatformSerial.POST("/ui/scroll", scrollHandler)
// Key operations
apiV1PlatformSerial.POST("/key/unlock", unlockHandler)
apiV1PlatformSerial.POST("/key/home", homeHandler)
apiV1PlatformSerial.POST("/key/backspace", backspaceHandler)
apiV1PlatformSerial.POST("/key", keycodeHandler)
apiV1PlatformSerial.POST("/key/unlock", r.unlockHandler)
apiV1PlatformSerial.POST("/key/home", r.homeHandler)
apiV1PlatformSerial.POST("/key/backspace", r.backspaceHandler)
apiV1PlatformSerial.POST("/key", r.keycodeHandler)
// APP operations
apiV1PlatformSerial.GET("/app/foreground", foregroundAppHandler)
apiV1PlatformSerial.GET("/app/appInfo", appInfoHandler)
apiV1PlatformSerial.POST("/app/clear", clearAppHandler)
apiV1PlatformSerial.POST("/app/launch", launchAppHandler)
apiV1PlatformSerial.POST("/app/terminal", terminalAppHandler)
apiV1PlatformSerial.POST("/app/uninstall", uninstallAppHandler)
apiV1PlatformSerial.GET("/app/foreground", r.foregroundAppHandler)
apiV1PlatformSerial.GET("/app/appInfo", r.appInfoHandler)
apiV1PlatformSerial.POST("/app/clear", r.clearAppHandler)
apiV1PlatformSerial.POST("/app/launch", r.launchAppHandler)
apiV1PlatformSerial.POST("/app/terminal", r.terminalAppHandler)
apiV1PlatformSerial.POST("/app/uninstall", r.uninstallAppHandler)
// Device operations
apiV1PlatformSerial.GET("/screenshot", screenshotHandler)
@@ -64,8 +74,8 @@ func (r *Router) Init() {
apiV1PlatformSerial.GET("/adb/source", adbSourceHandler)
// uixt operations
apiV1PlatformSerial.POST("/uixt/action", uixtActionHandler)
apiV1PlatformSerial.POST("/uixt/actions", uixtActionsHandler)
apiV1PlatformSerial.POST("/uixt/action", r.uixtActionHandler)
apiV1PlatformSerial.POST("/uixt/actions", r.uixtActionsHandler)
}
func (r *Router) Run(port int) error {
@@ -77,7 +87,7 @@ func (r *Router) Run(port int) error {
return nil
}
func pingHandler(c *gin.Context) {
func (r *Router) pingHandler(c *gin.Context) {
RenderSuccess(c, true)
}

View File

@@ -9,8 +9,8 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
)
func screenshotHandler(c *gin.Context) {
driver, err := GetDriver(c)
func (r *Router) screenshotHandler(c *gin.Context) {
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -23,8 +23,8 @@ func screenshotHandler(c *gin.Context) {
RenderSuccess(c, base64.StdEncoding.EncodeToString(raw.Bytes()))
}
func screenResultHandler(c *gin.Context) {
dExt, err := GetDriver(c)
func (r *Router) screenResultHandler(c *gin.Context) {
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -40,7 +40,7 @@ func screenResultHandler(c *gin.Context) {
actionOptions = screenReq.Options.Options()
}
screenResult, err := dExt.GetScreenResult(actionOptions...)
screenResult, err := driver.GetScreenResult(actionOptions...)
if err != nil {
log.Err(err).Msg("get screen result failed")
RenderError(c, err)
@@ -49,8 +49,8 @@ func screenResultHandler(c *gin.Context) {
RenderSuccess(c, screenResult)
}
func adbSourceHandler(c *gin.Context) {
dExt, err := GetDriver(c)
func (r *Router) adbSourceHandler(c *gin.Context) {
dExt, err := r.GetDriver(c)
if err != nil {
return
}

View File

@@ -6,13 +6,13 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
)
func tapHandler(c *gin.Context) {
func (r *Router) tapHandler(c *gin.Context) {
var tapReq TapRequest
if err := c.ShouldBindJSON(&tapReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -93,14 +93,14 @@ func scrollHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func doubleTapHandler(c *gin.Context) {
func (r *Router) doubleTapHandler(c *gin.Context) {
var tapReq TapRequest
if err := c.ShouldBindJSON(&tapReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -119,7 +119,7 @@ func doubleTapHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func dragHandler(c *gin.Context) {
func (r *Router) dragHandler(c *gin.Context) {
var dragReq DragRequest
if err := c.ShouldBindJSON(&dragReq); err != nil {
RenderErrorValidateRequest(c, err)
@@ -128,7 +128,7 @@ func dragHandler(c *gin.Context) {
if dragReq.Duration == 0 {
dragReq.Duration = 1
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}
@@ -143,13 +143,13 @@ func dragHandler(c *gin.Context) {
RenderSuccess(c, true)
}
func inputHandler(c *gin.Context) {
func (r *Router) inputHandler(c *gin.Context) {
var inputReq InputRequest
if err := c.ShouldBindJSON(&inputReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
driver, err := r.GetDriver(c)
if err != nil {
return
}

View File

@@ -7,8 +7,8 @@ import (
)
// exec a single uixt action
func uixtActionHandler(c *gin.Context) {
dExt, err := GetDriver(c)
func (r *Router) uixtActionHandler(c *gin.Context) {
dExt, err := r.GetDriver(c)
if err != nil {
return
}
@@ -29,8 +29,8 @@ func uixtActionHandler(c *gin.Context) {
}
// exec multiple uixt actions
func uixtActionsHandler(c *gin.Context) {
dExt, err := GetDriver(c)
func (r *Router) uixtActionsHandler(c *gin.Context) {
dExt, err := r.GetDriver(c)
if err != nil {
return
}