gitlab.science.ru.nl/irma/gomobile.git@v0.0.0-20200320223732-da812b634d1f/app/internal/apptest/apptest.go (about)

     1  // Copyright 2015 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package apptest provides utilities for testing an app.
     6  //
     7  // It is extremely incomplete, hence it being internal.
     8  // For starters, it should support iOS.
     9  package apptest
    10  
    11  import (
    12  	"bufio"
    13  	"bytes"
    14  	"fmt"
    15  	"net"
    16  )
    17  
    18  // Port is the TCP port used to communicate with the test app.
    19  //
    20  // TODO(crawshaw): find a way to make this configurable. adb am extras?
    21  const Port = "12533"
    22  
    23  // Comm is a simple text-based communication protocol.
    24  //
    25  // Assumes all sides are friendly and cooperative and that the
    26  // communication is over at the first sign of trouble.
    27  type Comm struct {
    28  	Conn   net.Conn
    29  	Fatalf func(format string, args ...interface{})
    30  	Printf func(format string, args ...interface{})
    31  
    32  	scanner *bufio.Scanner
    33  }
    34  
    35  func (c *Comm) Send(cmd string, args ...interface{}) {
    36  	buf := new(bytes.Buffer)
    37  	buf.WriteString(cmd)
    38  	for _, arg := range args {
    39  		buf.WriteRune(' ')
    40  		fmt.Fprintf(buf, "%v", arg)
    41  	}
    42  	buf.WriteRune('\n')
    43  	b := buf.Bytes()
    44  	c.Printf("comm.send: %s\n", b)
    45  	if _, err := c.Conn.Write(b); err != nil {
    46  		c.Fatalf("failed to send %s: %v", b, err)
    47  	}
    48  }
    49  
    50  func (c *Comm) Recv(cmd string, a ...interface{}) {
    51  	if c.scanner == nil {
    52  		c.scanner = bufio.NewScanner(c.Conn)
    53  	}
    54  	if !c.scanner.Scan() {
    55  		c.Fatalf("failed to recv %q: %v", cmd, c.scanner.Err())
    56  	}
    57  	text := c.scanner.Text()
    58  	c.Printf("comm.recv: %s\n", text)
    59  	var recvCmd string
    60  	args := append([]interface{}{&recvCmd}, a...)
    61  	if _, err := fmt.Sscan(text, args...); err != nil {
    62  		c.Fatalf("cannot scan recv command %s: %q: %v", cmd, text, err)
    63  	}
    64  	if cmd != recvCmd {
    65  		c.Fatalf("expecting recv %q, got %v", cmd, text)
    66  	}
    67  }