forked from nanoscopic/wdaproxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
351 lines (314 loc) · 8.99 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/facebookgo/freeport"
"github.com/gobuild/log"
"github.com/gorilla/mux"
accesslog "github.com/mash/go-accesslog"
flag "github.com/ogier/pflag"
_ "github.com/shurcooL/vfsgen"
"github.com/tmobile/wdaproxy/web"
)
func init() {
log.SetFlags(log.Lshortfile | log.LstdFlags)
}
var (
version = "develop"
lisPort = 8100
wdaPort = 8100
pWda string
udid string
yosemiteServer string
yosemiteGroup string
debug bool
iosversion string
iosDeploy string
mobileDevice string
rt = mux.NewRouter()
//udidNames = map[string]string{}
)
type statusResp struct {
Value map[string]interface{} `json:"value,omitempty"`
SessionId string `json:"sessionId,omitempty"`
Status int `json:"status"`
}
func getUdid() string {
if udid != "" {
return udid
}
output, err := exec.Command("idevice_id", "-l").Output()
if err != nil {
panic(err)
}
return strings.TrimSpace(string(output))
}
func assetsContent(name string) string {
fd, err := web.Assets.Open(name)
if err != nil {
panic(err)
}
data, err := ioutil.ReadAll(fd)
if err != nil {
panic(err)
}
return string(data)
}
type Device struct {
Udid string `json:"serial"`
Manufacturer string `json:"manufacturer"`
}
// LocalIP returns the non loopback local IP of the host
func LocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
func main() {
showVer := flag.BoolP("version", "v", false, "Print version")
flag.IntVarP(&lisPort, "port", "p", 8100, "Proxy listen port")
flag.IntVarP(&wdaPort, "wdaport", "q", 8100, "Upstream WDA port")
flag.StringVarP(&udid, "udid", "u", "", "device udid")
flag.StringVarP(&pWda, "wda", "W", "", "WebDriverAgent project directory [optional]")
flag.BoolVarP(&debug, "debug", "d", false, "Open debug mode")
flag.StringVarP(&iosversion, "iosversion", "V", "", "IOS Version")
flag.StringVarP(&iosDeploy, "iosDeploy", "I", "", "ios-deploy path")
flag.StringVarP(&mobileDevice, "mobileDevice", "M", "", "mobiledevice path")
// flag.StringVarP(&yosemiteServer, "yosemite-server", "S",
// os.Getenv("YOSEMITE_SERVER"),
// "server center(not open source yet")
// flag.StringVarP(&yosemiteGroup, "yosemite-group", "G",
// "everyone",
// "server center group")
flag.Parse()
if udid == "" {
udid = getUdid()
}
if *showVer {
println(version)
return
}
lis, err := net.Listen("tcp", ":"+strconv.Itoa(lisPort))
if err != nil {
log.Fatal(err)
}
// if yosemiteServer != "" {
// mockIOSProvider()
// }
errC := make(chan error)
freePort, err := freeport.Get()
if err != nil {
log.Fatal(err)
}
log.Printf("freeport %d", freePort)
go func() {
log.Printf("launch tcp-proxy, listen on %d", lisPort)
targetURL, _ := url.Parse("http://127.0.0.1:" + strconv.Itoa(freePort))
rt.HandleFunc("/wd/hub/{path:.*}", NewAppiumProxyHandlerFunc(targetURL))
rt.HandleFunc("/{path:.*}", NewReverseProxyHandlerFunc(targetURL))
err := http.Serve(lis, accesslog.NewLoggingHandler(rt, HTTPLogger{}))
fmt.Printf("http failure\n")
errC <- err
}()
go func() {
log.Printf("launch iproxy (udid: %s)", strconv.Quote(udid))
var c *exec.Cmd
if mobileDevice != "" {
c = exec.Command(mobileDevice, "tunnel", "-u", udid, strconv.Itoa(freePort), strconv.Itoa(wdaPort))
} else {
iproxyVersion := iproxy_version()
if iproxyVersion == 1 {
c = exec.Command("/usr/local/bin/iproxy", strconv.Itoa(freePort), strconv.Itoa(wdaPort))
if udid != "" {
c.Args = append(c.Args, udid)
}
} else if iproxyVersion == 2 {
c = exec.Command("/usr/local/bin/iproxy", "-s", "127.0.0.1", strconv.Itoa(freePort)+":"+strconv.Itoa(wdaPort))
if udid != "" {
c.Args = append(c.Args, "-u", udid)
}
}
}
c.Stdout = os.Stdout
c.Stderr = os.Stderr
err := c.Run()
fmt.Printf("iproxy failure\n")
errC <- err
}()
go func(udid string) {
if pWda == "" {
return
}
// device name
/*var deviceName string
if iosDeploy != "" {
nameBytes, _ := exec.Command( iosDeploy, "-u", udid).Output()
deviceName = strings.TrimSpace(string(nameBytes))
} else {
nameBytes, _ := exec.Command("/usr/local/bin/idevicename", "-u", udid).Output()
deviceName = strings.TrimSpace(string(nameBytes))
}
udidNames[udid] = deviceName
log.Printf("device name: %s", deviceName)*/
log.Printf("launch WebDriverAgent(dir=%s)", pWda)
var c *exec.Cmd
if fileExists("WebDriverAgent.xcodeproj") {
c = exec.Command("xcodebuild",
"-verbose",
"-project", "WebDriverAgent.xcodeproj",
"-scheme", "WebDriverAgentRunner",
"-destination", "id="+udid, "test-without-building") // test-without-building
} else {
xctestrunFile := findXctestrun(pWda)
if xctestrunFile == "" {
log.Fatal("Could not find WebDriverAgent.xcodeproj or xctestrun of sufficient version")
}
c = exec.Command("xcodebuild",
"test-without-building",
"-xctestrun", xctestrunFile,
"-destination", "id="+udid)
}
c.Dir, _ = filepath.Abs(pWda)
// Test Suite 'All tests' started at 2017-02-27 15:55:35.263
// Test Suite 'WebDriverAgentRunner.xctest' started at 2017-02-27 15:55:35.266
// Test Suite 'UITestingUITests' started at 2017-02-27 15:55:35.267
// Test Case '-[UITestingUITests testRunner]' started.
// t = 0.00s Start Test at 2017-02-27 15:55:35.270
// t = 0.01s Set Up
pipeReader, writer := io.Pipe()
c.Stdout = writer
c.Stderr = writer
c.Stdin = os.Stdin
portLine := fmt.Sprintf("USE_PORT=%d", wdaPort)
c.Env = append(os.Environ(), portLine)
bufrd := bufio.NewReader(pipeReader)
if err = c.Start(); err != nil {
log.Fatal(err)
}
// close writers when xcodebuild exit
go func() {
c.Wait()
writer.Close()
}()
lineStr := ""
for {
line, isPrefix, err := bufrd.ReadLine()
if isPrefix {
lineStr = lineStr + string(line)
continue
} else {
lineStr = string(line)
}
lineStr = strings.TrimSpace(string(line))
if debug {
fmt.Printf("[WDA] %s\n", lineStr)
}
if err != nil {
log.Fatal("[WDA] exit", err)
}
if strings.Contains(lineStr, "Successfully wrote Manifest cache to") {
log.Println("[WDA] test ipa successfully generated")
}
if strings.HasPrefix(lineStr, "Test Case '-[UITestingUITests testRunner]' started") {
log.Println("[WDA] successfully started")
}
lineStr = "" // reset str
}
}(udid)
log.Printf("Open webbrower with http://%s:%d", LocalIP(), lisPort)
err2 := <-errC
log.Fatalf("error %s\n", err2)
}
func iproxy_version() int {
output, _ := exec.Command("/usr/local/bin/iproxy", "-h").Output()
lines := strings.Split(string(output), "\n")
for _, line := range lines {
if strings.Contains(line, "LOCAL_PORT:DEVICE_PORT") {
return 2
}
}
return 1
}
func findXctestrun(folder string) string {
var files []string
err := filepath.Walk(folder, func(file string, info os.FileInfo, err error) error {
if info.IsDir() && folder != file {
return filepath.SkipDir
}
files = append(files, file)
return nil
})
if err != nil {
log.Fatal(err)
}
versionMatch := false
var findMajor int64 = 0
var findMinor int64 = 0
var curMajor int64 = 100
var curMinor int64 = 100
if iosversion != "" {
parts := strings.Split(iosversion, ".")
findMajor, _ = strconv.ParseInt(parts[0], 10, 64)
findMinor, _ = strconv.ParseInt(parts[1], 10, 64)
versionMatch = true
log.Println("device ios version to target: " + string(parts[0]) + "." + string(parts[1]))
}
xcFile := ""
for _, file := range files {
if !strings.HasSuffix(file, ".xctestrun") {
continue
} else {
log.Println("found .xctestrun file: " + string(file))
}
if !versionMatch {
xcFile = file
break
}
r := regexp.MustCompile(`iphoneos([0-9]+)\.([0-9]+)`)
fileParts := r.FindSubmatch([]byte(file))
fileMajor, _ := strconv.ParseInt(string(fileParts[1]), 10, 64)
fileMinor, _ := strconv.ParseInt(string(fileParts[2]), 10, 64)
// Find the smallest file version greater than or equal to the ios version
// Golang line continuation for long boolean expressions is horrible. :(
// Checked file version smaller than current file version
// &&
// Checked file version greater or equal to ios version
if (fileMajor < curMajor || (fileMajor == curMajor && fileMinor <= curMinor)) &&
(fileMajor > findMajor || (fileMajor == findMajor && fileMinor >= findMinor)) {
curMajor = fileMajor
curMinor = fileMinor
xcFile = file
} else {
log.Println(".xctestrun file isn't right")
}
}
return xcFile
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}