apptest.go 1.7 KB

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