change: server

This commit is contained in:
lilong.129 2025-02-18 20:22:07 +08:00
parent 5d91b69603
commit 7183eae486
10 changed files with 570 additions and 465 deletions

View File

@ -1 +1 @@
v5.0.0+2502181933 v5.0.0+2502182022

View File

@ -1,112 +1,121 @@
package server package server
import ( import (
"fmt"
"net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/httprunner/httprunner/v5/code" "github.com/httprunner/httprunner/v5/pkg/uixt"
"github.com/rs/zerolog/log"
) )
func foregroundAppHandler(c *gin.Context) { func foregroundAppHandler(c *gin.Context) {
dExt, err := GetContextDriver(c) driver, err := GetDriver(c)
if err != nil { if err != nil {
return return
} }
appInfo, err := driver.ForegroundInfo()
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, appInfo)
}
appInfo, err := dExt.ForegroundInfo() func appInfoHandler(c *gin.Context) {
if err != nil { var appInfoReq AppInfoRequest
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to unlick screen", c.HandlerName())) if err := c.ShouldBindQuery(&appInfoReq); err != nil {
c.JSON(http.StatusInternalServerError, RenderErrorValidateRequest(c, err)
HttpResponse{ return
Code: code.GetErrorCode(err), }
Message: err.Error(), device, err := GetDevice(c)
}, if err != nil {
) return
c.Abort() }
if androidDevice, ok := device.(*uixt.AndroidDevice); ok {
appInfo, err := androidDevice.GetAppInfo(appInfoReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, appInfo)
return
} else if iOSDevice, ok := device.(*uixt.IOSDevice); ok {
appInfo, err := iOSDevice.GetAppInfo(appInfoReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, appInfo)
return return
} }
c.JSON(http.StatusOK, HttpResponse{Result: appInfo})
} }
func clearAppHandler(c *gin.Context) { func clearAppHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
if err != nil {
return
}
var appClearReq AppClearRequest var appClearReq AppClearRequest
if err := c.ShouldBindJSON(&appClearReq); err != nil { if err := c.ShouldBindJSON(&appClearReq); err != nil {
handlerValidateRequestFailedContext(c, err) RenderErrorValidateRequest(c, err)
return return
} }
err = dExt.AppClear(appClearReq.PackageName) driver, err := GetDriver(c)
if err != nil { if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to unlick screen", c.HandlerName()))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"}) err = driver.IDriver.(*uixt.ADBDriver).AppClear(appClearReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
} }
func launchAppHandler(c *gin.Context) { func launchAppHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
if err != nil {
return
}
var appLaunchReq AppLaunchRequest var appLaunchReq AppLaunchRequest
if err := c.ShouldBindJSON(&appLaunchReq); err != nil { if err := c.ShouldBindJSON(&appLaunchReq); err != nil {
handlerValidateRequestFailedContext(c, err) RenderErrorValidateRequest(c, err)
return return
} }
driver, err := GetDriver(c)
err = dExt.AppLaunch(appLaunchReq.PackageName)
if err != nil { if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to launch app %s", c.HandlerName(), appLaunchReq.PackageName))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"}) err = driver.AppLaunch(appLaunchReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
} }
func terminalAppHandler(c *gin.Context) { func terminalAppHandler(c *gin.Context) {
dExt, err := GetContextDriver(c) var appTerminalReq AppTerminalRequest
if err := c.ShouldBindJSON(&appTerminalReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
if err != nil { if err != nil {
return return
} }
_, err = driver.AppTerminate(appTerminalReq.PackageName)
var appTerminalReq AppTerminalRequest if err != nil {
if err := c.ShouldBindJSON(&appTerminalReq); err != nil { RenderError(c, err)
handlerValidateRequestFailedContext(c, err)
return return
} }
RenderSuccess(c, true)
}
success, err := dExt.AppTerminate(appTerminalReq.PackageName) func uninstallAppHandler(c *gin.Context) {
if !success { var appUninstallReq AppUninstallRequest
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to launch app %s", c.HandlerName(), appTerminalReq.PackageName)) if err := c.ShouldBindJSON(&appUninstallReq); err != nil {
c.JSON(http.StatusInternalServerError, RenderErrorValidateRequest(c, err)
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"}) driver, err := GetDriver(c)
if err != nil {
return
}
err = driver.GetDevice().Uninstall(appUninstallReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
} }

View File

@ -14,49 +14,76 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/option" "github.com/httprunner/httprunner/v5/pkg/uixt/option"
) )
var uiClients = make(map[string]*uixt.XTDriver) // UI automation clients for iOS and Android, key is udid/serial func GetDriver(c *gin.Context) (driverExt *uixt.XTDriver, err error) {
deviceObj, exists := c.Get("device")
var device uixt.IDevice
var driver uixt.IDriver
if !exists {
device, err = GetDevice(c)
if err != nil {
return nil, err
}
} else {
device = deviceObj.(uixt.IDevice)
}
func (r *Router) HandleDeviceContext() gin.HandlerFunc { driver, err = device.NewDriver()
return func(c *gin.Context) { if err != nil {
RenderErrorInitDriver(c, err)
return
}
c.Set("driver", driver)
driverExt = uixt.NewXTDriver(driver,
ai.WithCVService(ai.CVServiceTypeVEDEM))
return driverExt, nil
}
func GetDevice(c *gin.Context) (device uixt.IDevice, err error) {
platform := c.Param("platform") platform := c.Param("platform")
serial := c.Param("serial") serial := c.Param("serial")
if serial == "" { if serial == "" {
log.Error().Str("platform", platform).Msg(fmt.Sprintf("[%s]: serial is empty", c.HandlerName())) RenderErrorInitDriver(c, err)
c.JSON(http.StatusBadRequest, HttpResponse{
Code: code.GetErrorCode(code.InvalidParamError),
Message: "serial is empty",
})
c.Abort()
return return
} }
// get cached driver
if driver, ok := uiClients[serial]; ok {
c.Set("driver", driver)
c.Next()
return
}
switch strings.ToLower(platform) { switch strings.ToLower(platform) {
case "android": case "android":
device, err := uixt.NewAndroidDevice( device, err = uixt.NewAndroidDevice(
option.WithSerialNumber(serial)) option.WithSerialNumber(serial))
if err != nil { if err != nil {
log.Error().Err(err).Str("platform", platform).Str("serial", serial). RenderErrorInitDriver(c, err)
Msg("device not found")
c.JSON(http.StatusBadRequest,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
_ = device.Setup()
driver, err := device.NewDriver() case "ios":
device, err = uixt.NewIOSDevice(
option.WithUDID(serial),
option.WithWDAPort(8700),
option.WithWDAMjpegPort(8800),
option.WithResetHomeOnStartup(false),
)
if err != nil { if err != nil {
log.Error().Err(err).Str("platform", platform).Str("serial", serial). RenderErrorInitDriver(c, err)
Msg("failed to init driver") return
}
default:
err = fmt.Errorf("[%s]: invalid platform", c.HandlerName())
return
}
c.Set("device", device)
return device, nil
}
func RenderSuccess(c *gin.Context, result interface{}) {
c.JSON(http.StatusOK, HttpResponse{
Code: code.Success,
Message: "success",
Result: result,
})
}
func RenderError(c *gin.Context, err error) {
log.Error().Err(err).Msgf("failed to %s", c.HandlerName())
c.JSON(http.StatusInternalServerError, c.JSON(http.StatusInternalServerError,
HttpResponse{ HttpResponse{
Code: code.GetErrorCode(err), Code: code.GetErrorCode(err),
@ -64,49 +91,24 @@ func (r *Router) HandleDeviceContext() gin.HandlerFunc {
}, },
) )
c.Abort() c.Abort()
return
} }
driverExt := uixt.NewXTDriver(driver, func RenderErrorInitDriver(c *gin.Context, err error) {
ai.WithCVService(ai.CVServiceTypeVEDEM)) log.Error().Err(err).Msg("init device driver failed")
errCode := code.GetErrorCode(err)
c.Set("driver", driverExt) if errCode == code.GeneralFail {
// cache driver errCode = code.GetErrorCode(code.MobileUIDriverError)
uiClients[serial] = driverExt
default:
c.JSON(http.StatusBadRequest, HttpResponse{
Code: code.GetErrorCode(code.InvalidParamError),
Message: fmt.Sprintf("unsupported platform %s", platform),
})
c.Abort()
return
} }
c.Next()
}
}
func GetContextDriver(c *gin.Context) (*uixt.XTDriver, error) {
driverObj, exists := c.Get("driver")
if !exists {
handlerInitDeviceDriverFailedContext(c)
return nil, fmt.Errorf("driver not found")
}
dExt := driverObj.(*uixt.XTDriver)
return dExt, nil
}
func handlerInitDeviceDriverFailedContext(c *gin.Context) {
log.Error().Msg("init device driver failed")
c.JSON(http.StatusInternalServerError, c.JSON(http.StatusInternalServerError,
HttpResponse{ HttpResponse{
Code: code.GetErrorCode(code.MobileUIDriverError), Code: errCode,
Message: "init driver failed", Message: "init driver failed",
}, },
) )
c.Abort() c.Abort()
} }
func handlerValidateRequestFailedContext(c *gin.Context, err error) { func RenderErrorValidateRequest(c *gin.Context, err error) {
log.Error().Err(err).Msg("validate request failed") log.Error().Err(err).Msg("validate request failed")
c.JSON(http.StatusBadRequest, HttpResponse{ c.JSON(http.StatusBadRequest, HttpResponse{
Code: code.GetErrorCode(code.InvalidParamError), Code: code.GetErrorCode(code.InvalidParamError),

View File

@ -1,93 +1,140 @@
package server package server
import ( import (
"fmt" "os"
"net/http" "path"
"strings"
"github.com/Masterminds/semver"
"github.com/danielpaulus/go-ios/ios"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/httprunner/httprunner/v5/code" "github.com/httprunner/httprunner/v5/internal/builtin"
"github.com/httprunner/httprunner/v5/pkg/gadb" "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" "github.com/rs/zerolog/log"
) )
func listDeviceHandler(c *gin.Context) { func listDeviceHandler(c *gin.Context) {
platform := c.Param("platform")
switch strings.ToLower(platform) {
case "android":
{
client, err := gadb.NewClient()
if err != nil {
log.Err(err).Msg("failed to init adb client")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
devices, err := client.DeviceList()
if err != nil && strings.Contains(err.Error(), "no android device found") {
c.JSON(http.StatusOK, HttpResponse{Result: nil})
return
} else if err != nil {
log.Err(err).Msg("failed to list devices")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
var deviceList []interface{} var deviceList []interface{}
for _, device := range devices { client, err := gadb.NewClient()
if err == nil {
androidDevices, err := client.DeviceList()
if err == nil {
for _, device := range androidDevices {
brand, err := device.Brand() brand, err := device.Brand()
if err != nil { if err != nil {
log.Err(err).Msg("failed to get device brand") RenderError(c, err)
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
model, err := device.Model() model, err := device.Model()
if err != nil { if err != nil {
log.Err(err).Msg("failed to get device model") RenderError(c, err)
c.JSON(http.StatusInternalServerError, return
HttpResponse{ }
Code: code.GetErrorCode(err), version, err := device.SdkVersion()
Message: err.Error(), if err != nil {
}, RenderError(c, err)
)
c.Abort()
return return
} }
deviceInfo := map[string]interface{}{ deviceInfo := map[string]interface{}{
"serial": device.Serial(), "serial": device.Serial(),
"brand": brand, "brand": brand,
"model": model, "model": model,
"version": version,
"platform": "android", "platform": "android",
} }
deviceList = append(deviceList, deviceInfo) deviceList = append(deviceList, deviceInfo)
} }
c.JSON(http.StatusOK, HttpResponse{Result: deviceList}) }
}
iosDevices, err := ios.ListDevices()
if err == nil {
for _, dev := range iosDevices.DeviceList {
device, err := uixt.NewIOSDevice(
option.WithUDID(dev.Properties.SerialNumber))
if err != nil {
continue
}
properties := device.Properties
err = ios.Pair(dev)
if err != nil {
log.Error().Err(err).Msg("failed to pair device")
continue
}
version, err := ios.GetProductVersion(dev)
if err != nil {
continue
}
if version.LessThan(semver.MustParse("17.4.0")) &&
version.GreaterThan(ios.IOS17()) {
log.Warn().Msg("not support ios 17.0-17.3")
continue
}
plist, err := ios.GetValuesPlist(dev)
if err != nil {
log.Error().Err(err).Msg("failed to get device info")
continue
}
deviceInfo := map[string]interface{}{
"udid": properties.SerialNumber,
"platform": "ios",
"brand": "apple",
"model": plist["ProductType"],
"version": plist["ProductVersion"],
}
deviceList = append(deviceList, deviceInfo)
}
}
RenderSuccess(c, deviceList)
}
func pushImageHandler(c *gin.Context) {
var pushMediaReq PushMediaRequest
if err := c.ShouldBindJSON(&pushMediaReq); err != nil {
RenderErrorValidateRequest(c, err)
return return
} }
default: driver, err := GetDriver(c)
{ if err != nil {
c.JSON(http.StatusBadRequest, HttpResponse{
Code: code.GetErrorCode(code.InvalidParamError),
Message: fmt.Sprintf("unsupported platform %s", platform),
})
c.Abort()
return return
} }
imagePath, err := builtin.DownloadFileByUrl(pushMediaReq.ImageUrl)
if path.Ext(imagePath) == "" {
err = os.Rename(imagePath, imagePath+".png")
if err != nil {
RenderError(c, err)
return
} }
imagePath = imagePath + ".png"
}
if err != nil {
RenderError(c, err)
return
}
defer func() {
_ = os.Remove(imagePath)
}()
err = driver.PushImage(imagePath)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
func clearImageHandler(c *gin.Context) {
driver, err := GetDriver(c)
if err != nil {
return
}
err = driver.ClearImages()
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
func videoHandler(c *gin.Context) {
RenderSuccess(c, "")
} }

View File

@ -1,53 +1,74 @@
package server package server
import ( import (
"fmt"
"net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v5/code" "github.com/httprunner/httprunner/v5/pkg/uixt"
) )
func unlockHandler(c *gin.Context) { func unlockHandler(c *gin.Context) {
dExt, err := GetContextDriver(c) driver, err := GetDriver(c)
if err != nil { if err != nil {
return return
} }
err = driver.Unlock()
err = dExt.Unlock()
if err != nil { if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to unlick screen", c.HandlerName())) RenderError(c, err)
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"}) RenderSuccess(c, true)
} }
func homeHandler(c *gin.Context) { func homeHandler(c *gin.Context) {
dExt, err := GetContextDriver(c) driver, err := GetDriver(c)
if err != nil { if err != nil {
return return
} }
err = driver.Home()
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
err = dExt.Home() func backspaceHandler(c *gin.Context) {
if err != nil { var deleteReq DeleteRequest
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to enter homescreen", c.HandlerName())) if err := c.ShouldBindJSON(&deleteReq); err != nil {
c.JSON(http.StatusInternalServerError, RenderErrorValidateRequest(c, err)
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"}) if deleteReq.Count == 0 {
deleteReq.Count = 20
}
driver, err := GetDriver(c)
if err != nil {
return
}
err = driver.Backspace(deleteReq.Count)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
func keycodeHandler(c *gin.Context) {
var keycodeReq KeycodeRequest
if err := c.ShouldBindJSON(&keycodeReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
if err != nil {
return
}
// TODO FIXME
err = driver.IDriver.(*uixt.ADBDriver).
PressKeyCode(uixt.KeyCode(keycodeReq.Keycode), uixt.KMEmpty)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
} }

View File

@ -2,7 +2,9 @@ package server
import ( import (
"fmt" "fmt"
"net/http" "time"
"github.com/httprunner/httprunner/v5/pkg/uixt"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -20,31 +22,45 @@ type Router struct {
func (r *Router) Init() { func (r *Router) Init() {
r.Engine = gin.Default() r.Engine = gin.Default()
r.Engine.Use(teardown())
r.Engine.GET("/ping", pingHandler) r.Engine.GET("/ping", pingHandler)
r.Engine.GET("/", pingHandler)
r.Engine.POST("/", pingHandler)
r.Engine.GET("/api/v1/devices", listDeviceHandler)
apiV1Platform := r.Engine.Group("/api/v1").Group("/:platform") apiV1PlatformSerial := r.Group("/api/v1").Group("/:platform").Group("/:serial")
apiV1Platform.GET("/devices", listDeviceHandler)
apiV1PlatformSerial := apiV1Platform.Group("/:serial")
// UI operations // UI operations
apiV1PlatformSerial.POST("/ui/tap", r.HandleDeviceContext(), tapHandler) apiV1PlatformSerial.POST("/ui/tap", tapHandler)
apiV1PlatformSerial.POST("/ui/drag", r.HandleDeviceContext(), dragHandler) apiV1PlatformSerial.POST("/ui/double_tap", doubleTapHandler)
apiV1PlatformSerial.POST("/ui/input", r.HandleDeviceContext(), inputHandler) apiV1PlatformSerial.POST("/ui/drag", dragHandler)
apiV1PlatformSerial.POST("/ui/input", inputHandler)
apiV1PlatformSerial.POST("/ui/home", homeHandler)
// Key operations // Key operations
apiV1PlatformSerial.POST("/key/unlock", r.HandleDeviceContext(), unlockHandler) apiV1PlatformSerial.POST("/key/unlock", unlockHandler)
apiV1PlatformSerial.POST("/key/home", r.HandleDeviceContext(), homeHandler) apiV1PlatformSerial.POST("/key/home", homeHandler)
// App operations apiV1PlatformSerial.POST("/key/backspace", backspaceHandler)
apiV1PlatformSerial.GET("/app/foreground", r.HandleDeviceContext(), foregroundAppHandler) apiV1PlatformSerial.POST("/key", keycodeHandler)
apiV1PlatformSerial.POST("/app/clear", r.HandleDeviceContext(), clearAppHandler)
apiV1PlatformSerial.POST("/app/launch", r.HandleDeviceContext(), launchAppHandler) // APP operations
apiV1PlatformSerial.POST("/app/terminal", r.HandleDeviceContext(), terminalAppHandler) apiV1PlatformSerial.GET("/app/foreground", foregroundAppHandler)
// get screen info apiV1PlatformSerial.GET("/app/appInfo", appInfoHandler)
apiV1PlatformSerial.GET("/screenshot", r.HandleDeviceContext(), screenshotHandler) apiV1PlatformSerial.POST("/app/clear", clearAppHandler)
apiV1PlatformSerial.POST("/screenresult", r.HandleDeviceContext(), screenResultHandler) apiV1PlatformSerial.POST("/app/launch", launchAppHandler)
apiV1PlatformSerial.GET("/adb/source", r.HandleDeviceContext(), adbSourceHandler) apiV1PlatformSerial.POST("/app/terminal", terminalAppHandler)
// run uixt actions apiV1PlatformSerial.POST("/app/uninstall", uninstallAppHandler)
apiV1PlatformSerial.POST("/uixt/action", r.HandleDeviceContext(), uixtActionHandler)
apiV1PlatformSerial.POST("/uixt/actions", r.HandleDeviceContext(), uixtActionsHandler) // Device operations
apiV1PlatformSerial.GET("/screenshot", screenshotHandler)
apiV1PlatformSerial.GET("/video", videoHandler)
apiV1PlatformSerial.POST("/device/push_image", pushImageHandler)
apiV1PlatformSerial.POST("/device/clear_image", clearImageHandler)
apiV1PlatformSerial.GET("/adb/source", adbSourceHandler)
// uixt operations
apiV1PlatformSerial.POST("/uixt/action", uixtActionHandler)
apiV1PlatformSerial.POST("/uixt/actions", uixtActionsHandler)
} }
func (r *Router) Run(port int) error { func (r *Router) Run(port int) error {
@ -57,5 +73,56 @@ func (r *Router) Run(port int) error {
} }
func pingHandler(c *gin.Context) { func pingHandler(c *gin.Context) {
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"}) RenderSuccess(c, true)
}
func teardown() gin.HandlerFunc {
return func(c *gin.Context) {
logID := c.Request.Header.Get("x-tt-logid")
startTime := time.Now()
// 结束处理后打印日志
fmt.Printf("[GIN] %s | %s | %-7s \"%s\"\n",
startTime.Format("2006/01/02 - 15:04:05"),
logID,
c.Request.Method,
c.Request.URL.Path,
)
// 执行请求处理器
c.Next()
driverObj, exists := c.Get("driver")
if exists {
if driver, ok := driverObj.(*uixt.XTDriver); ok {
_ = driver.TearDown()
}
}
deviceObj, exists := c.Get("device")
if exists {
if device, ok := deviceObj.(*uixt.IOSDevice); ok {
err := device.Teardown()
if err != nil {
log.Error().Err(err)
}
}
}
// 处理请求后获取结束时间
endTime := time.Now()
latency := endTime.Sub(startTime)
// 获取请求的状态码、客户端IP等信息
statusCode := c.Writer.Status()
// 结束处理后打印日志
fmt.Printf("[GIN] %s | %d | %v | %s | %-7s \"%s\"\n",
endTime.Format("2006/01/02 - 15:04:05"),
statusCode,
latency,
logID,
c.Request.Method,
c.Request.URL.Path,
)
c.Writer.Flush()
}
} }

View File

@ -4,50 +4,98 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/option" "github.com/httprunner/httprunner/v5/pkg/uixt/option"
) )
type TapRequest struct {
X float64 `json:"x" binding:"required"`
Y float64 `json:"y" binding:"required"`
Duration float64 `json:"duration"`
Options *option.ActionOptions `json:"options,omitempty"`
}
type DragRequest struct {
FromX float64 `json:"from_x" binding:"required"`
FromY float64 `json:"from_y" binding:"required"`
ToX float64 `json:"to_x" binding:"required"`
ToY float64 `json:"to_y" binding:"required"`
Duration float64 `json:"duration"`
PressDuration float64 `json:"press_duration"`
Options *option.ActionOptions `json:"options,omitempty"`
}
type InputRequest struct {
Text string `json:"text" binding:"required"`
Frequency int `json:"frequency"` // only iOS
}
type DeleteRequest struct {
Count int `json:"count" binding:"required"`
}
type KeycodeRequest struct {
Keycode int `json:"keycode" binding:"required"`
}
type AppClearRequest struct {
PackageName string `json:"packageName" binding:"required"`
}
type AppLaunchRequest struct {
PackageName string `json:"packageName" binding:"required"`
}
type AppTerminalRequest struct {
PackageName string `json:"packageName" binding:"required"`
}
type AppInstallRequest struct {
AppUrl string `json:"appUrl" binding:"required"`
MappingUrl string `json:"mappingUrl"`
ResourceMappingUrl string `json:"resourceMappingUrl"`
PackageName string `json:"packageName"`
}
type AppInfoRequest struct {
PackageName string `form:"packageName" binding:"required"`
}
type AppUninstallRequest struct {
PackageName string `json:"packageName" binding:"required"`
}
type PushMediaRequest struct {
ImageUrl string `json:"imageUrl" binding:"required_without=VideoUrl"`
VideoUrl string `json:"videoUrl" binding:"required_without=ImageUrl"`
}
type OperateRequest struct {
StepText string `json:"stepText" binding:"required"`
}
type HttpResponse struct { type HttpResponse struct {
Code int `json:"code"` Code int `json:"code"`
Message string `json:"msg"` Message string `json:"msg"`
Result interface{} `json:"result,omitempty"` Result interface{} `json:"result,omitempty"`
} }
type TapRequest struct {
X float64 `json:"x"`
Y float64 `json:"y"`
Text string `json:"text"`
Options *option.ActionOptions `json:"options,omitempty"`
}
type DragRequest struct {
FromX float64 `json:"from_x"`
FromY float64 `json:"from_y"`
ToX float64 `json:"to_x"`
ToY float64 `json:"to_y"`
Options *option.ActionOptions `json:"options,omitempty"`
}
type InputRequest struct {
Text string `json:"text"`
Frequency int `json:"frequency"` // only iOS
}
type ScreenRequest struct { type ScreenRequest struct {
Options *option.ScreenOptions `json:"options,omitempty"` Options *option.ScreenOptions `json:"options,omitempty"`
} }
type KeycodeRequest struct { type UploadRequest struct {
Keycode int `json:"keycode"` X float64 `json:"x"`
Y float64 `json:"y"`
FileUrl string `json:"file_url"`
FileFormat string `json:"file_format"`
} }
type AppClearRequest struct { type HoverRequest struct {
PackageName string `json:"packageName"` X float64 `json:"x"`
Y float64 `json:"y"`
} }
type AppLaunchRequest struct { type ScrollRequest struct {
PackageName string `json:"packageName"` Delta int `json:"delta"`
} }
type AppTerminalRequest struct { type CreateBrowserRequest struct {
PackageName string `json:"packageName"` Timeout int `json:"timeout"`
} }

View File

@ -2,7 +2,6 @@ package server
import ( import (
"encoding/base64" "encoding/base64"
"fmt"
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -13,42 +12,28 @@ import (
) )
func screenshotHandler(c *gin.Context) { func screenshotHandler(c *gin.Context) {
dExt, err := GetContextDriver(c) driver, err := GetDriver(c)
if err != nil { if err != nil {
return return
} }
raw, err := dExt.ScreenShot() raw, err := driver.ScreenShot()
if err != nil { if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to get screenshot", c.HandlerName())) RenderError(c, err)
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
RenderSuccess(c, base64.StdEncoding.EncodeToString(raw.Bytes()))
c.JSON(http.StatusOK,
HttpResponse{
Code: code.Success,
Message: "success",
Result: base64.StdEncoding.EncodeToString(raw.Bytes()),
},
)
} }
func screenResultHandler(c *gin.Context) { func screenResultHandler(c *gin.Context) {
dExt, err := GetContextDriver(c) dExt, err := GetDriver(c)
if err != nil { if err != nil {
return return
} }
var screenReq ScreenRequest var screenReq ScreenRequest
if err := c.ShouldBindJSON(&screenReq); err != nil { if err := c.ShouldBindJSON(&screenReq); err != nil {
handlerValidateRequestFailedContext(c, err) RenderErrorValidateRequest(c, err)
return return
} }
@ -69,32 +54,19 @@ func screenResultHandler(c *gin.Context) {
c.Abort() c.Abort()
return return
} }
c.JSON(http.StatusOK, RenderSuccess(c, screenResult)
HttpResponse{
Code: code.Success,
Message: "success",
Result: screenResult,
},
)
} }
func adbSourceHandler(c *gin.Context) { func adbSourceHandler(c *gin.Context) {
dExt, err := GetContextDriver(c) dExt, err := GetDriver(c)
if err != nil { if err != nil {
return return
} }
source, err := dExt.Source() source, err := dExt.Source()
if err != nil { if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to get adb source", c.HandlerName())) RenderError(c, err)
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
c.JSON(http.StatusOK, HttpResponse{Result: source}) RenderSuccess(c, source)
} }

View File

@ -1,157 +1,98 @@
package server package server
import ( import (
"fmt"
"net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v5/code"
"github.com/httprunner/httprunner/v5/pkg/uixt/option" "github.com/httprunner/httprunner/v5/pkg/uixt/option"
) )
func tapHandler(c *gin.Context) { func tapHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
if err != nil {
return
}
var tapReq TapRequest var tapReq TapRequest
if err := c.ShouldBindJSON(&tapReq); err != nil { if err := c.ShouldBindJSON(&tapReq); err != nil {
handlerValidateRequestFailedContext(c, err) RenderErrorValidateRequest(c, err)
return return
} }
driver, err := GetDriver(c)
var actionOptions []option.ActionOption
if tapReq.Options != nil {
actionOptions = tapReq.Options.Options()
}
if tapReq.Text != "" {
err := dExt.TapByOCR(tapReq.Text, actionOptions...)
if err != nil { if err != nil {
log.Err(err).Str("text", tapReq.Text).Msg("tap text failed")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
} else if tapReq.X < 1 && tapReq.Y < 1 {
err := dExt.TapXY(tapReq.X, tapReq.Y, actionOptions...)
if err != nil {
log.Err(err).Float64("x", tapReq.X).Float64("y", tapReq.Y).Msg("tap relative xy failed")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
if tapReq.Duration > 0 {
err = driver.Drag(tapReq.X, tapReq.Y, tapReq.X, tapReq.Y,
option.WithDuration(tapReq.Duration),
option.WithAbsoluteCoordinate(true))
} else { } else {
err := dExt.TapAbsXY(tapReq.X, tapReq.Y, actionOptions...) err = driver.TapAbsXY(tapReq.X, tapReq.Y)
}
if err != nil { if err != nil {
log.Err(err).Float64("x", tapReq.X).Float64("y", tapReq.Y).Msg("tap abs xy failed") RenderError(c, err)
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
RenderSuccess(c, true)
} }
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
func doubleTapHandler(c *gin.Context) {
var tapReq TapRequest
if err := c.ShouldBindJSON(&tapReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
if err != nil {
return
}
if tapReq.X < 1 && tapReq.Y < 1 {
err = driver.DoubleTapXY(tapReq.X, tapReq.Y)
} else {
err = driver.DoubleTapXY(tapReq.X, tapReq.Y,
option.WithAbsoluteCoordinate(true))
}
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
} }
func dragHandler(c *gin.Context) { func dragHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
if err != nil {
return
}
var dragReq DragRequest var dragReq DragRequest
if err := c.ShouldBindJSON(&dragReq); err != nil { if err := c.ShouldBindJSON(&dragReq); err != nil {
handlerValidateRequestFailedContext(c, err) RenderErrorValidateRequest(c, err)
return
}
if dragReq.Duration == 0 {
dragReq.Duration = 1
}
driver, err := GetDriver(c)
if err != nil {
return return
} }
var actionOptions []option.ActionOption err = driver.Drag(dragReq.FromX, dragReq.FromY, dragReq.ToX, dragReq.ToY,
if dragReq.Options != nil { option.WithDuration(dragReq.Duration), option.WithPressDuration(dragReq.PressDuration),
actionOptions = dragReq.Options.Options() option.WithAbsoluteCoordinate(true))
}
if dragReq.FromX < 1 && dragReq.FromY < 1 && dragReq.ToX < 1 && dragReq.ToY < 1 {
err := dExt.Swipe(
dragReq.FromX, dragReq.FromY, dragReq.ToX, dragReq.ToY,
actionOptions...)
if err != nil { if err != nil {
log.Err(err). RenderError(c, err)
Float64("from_x", dragReq.FromX).Float64("from_y", dragReq.FromY).
Float64("to_x", dragReq.ToX).Float64("to_y", dragReq.ToY).
Msg("swipe relative failed")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
} else { RenderSuccess(c, true)
err := dExt.Swipe(
dragReq.FromX, dragReq.FromY, dragReq.ToX, dragReq.ToY,
actionOptions...)
if err != nil {
log.Err(err).
Float64("from_x", dragReq.FromX).Float64("from_y", dragReq.FromY).
Float64("to_x", dragReq.ToX).Float64("to_y", dragReq.ToY).
Msg("swipe absolute failed")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
} }
func inputHandler(c *gin.Context) { func inputHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
if err != nil {
return
}
var inputReq InputRequest var inputReq InputRequest
if err := c.ShouldBindJSON(&inputReq); err != nil { if err := c.ShouldBindJSON(&inputReq); err != nil {
handlerValidateRequestFailedContext(c, err) RenderErrorValidateRequest(c, err)
return return
} }
driver, err := GetDriver(c)
err = dExt.Input(inputReq.Text,
option.WithFrequency(inputReq.Frequency))
if err != nil { if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to input text %s", c.HandlerName(), inputReq.Text))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return return
} }
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"}) err = driver.Input(inputReq.Text, option.WithFrequency(inputReq.Frequency))
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
} }

View File

@ -11,14 +11,14 @@ import (
// exec a single uixt action // exec a single uixt action
func uixtActionHandler(c *gin.Context) { func uixtActionHandler(c *gin.Context) {
dExt, err := GetContextDriver(c) dExt, err := GetDriver(c)
if err != nil { if err != nil {
return return
} }
var req uixt.MobileAction var req uixt.MobileAction
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
handlerValidateRequestFailedContext(c, err) RenderErrorValidateRequest(c, err)
return return
} }
@ -34,20 +34,19 @@ func uixtActionHandler(c *gin.Context) {
c.Abort() c.Abort()
return return
} }
RenderSuccess(c, true)
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
} }
// exec multiple uixt actions // exec multiple uixt actions
func uixtActionsHandler(c *gin.Context) { func uixtActionsHandler(c *gin.Context) {
dExt, err := GetContextDriver(c) dExt, err := GetDriver(c)
if err != nil { if err != nil {
return return
} }
var actions []uixt.MobileAction var actions []uixt.MobileAction
if err := c.ShouldBindJSON(&actions); err != nil { if err := c.ShouldBindJSON(&actions); err != nil {
handlerValidateRequestFailedContext(c, err) RenderErrorValidateRequest(c, err)
return return
} }
@ -65,6 +64,5 @@ func uixtActionsHandler(c *gin.Context) {
return return
} }
} }
RenderSuccess(c, true)
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
} }