File: apptest.go

package info (click to toggle)
golang-golang-x-mobile 0.0~git20250520.a1d9079%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,784 kB
  • sloc: objc: 1,512; java: 1,489; ansic: 1,159; xml: 365; asm: 34; sh: 14; makefile: 5
file content (67 lines) | stat: -rw-r--r-- 1,755 bytes parent folder | download
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
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package apptest provides utilities for testing an app.
//
// It is extremely incomplete, hence it being internal.
// For starters, it should support iOS.
package apptest

import (
	"bufio"
	"bytes"
	"fmt"
	"net"
)

// Port is the TCP port used to communicate with the test app.
//
// TODO(crawshaw): find a way to make this configurable. adb am extras?
const Port = "12533"

// Comm is a simple text-based communication protocol.
//
// Assumes all sides are friendly and cooperative and that the
// communication is over at the first sign of trouble.
type Comm struct {
	Conn   net.Conn
	Fatalf func(format string, args ...interface{})
	Printf func(format string, args ...interface{})

	scanner *bufio.Scanner
}

func (c *Comm) Send(cmd string, args ...interface{}) {
	buf := new(bytes.Buffer)
	buf.WriteString(cmd)
	for _, arg := range args {
		buf.WriteRune(' ')
		fmt.Fprintf(buf, "%v", arg)
	}
	buf.WriteRune('\n')
	b := buf.Bytes()
	c.Printf("comm.send: %s\n", b)
	if _, err := c.Conn.Write(b); err != nil {
		c.Fatalf("failed to send %s: %v", b, err)
	}
}

func (c *Comm) Recv(cmd string, a ...interface{}) {
	if c.scanner == nil {
		c.scanner = bufio.NewScanner(c.Conn)
	}
	if !c.scanner.Scan() {
		c.Fatalf("failed to recv %q: %v", cmd, c.scanner.Err())
	}
	text := c.scanner.Text()
	c.Printf("comm.recv: %s\n", text)
	var recvCmd string
	args := append([]interface{}{&recvCmd}, a...)
	if _, err := fmt.Sscan(text, args...); err != nil {
		c.Fatalf("cannot scan recv command %s: %q: %v", cmd, text, err)
	}
	if cmd != recvCmd {
		c.Fatalf("expecting recv %q, got %v", cmd, text)
	}
}