refactor: driver Session

This commit is contained in:
lilong.129
2025-02-07 18:02:17 +08:00
parent 91df2906c4
commit 03bdb2b741
12 changed files with 398 additions and 397 deletions

2
go.mod
View File

@@ -1,6 +1,6 @@
module github.com/httprunner/httprunner/v5
go 1.22.0
go 1.23.0
require (
code.byted.org/iesqa/ghdc v0.0.0-20241009025217-ecb76cf5bd27

View File

@@ -1 +1 @@
v5.0.0+2502071738
v5.0.0+2502071804

View File

@@ -30,7 +30,7 @@ func NewADBDriver(device *AndroidDevice) (*ADBDriver, error) {
log.Info().Interface("device", device).Msg("init android adb driver")
driver := &ADBDriver{
AndroidDevice: device,
DriverSession: &DriverSession{},
Session: &Session{},
}
driver.NewSession(nil)
return driver, nil
@@ -38,7 +38,7 @@ func NewADBDriver(device *AndroidDevice) (*ADBDriver, error) {
type ADBDriver struct {
*AndroidDevice
*DriverSession
*Session
}
func (ad *ADBDriver) runShellCommand(cmd string, args ...string) (output string, err error) {
@@ -74,7 +74,7 @@ func (ad *ADBDriver) runShellCommand(cmd string, args ...string) (output string,
return output, err
}
func (ad *ADBDriver) NewSession(capabilities option.Capabilities) (sessionInfo SessionInfo, err error) {
func (ad *ADBDriver) NewSession(capabilities option.Capabilities) (sessionInfo Session, err error) {
ad.Reset()
err = errDriverNotImplemented
return
@@ -857,8 +857,8 @@ func (ad *ADBDriver) StopCaptureLog() (result interface{}, err error) {
return pointRes, nil
}
func (ad *ADBDriver) GetSession() *DriverSession {
return ad.DriverSession
func (ad *ADBDriver) GetSession() *Session {
return ad.Session
}
func (ad *ADBDriver) GetDriverResults() []*DriverRequests {

View File

@@ -51,7 +51,7 @@ func NewStubDriver(device *AndroidDevice) (driver *StubAndroidDriver, err error)
rawURL := fmt.Sprintf("http://forward-to-%d:%d",
serverLocalPort, DouyinServerPort)
if driver.urlPrefix, err = url.Parse(rawURL); err != nil {
if driver.baseURL, err = url.Parse(rawURL); err != nil {
return nil, err
}
@@ -77,7 +77,7 @@ type AppLoginInfo struct {
func (sad *StubAndroidDriver) httpGET(pathElem ...string) (rawResp rawResponse, err error) {
var localPort int
{
tmpURL, _ := url.Parse(sad.urlPrefix.String())
tmpURL, _ := url.Parse(sad.baseURL.String())
hostname := tmpURL.Hostname()
if strings.HasPrefix(hostname, forwardToPrefix) {
localPort, _ = strconv.Atoi(strings.TrimPrefix(hostname, forwardToPrefix))
@@ -88,14 +88,14 @@ func (sad *StubAndroidDriver) httpGET(pathElem ...string) (rawResp rawResponse,
if err != nil {
return nil, fmt.Errorf("adb forward: %w", err)
}
sad.Client = convertToHTTPClient(conn)
sad.client = convertToHTTPClient(conn)
return sad.Request(http.MethodGet, sad.concatURL(nil, pathElem...), nil)
}
func (sad *StubAndroidDriver) httpPOST(data interface{}, pathElem ...string) (rawResp rawResponse, err error) {
var localPort int
{
tmpURL, _ := url.Parse(sad.urlPrefix.String())
tmpURL, _ := url.Parse(sad.baseURL.String())
hostname := tmpURL.Hostname()
if strings.HasPrefix(hostname, forwardToPrefix) {
localPort, _ = strconv.Atoi(strings.TrimPrefix(hostname, forwardToPrefix))
@@ -106,7 +106,7 @@ func (sad *StubAndroidDriver) httpPOST(data interface{}, pathElem ...string) (ra
if err != nil {
return nil, fmt.Errorf("adb forward: %w", err)
}
sad.Client = convertToHTTPClient(conn)
sad.client = convertToHTTPClient(conn)
var bsJSON []byte = nil
if data != nil {
@@ -117,9 +117,9 @@ func (sad *StubAndroidDriver) httpPOST(data interface{}, pathElem ...string) (ra
return sad.Request(http.MethodPost, sad.concatURL(nil, pathElem...), bsJSON)
}
func (sad *StubAndroidDriver) NewSession(capabilities option.Capabilities) (SessionInfo, error) {
func (sad *StubAndroidDriver) NewSession(capabilities option.Capabilities) (Session, error) {
sad.Reset()
return SessionInfo{}, errDriverNotImplemented
return Session{}, errDriverNotImplemented
}
func (sad *StubAndroidDriver) sendCommand(packageName string, cmdType string, params map[string]interface{}, readTimeout ...time.Duration) (interface{}, error) {

View File

@@ -36,7 +36,7 @@ func NewUIA2Driver(device *AndroidDevice) (*UIA2Driver, error) {
return nil, fmt.Errorf("adb forward: %w", err)
}
driver := new(UIA2Driver)
driver.Client = convertToHTTPClient(conn)
driver.client = convertToHTTPClient(conn)
driver.Device = device.Device
driver.Logcat = device.Logcat
@@ -56,7 +56,7 @@ func (ud *UIA2Driver) resetDriver() error {
if err != nil {
return err
}
ud.SessionID = session.SessionId
ud.sessionID = session.sessionID
return nil
}
@@ -68,14 +68,14 @@ func (ud *UIA2Driver) httpRequest(method string, rawURL string, rawBody []byte)
}
// wait for UIA2 server to resume automatically
time.Sleep(3 * time.Second)
oldSessionID := ud.SessionID
oldSessionID := ud.sessionID
if err2 := ud.resetDriver(); err2 != nil {
log.Err(err2).Msgf("failed to reset uia2 driver, retry count: %v", retryCount)
continue
}
log.Debug().Str("new session", ud.SessionID).Str("old session", oldSessionID).Msgf("successful to reset uia2 driver, retry count: %v", retryCount)
log.Debug().Str("new session", ud.sessionID).Str("old session", oldSessionID).Msgf("successful to reset uia2 driver, retry count: %v", retryCount)
if oldSessionID != "" {
rawURL = strings.Replace(rawURL, oldSessionID, ud.SessionID, 1)
rawURL = strings.Replace(rawURL, oldSessionID, ud.sessionID, 1)
}
}
return
@@ -99,7 +99,7 @@ func (ud *UIA2Driver) httpDELETE(pathElem ...string) (rawResp rawResponse, err e
return ud.httpRequest(http.MethodDelete, ud.concatURL(nil, pathElem...), nil)
}
func (ud *UIA2Driver) NewSession(capabilities option.Capabilities) (sessionInfo SessionInfo, err error) {
func (ud *UIA2Driver) NewSession(capabilities option.Capabilities) (sessionInfo Session, err error) {
// register(postHandler, new NewSession("/wd/hub/session"))
var rawResp rawResponse
data := make(map[string]interface{})
@@ -109,25 +109,25 @@ func (ud *UIA2Driver) NewSession(capabilities option.Capabilities) (sessionInfo
data["capabilities"] = map[string]interface{}{"alwaysMatch": capabilities}
}
if rawResp, err = ud.POST(data, "/session"); err != nil {
return SessionInfo{SessionId: ""}, err
return Session{sessionID: ""}, err
}
reply := new(struct{ Value struct{ SessionId string } })
if err = json.Unmarshal(rawResp, reply); err != nil {
return SessionInfo{SessionId: ""}, err
return Session{sessionID: ""}, err
}
sessionID := reply.Value.SessionId
ud.Reset()
ud.SessionID = sessionID
ud.sessionID = sessionID
// d.sessionIdCache[sessionID] = true
return SessionInfo{SessionId: sessionID}, nil
return Session{sessionID: sessionID}, nil
}
func (ud *UIA2Driver) DeleteSession() (err error) {
if ud.SessionID == "" {
if ud.sessionID == "" {
return nil
}
if _, err = ud.httpDELETE("/session", ud.SessionID); err == nil {
ud.SessionID = ""
if _, err = ud.httpDELETE("/session", ud.sessionID); err == nil {
ud.sessionID = ""
}
return err
@@ -155,7 +155,7 @@ func (ud *UIA2Driver) Status() (deviceStatus DeviceStatus, err error) {
func (ud *UIA2Driver) DeviceInfo() (deviceInfo DeviceInfo, err error) {
// register(getHandler, new GetDeviceInfo("/wd/hub/session/:sessionId/appium/device/info"))
var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.SessionID, "appium/device/info"); err != nil {
if rawResp, err = ud.httpGET("/session", ud.sessionID, "appium/device/info"); err != nil {
return DeviceInfo{}, err
}
reply := new(struct{ Value struct{ DeviceInfo } })
@@ -169,7 +169,7 @@ func (ud *UIA2Driver) DeviceInfo() (deviceInfo DeviceInfo, err error) {
func (ud *UIA2Driver) BatteryInfo() (batteryInfo BatteryInfo, err error) {
// register(getHandler, new GetBatteryInfo("/wd/hub/session/:sessionId/appium/device/battery_info"))
var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.SessionID, "appium/device/battery_info"); err != nil {
if rawResp, err = ud.httpGET("/session", ud.sessionID, "appium/device/battery_info"); err != nil {
return BatteryInfo{}, err
}
reply := new(struct{ Value struct{ BatteryInfo } })
@@ -191,7 +191,7 @@ func (ud *UIA2Driver) WindowSize() (size Size, err error) {
}
var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.SessionID, "window/:windowHandle/size"); err != nil {
if rawResp, err = ud.httpGET("/session", ud.sessionID, "window/:windowHandle/size"); err != nil {
return Size{}, errors.Wrap(err, "get window size failed by UIA2 request")
}
reply := new(struct{ Value struct{ Size } })
@@ -217,7 +217,7 @@ func (ud *UIA2Driver) WindowSize() (size Size, err error) {
// PressBack simulates a short press on the BACK button.
func (ud *UIA2Driver) PressBack(opts ...option.ActionOption) (err error) {
// register(postHandler, new PressBack("/wd/hub/session/:sessionId/back"))
_, err = ud.httpPOST(nil, "/session", ud.SessionID, "back")
_, err = ud.httpPOST(nil, "/session", ud.sessionID, "back")
return
}
@@ -240,14 +240,14 @@ func (ud *UIA2Driver) PressKeyCodes(keyCode KeyCode, metaState KeyMeta, flags ..
if len(flags) != 0 {
data["flags"] = flags[0]
}
_, err = ud.httpPOST(data, "/session", ud.SessionID, "appium/device/press_keycode")
_, err = ud.httpPOST(data, "/session", ud.sessionID, "appium/device/press_keycode")
return
}
func (ud *UIA2Driver) Orientation() (orientation Orientation, err error) {
// [[FBRoute GET:@"/orientation"] respondWithTarget:self action:@selector(handleGetOrientation:)]
var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.SessionID, "/orientation"); err != nil {
if rawResp, err = ud.httpGET("/session", ud.sessionID, "/orientation"); err != nil {
return "", err
}
reply := new(struct{ Value Orientation })
@@ -280,7 +280,7 @@ func (ud *UIA2Driver) DoubleFloatTap(x, y float64) error {
},
}
_, err := ud.httpPOST(data, "/session", ud.SessionID, "actions/tap")
_, err := ud.httpPOST(data, "/session", ud.sessionID, "actions/tap")
return err
}
@@ -318,7 +318,7 @@ func (ud *UIA2Driver) Tap(x, y float64, opts ...option.ActionOption) (err error)
// update data options in post data for extra uiautomator configurations
actionOptions.UpdateData(data)
_, err = ud.httpPOST(data, "/session", ud.SessionID, "actions/tap")
_, err = ud.httpPOST(data, "/session", ud.sessionID, "actions/tap")
return err
}
@@ -336,7 +336,7 @@ func (ud *UIA2Driver) TouchAndHold(x, y float64, opts ...option.ActionOption) (e
"duration": int(duration * 1000),
},
}
_, err = ud.httpPOST(data, "/session", ud.SessionID, "touch/longclick")
_, err = ud.httpPOST(data, "/session", ud.sessionID, "touch/longclick")
return
}
@@ -368,7 +368,7 @@ func (ud *UIA2Driver) Drag(fromX, fromY, toX, toY float64, opts ...option.Action
actionOptions.UpdateData(data)
// register(postHandler, new Drag("/wd/hub/session/:sessionId/touch/drag"))
_, err = ud.httpPOST(data, "/session", ud.SessionID, "touch/drag")
_, err = ud.httpPOST(data, "/session", ud.sessionID, "touch/drag")
return
}
@@ -414,7 +414,7 @@ func (ud *UIA2Driver) Swipe(fromX, fromY, toX, toY float64, opts ...option.Actio
// update data options in post data for extra uiautomator configurations
actionOptions.UpdateData(data)
_, err := ud.httpPOST(data, "/session", ud.SessionID, "actions/swipe")
_, err := ud.httpPOST(data, "/session", ud.sessionID, "actions/swipe")
return err
}
@@ -432,7 +432,7 @@ func (ud *UIA2Driver) SetPasteboard(contentType PasteboardType, content string)
"content": base64.StdEncoding.EncodeToString([]byte(content)),
}
// register(postHandler, new SetClipboard("/wd/hub/session/:sessionId/appium/device/set_clipboard"))
_, err = ud.httpPOST(data, "/session", ud.SessionID, "appium/device/set_clipboard")
_, err = ud.httpPOST(data, "/session", ud.sessionID, "appium/device/set_clipboard")
return
}
@@ -445,7 +445,7 @@ func (ud *UIA2Driver) GetPasteboard(contentType PasteboardType) (raw *bytes.Buff
"contentType": contentType[0],
}
var rawResp rawResponse
if rawResp, err = ud.httpPOST(data, "/session", ud.SessionID, "appium/device/get_clipboard"); err != nil {
if rawResp, err = ud.httpPOST(data, "/session", ud.sessionID, "appium/device/get_clipboard"); err != nil {
return
}
reply := new(struct{ Value string })
@@ -475,7 +475,7 @@ func (ud *UIA2Driver) SendKeys(text string, opts ...option.ActionOption) (err er
// new data options in post data for extra uiautomator configurations
actionOptions.UpdateData(data)
_, err = ud.httpPOST(data, "/session", ud.SessionID, "/keys")
_, err = ud.httpPOST(data, "/session", ud.sessionID, "/keys")
}
return
}
@@ -533,7 +533,7 @@ func (ud *UIA2Driver) SendActionKey(text string, opts ...option.ActionOption) (e
// new data options in post data for extra uiautomator configurations
actionOptions.UpdateData(data)
_, err = ud.httpPOST(data, "/session", ud.SessionID, "/actions/keys")
_, err = ud.httpPOST(data, "/session", ud.sessionID, "/actions/keys")
return
}
@@ -544,7 +544,7 @@ func (ud *UIA2Driver) Input(text string, opts ...option.ActionOption) (err error
func (ud *UIA2Driver) Rotation() (rotation Rotation, err error) {
// register(getHandler, new GetRotation("/wd/hub/session/:sessionId/rotation"))
var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.SessionID, "rotation"); err != nil {
if rawResp, err = ud.httpGET("/session", ud.sessionID, "rotation"); err != nil {
return Rotation{}, err
}
reply := new(struct{ Value Rotation })
@@ -565,7 +565,7 @@ func (ud *UIA2Driver) Screenshot() (raw *bytes.Buffer, err error) {
func (ud *UIA2Driver) Source(srcOpt ...option.SourceOption) (source string, err error) {
// register(getHandler, new Source("/wd/hub/session/:sessionId/source"))
var rawResp rawResponse
if rawResp, err = ud.httpGET("/session", ud.SessionID, "source"); err != nil {
if rawResp, err = ud.httpGET("/session", ud.sessionID, "source"); err != nil {
return "", err
}
reply := new(struct{ Value string })

View File

@@ -2,32 +2,27 @@ package uixt
import (
"bytes"
"context"
"encoding/json"
"encoding/base64"
builtinJSON "encoding/json"
"fmt"
_ "image/gif"
_ "image/png"
"io"
"net"
"net/http"
"net/url"
"path"
"strings"
"regexp"
"time"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v5/internal/builtin"
"github.com/httprunner/httprunner/v5/internal/config"
"github.com/httprunner/httprunner/v5/internal/json"
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
)
// current implemeted driver: ADBDriver, UIA2Driver, WDADriver, HDCDriver
type IDriver interface {
// NewSession starts a new session and returns the SessionInfo.
NewSession(capabilities option.Capabilities) (SessionInfo, error)
// NewSession starts a new session and returns the DriverSession.
NewSession(capabilities option.Capabilities) (Session, error)
// DeleteSession Kills application associated with that session and removes session
// 1) alertsMonitor disable
@@ -35,7 +30,7 @@ type IDriver interface {
DeleteSession() error
// GetSession returns session cache, including requests, screenshots, etc.
GetSession() *DriverSession
GetSession() *Session
Status() (DeviceStatus, error)
@@ -170,199 +165,6 @@ type IDriver interface {
TearDown() error
}
type SessionInfo struct {
SessionId string `json:"sessionId"`
Capabilities struct {
Device string `json:"device"`
BrowserName string `json:"browserName"`
SdkVersion string `json:"sdkVersion"`
CFBundleIdentifier string `json:"CFBundleIdentifier"`
} `json:"capabilities"`
}
type DriverSession struct {
// ctx context.Context
SessionID string
urlPrefix *url.URL
Client *http.Client
// cache to avoid repeated query
scale float64
windowSize Size
// cache uia2/wda request and response
requests []*DriverRequests
// cache screenshot ocr results
screenResults []*ScreenResult
// cache e2e delay
e2eDelay []timeLog
}
func (d *DriverSession) addScreenResult(screenResult *ScreenResult) {
d.screenResults = append(d.screenResults, screenResult)
}
func (d *DriverSession) addRequestResult(driverResult *DriverRequests) {
d.requests = append(d.requests, driverResult)
}
func (d *DriverSession) Reset() {
d.screenResults = make([]*ScreenResult, 0)
d.requests = make([]*DriverRequests, 0)
d.e2eDelay = nil
}
type Attachments map[string]interface{}
func (d *DriverSession) Get(withReset bool) Attachments {
data := Attachments{
"screen_results": d.screenResults,
}
if len(d.requests) != 0 {
data["requests"] = d.requests
}
if d.e2eDelay != nil {
data["e2e_results"] = d.e2eDelay
}
if withReset {
d.Reset()
}
return data
}
type DriverRequests struct {
RequestMethod string `json:"request_method"`
RequestUrl string `json:"request_url"`
RequestBody string `json:"request_body,omitempty"`
RequestTime time.Time `json:"request_time"`
ResponseStatus int `json:"response_status"`
ResponseDuration int64 `json:"response_duration(ms)"` // ms
ResponseBody string `json:"response_body"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
func (wd *DriverSession) concatURL(u *url.URL, elem ...string) string {
var tmp *url.URL
if u == nil {
u = wd.urlPrefix
}
tmp, _ = url.Parse(u.String())
tmp.Path = path.Join(append([]string{u.Path}, elem...)...)
return tmp.String()
}
func (wd *DriverSession) GET(pathElem ...string) (rawResp rawResponse, err error) {
return wd.Request(http.MethodGet, wd.concatURL(nil, pathElem...), nil)
}
func (wd *DriverSession) POST(data interface{}, pathElem ...string) (rawResp rawResponse, err error) {
var bsJSON []byte = nil
if data != nil {
if bsJSON, err = json.Marshal(data); err != nil {
return nil, err
}
}
return wd.Request(http.MethodPost, wd.concatURL(nil, pathElem...), bsJSON)
}
func (wd *DriverSession) DELETE(pathElem ...string) (rawResp rawResponse, err error) {
return wd.Request(http.MethodDelete, wd.concatURL(nil, pathElem...), nil)
}
func (wd *DriverSession) Request(method string, rawURL string, rawBody []byte) (rawResp rawResponse, err error) {
driverResult := &DriverRequests{
RequestMethod: method,
RequestUrl: rawURL,
RequestBody: string(rawBody),
}
defer func() {
wd.addRequestResult(driverResult)
var logger *zerolog.Event
if err != nil {
driverResult.Success = false
driverResult.Error = err.Error()
logger = log.Error().Bool("success", false).Err(err)
} else {
driverResult.Success = true
logger = log.Debug().Bool("success", true)
}
logger = logger.Str("request_method", method).Str("request_url", rawURL).
Str("request_body", string(rawBody))
if !driverResult.RequestTime.IsZero() {
logger = logger.Int64("request_time", driverResult.RequestTime.UnixMilli())
}
if driverResult.ResponseStatus != 0 {
logger = logger.
Int("response_status", driverResult.ResponseStatus).
Int64("response_duration(ms)", driverResult.ResponseDuration).
Str("response_body", driverResult.ResponseBody)
}
logger.Msg("request uixt driver")
}()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var req *http.Request
if req, err = http.NewRequestWithContext(ctx, method, rawURL, bytes.NewBuffer(rawBody)); err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("Accept", "application/json")
driverResult.RequestTime = time.Now()
var resp *http.Response
if resp, err = wd.Client.Do(req); err != nil {
return nil, err
}
defer func() {
// https://github.com/etcd-io/etcd/blob/v3.3.25/pkg/httputil/httputil.go#L16-L22
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}()
rawResp, err = io.ReadAll(resp.Body)
duration := time.Since(driverResult.RequestTime)
driverResult.ResponseDuration = duration.Milliseconds()
driverResult.ResponseStatus = resp.StatusCode
if strings.HasSuffix(rawURL, "screenshot") {
// avoid printing screenshot data
driverResult.ResponseBody = "OMITTED"
} else {
driverResult.ResponseBody = string(rawResp)
}
if err != nil {
return nil, err
}
if err = rawResp.checkErr(); err != nil {
if resp.StatusCode == http.StatusOK {
return rawResp, nil
}
return nil, err
}
return
}
func convertToHTTPClient(conn net.Conn) *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return conn, nil
},
},
Timeout: 30 * time.Second,
}
}
type DriverExt struct {
Device IDevice
Driver IDriver
@@ -475,3 +277,85 @@ func (dExt *DriverExt) DoValidation(check, assert, expected string, message ...s
log.Info().Str("assert", assert).Str("expect", expected).Msg("validate success")
return nil
}
type rawResponse []byte
func (r rawResponse) checkErr() (err error) {
reply := new(struct {
Value struct {
Err string `json:"error"`
Message string `json:"message"`
Traceback string `json:"traceback"` // wda
Stacktrace string `json:"stacktrace"` // uia
}
})
if err = json.Unmarshal(r, reply); err != nil {
return err
}
if reply.Value.Err != "" {
errText := reply.Value.Message
re := regexp.MustCompile(`{.+?=(.+?)}`)
if re.MatchString(reply.Value.Message) {
subMatch := re.FindStringSubmatch(reply.Value.Message)
errText = subMatch[len(subMatch)-1]
}
return fmt.Errorf("%s: %s", reply.Value.Err, errText)
}
return
}
func (r rawResponse) valueConvertToString() (s string, err error) {
reply := new(struct{ Value string })
if err = json.Unmarshal(r, reply); err != nil {
return "", errors.Wrapf(err, "json.Unmarshal failed, rawResponse: %s", string(r))
}
s = reply.Value
return
}
func (r rawResponse) valueConvertToBool() (b bool, err error) {
reply := new(struct{ Value bool })
if err = json.Unmarshal(r, reply); err != nil {
return false, err
}
b = reply.Value
return
}
func (r rawResponse) valueConvertToSessionInfo() (sessionInfo Session, err error) {
reply := new(struct{ Value struct{ Session } })
if err = json.Unmarshal(r, reply); err != nil {
return Session{}, err
}
sessionInfo = reply.Value.Session
return
}
func (r rawResponse) valueConvertToJsonRawMessage() (raw builtinJSON.RawMessage, err error) {
reply := new(struct{ Value builtinJSON.RawMessage })
if err = json.Unmarshal(r, reply); err != nil {
return nil, err
}
raw = reply.Value
return
}
func (r rawResponse) valueConvertToJsonObject() (obj map[string]interface{}, err error) {
if err = json.Unmarshal(r, &obj); err != nil {
return nil, err
}
return
}
func (r rawResponse) valueDecodeAsBase64() (raw *bytes.Buffer, err error) {
str, err := r.valueConvertToString()
if err != nil {
return nil, errors.Wrap(err, "failed to convert value to string")
}
decodeString, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return nil, errors.Wrap(err, "failed to decode base64 string")
}
raw = bytes.NewBuffer(decodeString)
return
}

200
pkg/uixt/driver_session.go Normal file
View File

@@ -0,0 +1,200 @@
package uixt
import (
"bytes"
"context"
"io"
"net"
"net/http"
"net/url"
"path"
"strings"
"time"
"github.com/httprunner/httprunner/v5/internal/json"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type Session struct {
// ctx context.Context
sessionID string
baseURL *url.URL
client *http.Client
// cache to avoid repeated query
scale float64
windowSize Size
// cache uia2/wda request and response
requests []*DriverRequests
// cache screenshot ocr results
screenResults []*ScreenResult
// cache e2e delay
e2eDelay []timeLog
}
func (d *Session) addScreenResult(screenResult *ScreenResult) {
d.screenResults = append(d.screenResults, screenResult)
}
func (d *Session) addRequestResult(driverResult *DriverRequests) {
d.requests = append(d.requests, driverResult)
}
func (d *Session) Reset() {
d.screenResults = make([]*ScreenResult, 0)
d.requests = make([]*DriverRequests, 0)
d.e2eDelay = nil
}
type Attachments map[string]interface{}
func (d *Session) GetData(withReset bool) Attachments {
data := Attachments{
"screen_results": d.screenResults,
}
if len(d.requests) != 0 {
data["requests"] = d.requests
}
if d.e2eDelay != nil {
data["e2e_results"] = d.e2eDelay
}
if withReset {
d.Reset()
}
return data
}
type DriverRequests struct {
RequestMethod string `json:"request_method"`
RequestUrl string `json:"request_url"`
RequestBody string `json:"request_body,omitempty"`
RequestTime time.Time `json:"request_time"`
ResponseStatus int `json:"response_status"`
ResponseDuration int64 `json:"response_duration(ms)"` // ms
ResponseBody string `json:"response_body"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
func (wd *Session) concatURL(u *url.URL, elem ...string) string {
var tmp *url.URL
if u == nil {
u = wd.baseURL
}
tmp, _ = url.Parse(u.String())
tmp.Path = path.Join(append([]string{u.Path}, elem...)...)
return tmp.String()
}
func (wd *Session) GET(pathElem ...string) (rawResp rawResponse, err error) {
return wd.Request(http.MethodGet, wd.concatURL(nil, pathElem...), nil)
}
func (wd *Session) POST(data interface{}, pathElem ...string) (rawResp rawResponse, err error) {
var bsJSON []byte = nil
if data != nil {
if bsJSON, err = json.Marshal(data); err != nil {
return nil, err
}
}
return wd.Request(http.MethodPost, wd.concatURL(nil, pathElem...), bsJSON)
}
func (wd *Session) DELETE(pathElem ...string) (rawResp rawResponse, err error) {
return wd.Request(http.MethodDelete, wd.concatURL(nil, pathElem...), nil)
}
func (wd *Session) Request(method string, rawURL string, rawBody []byte) (rawResp rawResponse, err error) {
driverResult := &DriverRequests{
RequestMethod: method,
RequestUrl: rawURL,
RequestBody: string(rawBody),
}
defer func() {
wd.addRequestResult(driverResult)
var logger *zerolog.Event
if err != nil {
driverResult.Success = false
driverResult.Error = err.Error()
logger = log.Error().Bool("success", false).Err(err)
} else {
driverResult.Success = true
logger = log.Debug().Bool("success", true)
}
logger = logger.Str("request_method", method).Str("request_url", rawURL).
Str("request_body", string(rawBody))
if !driverResult.RequestTime.IsZero() {
logger = logger.Int64("request_time", driverResult.RequestTime.UnixMilli())
}
if driverResult.ResponseStatus != 0 {
logger = logger.
Int("response_status", driverResult.ResponseStatus).
Int64("response_duration(ms)", driverResult.ResponseDuration).
Str("response_body", driverResult.ResponseBody)
}
logger.Msg("request uixt driver")
}()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var req *http.Request
if req, err = http.NewRequestWithContext(ctx, method, rawURL, bytes.NewBuffer(rawBody)); err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("Accept", "application/json")
driverResult.RequestTime = time.Now()
var resp *http.Response
if resp, err = wd.client.Do(req); err != nil {
return nil, err
}
defer func() {
// https://github.com/etcd-io/etcd/blob/v3.3.25/pkg/httputil/httputil.go#L16-L22
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}()
rawResp, err = io.ReadAll(resp.Body)
duration := time.Since(driverResult.RequestTime)
driverResult.ResponseDuration = duration.Milliseconds()
driverResult.ResponseStatus = resp.StatusCode
if strings.HasSuffix(rawURL, "screenshot") {
// avoid printing screenshot data
driverResult.ResponseBody = "OMITTED"
} else {
driverResult.ResponseBody = string(rawResp)
}
if err != nil {
return nil, err
}
if err = rawResp.checkErr(); err != nil {
if resp.StatusCode == http.StatusOK {
return rawResp, nil
}
return nil, err
}
return
}
func convertToHTTPClient(conn net.Conn) *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return conn, nil
},
},
Timeout: 30 * time.Second,
}
}

View File

@@ -15,7 +15,7 @@ import (
type hdcDriver struct {
*HarmonyDevice
*DriverSession
*Session
points []ExportPoint
uiDriver *ghdc.UIDriver
}
@@ -41,18 +41,18 @@ func newHarmonyDriver(device *ghdc.Device) (driver *hdcDriver, err error) {
return
}
func (hd *hdcDriver) NewSession(capabilities option.Capabilities) (SessionInfo, error) {
func (hd *hdcDriver) NewSession(capabilities option.Capabilities) (Session, error) {
hd.Reset()
hd.Unlock()
return SessionInfo{}, errDriverNotImplemented
return Session{}, errDriverNotImplemented
}
func (hd *hdcDriver) DeleteSession() error {
return errDriverNotImplemented
}
func (hd *hdcDriver) GetSession() *DriverSession {
return hd.DriverSession
func (hd *hdcDriver) GetSession() *Session {
return hd.Session
}
func (hd *hdcDriver) Status() (DeviceStatus, error) {

View File

@@ -567,21 +567,21 @@ func (dev *IOSDevice) NewHTTPDriver(capabilities option.Capabilities) (driver ID
wd := new(wdaDriver)
wd.IOSDevice = dev
wd.udid = dev.UDID
wd.Client = &http.Client{
wd.client = &http.Client{
Timeout: time.Second * 10, // 设置超时时间为 10 秒
}
host := "localhost"
if wd.urlPrefix, err = url.Parse(fmt.Sprintf("http://%s:%d", host, localPort)); err != nil {
if wd.baseURL, err = url.Parse(fmt.Sprintf("http://%s:%d", host, localPort)); err != nil {
return nil, errors.Wrap(code.DeviceHTTPDriverError, err.Error())
}
// create new session
var sessionInfo SessionInfo
var sessionInfo Session
if sessionInfo, err = wd.NewSession(capabilities); err != nil {
return nil, errors.Wrap(code.DeviceHTTPDriverError, err.Error())
}
wd.SessionID = sessionInfo.SessionId
wd.sessionID = sessionInfo.sessionID
if wd.mjpegHTTPConn, err = net.Dial(
"tcp",

View File

@@ -31,7 +31,7 @@ func newStubIOSDriver(bightInsightAddr, serverAddr string, dev *IOSDevice, readT
driver.bightInsightPrefix = bightInsightAddr
driver.serverPrefix = serverAddr
driver.timeout = timeout
driver.Client = &http.Client{
driver.client = &http.Client{
Timeout: time.Second * 10, // 设置超时时间为 10 秒
}
return driver, nil
@@ -51,11 +51,11 @@ func (s *stubIOSDriver) setUpWda() (err error) {
return nil
}
// NewSession starts a new session and returns the SessionInfo.
func (s *stubIOSDriver) NewSession(capabilities option.Capabilities) (SessionInfo, error) {
// NewSession starts a new session and returns the DriverSession.
func (s *stubIOSDriver) NewSession(capabilities option.Capabilities) (Session, error) {
err := s.setUpWda()
if err != nil {
return SessionInfo{}, err
return Session{}, err
}
return s.wdaDriver.NewSession(capabilities)
}
@@ -515,7 +515,7 @@ func (s *stubIOSDriver) LogoutNoneUI(packageName string) error {
}
func (s *stubIOSDriver) TearDown() error {
s.Client.CloseIdleConnections()
s.client.CloseIdleConnections()
return nil
}
@@ -541,6 +541,6 @@ func (s *stubIOSDriver) getLoginAppInfo(packageName string) (info AppLoginInfo,
return info, nil
}
func (s *stubIOSDriver) GetSession() *DriverSession {
return s.DriverSession
func (s *stubIOSDriver) GetSession() *Session {
return s.Session
}

View File

@@ -13,7 +13,6 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"syscall"
"time"
@@ -29,7 +28,7 @@ import (
type wdaDriver struct {
*IOSDevice
*DriverSession
*Session
udid string
mjpegHTTPConn net.Conn // via HTTP
mjpegClient *http.Client
@@ -47,7 +46,7 @@ func (wd *wdaDriver) resetSession() error {
}
// Notice: use Driver.POST instead of httpPOST to avoid loop calling
rawResp, err := wd.DriverSession.POST(data, "/session")
rawResp, err := wd.Session.POST(data, "/session")
if err != nil {
return err
}
@@ -56,7 +55,7 @@ func (wd *wdaDriver) resetSession() error {
return err
}
// update session ID
wd.SessionID = sessionInfo.SessionId
wd.sessionID = sessionInfo.sessionID
return nil
}
@@ -80,15 +79,15 @@ func (wd *wdaDriver) httpRequest(method string, rawURL string, rawBody []byte) (
retryInterval = retryInterval * 2
time.Sleep(retryInterval)
oldSessionID := wd.SessionID
oldSessionID := wd.sessionID
if err2 := wd.resetSession(); err2 != nil {
log.Err(err2).Msgf("failed to reset wda driver session, retry count: %v", retryCount)
continue
}
log.Debug().Str("new session", wd.SessionID).Str("old session", oldSessionID).
log.Debug().Str("new session", wd.sessionID).Str("old session", oldSessionID).
Msgf("reset wda driver session successfully, retry count: %v", retryCount)
if oldSessionID != "" {
rawURL = strings.Replace(rawURL, oldSessionID, wd.SessionID, 1)
rawURL = strings.Replace(rawURL, oldSessionID, wd.sessionID, 1)
}
}
return
@@ -116,7 +115,7 @@ func (wd *wdaDriver) GetMjpegClient() *http.Client {
return wd.mjpegClient
}
func (wd *wdaDriver) NewSession(capabilities option.Capabilities) (sessionInfo SessionInfo, err error) {
func (wd *wdaDriver) NewSession(capabilities option.Capabilities) (sessionInfo Session, err error) {
// [[FBRoute POST:@"/session"].withoutSession respondWithTarget:self action:@selector(handleCreateSession:)]
data := make(map[string]interface{})
if len(capabilities) == 0 {
@@ -129,10 +128,10 @@ func (wd *wdaDriver) NewSession(capabilities option.Capabilities) (sessionInfo S
var rawResp rawResponse
if rawResp, err = wd.httpPOST(data, "/session"); err != nil {
return SessionInfo{}, err
return Session{}, err
}
if sessionInfo, err = rawResp.valueConvertToSessionInfo(); err != nil {
return SessionInfo{}, err
return Session{}, err
}
return
}
@@ -146,7 +145,7 @@ func (wd *wdaDriver) DeleteSession() (err error) {
}
// [[FBRoute DELETE:@""] respondWithTarget:self action:@selector(handleDeleteSession:)]
_, err = wd.httpDELETE("/session", wd.SessionID)
_, err = wd.httpDELETE("/session", wd.sessionID)
return
}
@@ -169,7 +168,7 @@ func (wd *wdaDriver) DeviceInfo() (deviceInfo DeviceInfo, err error) {
// [[FBRoute GET:@"/wda/device/info"] respondWithTarget:self action:@selector(handleGetDeviceInfo:)]
// [[FBRoute GET:@"/wda/device/info"].withoutSession
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/wda/device/info"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/wda/device/info"); err != nil {
return DeviceInfo{}, err
}
reply := new(struct{ Value struct{ DeviceInfo } })
@@ -184,7 +183,7 @@ func (wd *wdaDriver) Location() (location Location, err error) {
// [[FBRoute GET:@"/wda/device/location"] respondWithTarget:self action:@selector(handleGetLocation:)]
// [[FBRoute GET:@"/wda/device/location"].withoutSession
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/wda/device/location"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/wda/device/location"); err != nil {
return Location{}, err
}
reply := new(struct{ Value struct{ Location } })
@@ -198,7 +197,7 @@ func (wd *wdaDriver) Location() (location Location, err error) {
func (wd *wdaDriver) BatteryInfo() (batteryInfo BatteryInfo, err error) {
// [[FBRoute GET:@"/wda/batteryInfo"] respondWithTarget:self action:@selector(handleGetBatteryInfo:)]
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/wda/batteryInfo"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/wda/batteryInfo"); err != nil {
return BatteryInfo{}, err
}
reply := new(struct{ Value struct{ BatteryInfo } })
@@ -217,7 +216,7 @@ func (wd *wdaDriver) WindowSize() (size Size, err error) {
}
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/window/size"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/window/size"); err != nil {
return Size{}, errors.Wrap(err, "get window size failed by WDA request")
}
reply := new(struct{ Value struct{ Size } })
@@ -239,7 +238,7 @@ func (wd *wdaDriver) WindowSize() (size Size, err error) {
func (wd *wdaDriver) Screen() (screen Screen, err error) {
// [[FBRoute GET:@"/wda/screen"] respondWithTarget:self action:@selector(handleGetScreen:)]
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/wda/screen"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/wda/screen"); err != nil {
return Screen{}, err
}
reply := new(struct{ Value struct{ Screen } })
@@ -275,7 +274,7 @@ func (wd *wdaDriver) ActiveAppInfo() (info AppInfo, err error) {
// [[FBRoute GET:@"/wda/activeAppInfo"] respondWithTarget:self action:@selector(handleActiveAppInfo:)]
// [[FBRoute GET:@"/wda/activeAppInfo"].withoutSession
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/wda/activeAppInfo"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/wda/activeAppInfo"); err != nil {
return AppInfo{}, err
}
reply := new(struct{ Value struct{ AppInfo } })
@@ -289,7 +288,7 @@ func (wd *wdaDriver) ActiveAppInfo() (info AppInfo, err error) {
func (wd *wdaDriver) ActiveAppsList() (appsList []AppBaseInfo, err error) {
// [[FBRoute GET:@"/wda/apps/list"] respondWithTarget:self action:@selector(handleGetActiveAppsList:)]
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/wda/apps/list"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/wda/apps/list"); err != nil {
return nil, err
}
reply := new(struct{ Value []AppBaseInfo })
@@ -304,7 +303,7 @@ func (wd *wdaDriver) AppState(bundleId string) (runState AppState, err error) {
// [[FBRoute POST:@"/wda/apps/state"] respondWithTarget:self action:@selector(handleSessionAppState:)]
data := map[string]interface{}{"bundleId": bundleId}
var rawResp rawResponse
if rawResp, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/apps/state"); err != nil {
if rawResp, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/apps/state"); err != nil {
return 0, err
}
reply := new(struct{ Value AppState })
@@ -320,7 +319,7 @@ func (wd *wdaDriver) IsLocked() (locked bool, err error) {
// [[FBRoute GET:@"/wda/locked"] respondWithTarget:self action:@selector(handleIsLocked:)]
// [[FBRoute GET:@"/wda/locked"].withoutSession
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/wda/locked"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/wda/locked"); err != nil {
return false, err
}
if locked, err = rawResp.valueConvertToBool(); err != nil {
@@ -332,14 +331,14 @@ 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.httpPOST(nil, "/session", wd.SessionID, "/wda/unlock")
_, err = wd.httpPOST(nil, "/session", wd.sessionID, "/wda/unlock")
return
}
func (wd *wdaDriver) Lock() (err error) {
// [[FBRoute POST:@"/wda/lock"] respondWithTarget:self action:@selector(handleLock:)]
// [[FBRoute POST:@"/wda/lock"].withoutSession
_, err = wd.httpPOST(nil, "/session", wd.SessionID, "/wda/lock")
_, err = wd.httpPOST(nil, "/session", wd.sessionID, "/wda/lock")
return
}
@@ -353,7 +352,7 @@ func (wd *wdaDriver) AlertText() (text string, err error) {
// [[FBRoute GET:@"/alert/text"] respondWithTarget:self action:@selector(handleAlertGetTextCommand:)]
// [[FBRoute GET:@"/alert/text"].withoutSession
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/alert/text"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/alert/text"); err != nil {
return "", err
}
if text, err = rawResp.valueConvertToString(); err != nil {
@@ -365,7 +364,7 @@ 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 rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/wda/alert/buttons"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/wda/alert/buttons"); err != nil {
return nil, err
}
reply := new(struct{ Value []string })
@@ -401,7 +400,7 @@ 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.httpPOST(data, "/session", wd.SessionID, "/alert/text")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/alert/text")
return
}
@@ -412,7 +411,7 @@ func (wd *wdaDriver) AppLaunch(bundleId string) (err error) {
data["environment"] = map[string]interface{}{
"SHOW_EXPLORER": "NO",
}
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/apps/launch")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/apps/launch")
if err != nil {
return errors.Wrap(code.MobileUILaunchAppError,
fmt.Sprintf("wda launch failed: %v", err))
@@ -435,7 +434,7 @@ 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 rawResponse
if rawResp, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/apps/terminate"); err != nil {
if rawResp, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/apps/terminate"); err != nil {
return false, err
}
if successful, err = rawResp.valueConvertToBool(); err != nil {
@@ -447,7 +446,7 @@ 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.httpPOST(data, "/session", wd.SessionID, "/wda/apps/activate")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/apps/activate")
return
}
@@ -457,7 +456,7 @@ func (wd *wdaDriver) AppDeactivate(second float64) (err error) {
second = 3.0
}
data := map[string]interface{}{"duration": second}
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/deactivateApp")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/deactivateApp")
return
}
@@ -528,7 +527,7 @@ func (wd *wdaDriver) Tap(x, y float64, opts ...option.ActionOption) (err error)
// update data options in post data for extra WDA configurations
actionOptions.UpdateData(data)
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/tap/0")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/tap/0")
return
}
@@ -548,7 +547,7 @@ func (wd *wdaDriver) DoubleTap(x, y float64, opts ...option.ActionOption) (err e
"x": x,
"y": y,
}
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/doubleTap")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/doubleTap")
return
}
@@ -592,7 +591,7 @@ func (wd *wdaDriver) Drag(fromX, fromY, toX, toY float64, opts ...option.ActionO
// update data options in post data for extra WDA configurations
actionOptions.UpdateData(data)
// wda 43 version
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/dragfromtoforduration")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/dragfromtoforduration")
// _, err = wd.httpPOST(data, "/session", wd.ID, "/wda/drag")
return
}
@@ -607,7 +606,7 @@ func (wd *wdaDriver) SetPasteboard(contentType PasteboardType, content string) (
"contentType": contentType,
"content": base64.StdEncoding.EncodeToString([]byte(content)),
}
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/setPasteboard")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/setPasteboard")
return
}
@@ -615,7 +614,7 @@ func (wd *wdaDriver) GetPasteboard(contentType PasteboardType) (raw *bytes.Buffe
// [[FBRoute POST:@"/wda/getPasteboard"] respondWithTarget:self action:@selector(handleGetPasteboard:)]
data := map[string]interface{}{"contentType": contentType}
var rawResp rawResponse
if rawResp, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/getPasteboard"); err != nil {
if rawResp, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/getPasteboard"); err != nil {
return nil, err
}
if raw, err = rawResp.valueDecodeAsBase64(); err != nil {
@@ -640,7 +639,7 @@ func (wd *wdaDriver) SendKeys(text string, opts ...option.ActionOption) (err err
// new data options in post data for extra WDA configurations
actionOptions.UpdateData(data)
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/keys")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/keys")
return
}
@@ -699,14 +698,14 @@ func (wd *wdaDriver) PressBack(opts ...option.ActionOption) (err error) {
// update data options in post data for extra WDA configurations
actionOptions.UpdateData(data)
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/dragfromtoforduration")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/dragfromtoforduration")
return
}
func (wd *wdaDriver) PressButton(devBtn DeviceButton) (err error) {
// [[FBRoute POST:@"/wda/pressButton"] respondWithTarget:self action:@selector(handlePressButtonCommand:)]
data := map[string]interface{}{"name": devBtn}
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/wda/pressButton")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/wda/pressButton")
return
}
@@ -738,7 +737,7 @@ func (wd *wdaDriver) StopCamera() (err error) {
func (wd *wdaDriver) Orientation() (orientation Orientation, err error) {
// [[FBRoute GET:@"/orientation"] respondWithTarget:self action:@selector(handleGetOrientation:)]
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/orientation"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/orientation"); err != nil {
return "", err
}
reply := new(struct{ Value Orientation })
@@ -752,14 +751,14 @@ func (wd *wdaDriver) Orientation() (orientation Orientation, err error) {
func (wd *wdaDriver) SetOrientation(orientation Orientation) (err error) {
// [[FBRoute POST:@"/orientation"] respondWithTarget:self action:@selector(handleSetOrientation:)]
data := map[string]interface{}{"orientation": orientation}
_, err = wd.httpPOST(data, "/session", wd.SessionID, "/orientation")
_, err = wd.httpPOST(data, "/session", wd.sessionID, "/orientation")
return
}
func (wd *wdaDriver) Rotation() (rotation Rotation, err error) {
// [[FBRoute GET:@"/rotation"] respondWithTarget:self action:@selector(handleGetRotation:)]
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/rotation"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/rotation"); err != nil {
return Rotation{}, err
}
reply := new(struct{ Value Rotation })
@@ -772,7 +771,7 @@ func (wd *wdaDriver) Rotation() (rotation Rotation, err error) {
func (wd *wdaDriver) SetRotation(rotation Rotation) (err error) {
// [[FBRoute POST:@"/rotation"] respondWithTarget:self action:@selector(handleSetRotation:)]
_, err = wd.httpPOST(rotation, "/session", wd.SessionID, "/rotation")
_, err = wd.httpPOST(rotation, "/session", wd.sessionID, "/rotation")
return
}
@@ -780,7 +779,7 @@ func (wd *wdaDriver) Screenshot() (raw *bytes.Buffer, err error) {
// [[FBRoute GET:@"/screenshot"] respondWithTarget:self action:@selector(handleGetScreenshot:)]
// [[FBRoute GET:@"/screenshot"].withoutSession respondWithTarget:self action:@selector(handleGetScreenshot:)]
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/screenshot"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/screenshot"); err != nil {
return nil, errors.Wrap(code.DeviceScreenShotError,
fmt.Sprintf("get WDA screenshot data failed: %v", err))
}
@@ -795,7 +794,7 @@ func (wd *wdaDriver) Screenshot() (raw *bytes.Buffer, err error) {
func (wd *wdaDriver) Source(srcOpt ...option.SourceOption) (source string, err error) {
// [[FBRoute GET:@"/source"] respondWithTarget:self action:@selector(handleGetSourceCommand:)]
// [[FBRoute GET:@"/source"].withoutSession
tmp, _ := url.Parse(wd.concatURL(nil, "/session", wd.SessionID))
tmp, _ := url.Parse(wd.concatURL(nil, "/session", wd.sessionID))
toJsonRaw := false
if len(srcOpt) != 0 {
q := tmp.Query()
@@ -838,7 +837,7 @@ func (wd *wdaDriver) AccessibleSource() (source string, err error) {
// [[FBRoute GET:@"/wda/accessibleSource"] respondWithTarget:self action:@selector(handleGetAccessibleSourceCommand:)]
// [[FBRoute GET:@"/wda/accessibleSource"].withoutSession
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/wda/accessibleSource"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/wda/accessibleSource"); err != nil {
return "", err
}
var jr builtinJSON.RawMessage
@@ -858,7 +857,7 @@ func (wd *wdaDriver) HealthCheck() (err error) {
func (wd *wdaDriver) GetAppiumSettings() (settings map[string]interface{}, err error) {
// [[FBRoute GET:@"/appium/settings"] respondWithTarget:self action:@selector(handleGetSettings:)]
var rawResp rawResponse
if rawResp, err = wd.httpGET("/session", wd.SessionID, "/appium/settings"); err != nil {
if rawResp, err = wd.httpGET("/session", wd.sessionID, "/appium/settings"); err != nil {
return nil, err
}
reply := new(struct{ Value map[string]interface{} })
@@ -873,7 +872,7 @@ 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 rawResponse
if rawResp, err = wd.httpPOST(data, "/session", wd.SessionID, "/appium/settings"); err != nil {
if rawResp, err = wd.httpPOST(data, "/session", wd.sessionID, "/appium/settings"); err != nil {
return nil, err
}
reply := new(struct{ Value map[string]interface{} })
@@ -1008,8 +1007,8 @@ func (wd *wdaDriver) StopCaptureLog() (result interface{}, err error) {
return reply.Value, nil
}
func (wd *wdaDriver) GetSession() *DriverSession {
return wd.DriverSession
func (wd *wdaDriver) GetSession() *Session {
return wd.Session
}
func (wd *wdaDriver) GetDriverResults() []*DriverRequests {
@@ -1021,88 +1020,6 @@ func (wd *wdaDriver) GetDriverResults() []*DriverRequests {
func (wd *wdaDriver) TearDown() error {
wd.mjpegClient.CloseIdleConnections()
wd.Client.CloseIdleConnections()
wd.client.CloseIdleConnections()
return nil
}
type rawResponse []byte
func (r rawResponse) checkErr() (err error) {
reply := new(struct {
Value struct {
Err string `json:"error"`
Message string `json:"message"`
Traceback string `json:"traceback"` // wda
Stacktrace string `json:"stacktrace"` // uia
}
})
if err = json.Unmarshal(r, reply); err != nil {
return err
}
if reply.Value.Err != "" {
errText := reply.Value.Message
re := regexp.MustCompile(`{.+?=(.+?)}`)
if re.MatchString(reply.Value.Message) {
subMatch := re.FindStringSubmatch(reply.Value.Message)
errText = subMatch[len(subMatch)-1]
}
return fmt.Errorf("%s: %s", reply.Value.Err, errText)
}
return
}
func (r rawResponse) valueConvertToString() (s string, err error) {
reply := new(struct{ Value string })
if err = json.Unmarshal(r, reply); err != nil {
return "", errors.Wrapf(err, "json.Unmarshal failed, rawResponse: %s", string(r))
}
s = reply.Value
return
}
func (r rawResponse) valueConvertToBool() (b bool, err error) {
reply := new(struct{ Value bool })
if err = json.Unmarshal(r, reply); err != nil {
return false, err
}
b = reply.Value
return
}
func (r rawResponse) valueConvertToSessionInfo() (sessionInfo SessionInfo, err error) {
reply := new(struct{ Value struct{ SessionInfo } })
if err = json.Unmarshal(r, reply); err != nil {
return SessionInfo{}, err
}
sessionInfo = reply.Value.SessionInfo
return
}
func (r rawResponse) valueConvertToJsonRawMessage() (raw builtinJSON.RawMessage, err error) {
reply := new(struct{ Value builtinJSON.RawMessage })
if err = json.Unmarshal(r, reply); err != nil {
return nil, err
}
raw = reply.Value
return
}
func (r rawResponse) valueConvertToJsonObject() (obj map[string]interface{}, err error) {
if err = json.Unmarshal(r, &obj); err != nil {
return nil, err
}
return
}
func (r rawResponse) valueDecodeAsBase64() (raw *bytes.Buffer, err error) {
str, err := r.valueConvertToString()
if err != nil {
return nil, errors.Wrap(err, "failed to convert value to string")
}
decodeString, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return nil, errors.Wrap(err, "failed to decode base64 string")
}
raw = bytes.NewBuffer(decodeString)
return
}

View File

@@ -712,7 +712,7 @@ func runStepMobileUI(s *SessionRunner, step IStep) (stepResult *StepResult, err
// save attachments
session := uiDriver.Driver.GetSession()
for key, value := range session.Get(true) {
for key, value := range session.GetData(true) {
attachments[key] = value
}
stepResult.Attachments = attachments