device

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	DefaultSocketTimeout = 2 * time.Minute
	ReceiveBufferSize    = 20 * 1024
)
View Source
const (
	ControlTap      = "tap"
	ControlSwipe    = "swipe"
	ControlText     = "text"
	ControlKey      = "key"
	ControlReadLogs = "logs"
)

Control operations, used to forward native control calls to node devices.

View Source
const (
	// CodecH264 packets are H.264 in Annex B format.
	CodecH264 = "h264"
	// CodecMJPEG packets are complete JPEG images, each one a key frame.
	CodecMJPEG = "mjpeg"
)

Codecs of VideoMeta.Codec.

View Source
const (
	InputTouch      = "touch"
	InputKey        = "key"
	InputText       = "text"
	InputScroll     = "scroll"
	InputResetVideo = "reset_video"

	InputDown   = "down"
	InputMove   = "move"
	InputUp     = "up"
	InputCancel = "cancel"
	// InputPress is a key down followed by a key up.
	InputPress = "press"
)

Input event kinds and actions of InputEvent.

Variables

View Source
var (
	DeviceNotFoundError  = errors.New("Device not found")
	ManagerNotFoundError = errors.New("Manager not found")
)
View Source
var (
	DeviceDisconnectedError = fmt.Errorf("device disconnected")
)
View Source
var ErrUnsupported = errors.New("operation not supported by this device")

ErrUnsupported is returned by optional device capabilities that the platform does not implement.

Functions

func As added in v1.2.0

func As[R any](d Device) (R, bool)

As is a generic type assertion: it returns the device as role R, or false when the device doesn't implement it.

func ControlError added in v1.1.0

func ControlError(message string) error

ControlError restores well-known errors from their message after a remote call, so callers can still use errors.Is.

func DropAppConnection added in v1.2.0

func DropAppConnection(d Device)

DropAppConnection forgets the app connection of a device whose app was just stopped. A killed app does not always close its socket: through "adb reverse" the close can stay unnoticed until DefaultSocketTimeout, and a run started meanwhile took the dead connection for its new app and sent the tests into it. Closing the socket ends the connection's goroutines; a newer connection that replaces this one is left alone.

func GetAttribute added in v1.0.4

func GetAttribute(config *DeviceConfig, attribute string) string

func StateToString

func StateToString(state State) string

Types

type ActionHandlerRegistry added in v1.2.0

type ActionHandlerRegistry interface {
	AddActionHandler(appproto.ActionHandler)
	RemoveActionHandler(appproto.ActionHandler)
	ActionHandlers() []appproto.ActionHandler
}

ActionHandlerRegistry holds the handlers that get the app's responses.

type AppConnection added in v1.2.0

type AppConnection interface {
	NewContext() context.Context
	Cancel()
	ConnectionTimeout() time.Duration
	SetConnection(*Connection)
	Connection() *Connection
	IsAppConnected() bool
	Send([]byte) error
}

AppConnection is the link to the running app: its context, its websocket connection and sending data to it.

type AppDataClearer added in v1.1.0

type AppDataClearer interface {
	ClearAppData(*app.Parameter) error
}

AppDataClearer is implemented by devices that can wipe an app's data.

type AppManager added in v1.2.0

type AppManager interface {
	IsAppInstalled(*app.Parameter) (bool, error)
	InstallApp(*app.Parameter) error
	UninstallApp(*app.Parameter) error
	StartApp(deviceConfig *DeviceConfig, appParams *app.Parameter, sessionId string, nodeUrl string) error
	StopApp(*app.Parameter) error
}

AppManager installs, starts and stops the app under test.

type ChangeNotifying added in v1.1.0

type ChangeNotifying interface {
	SetChangeNotifier(notify func())
}

ChangeNotifying is implemented by handlers that detect device changes on their own (adb or usbmuxd events). The device manager hands them a callback to report a change, so a node pushes it to the master right away instead of with its next local refresh.

type Clock added in v1.2.0

type Clock interface {
	Now() time.Time
	After(d time.Duration) <-chan time.Time
}

Clock is the time source of the platform packages.

type CommandError added in v1.2.0

type CommandError struct {
	Name   string
	Stdout []byte
	Stderr []byte
	Err    error
}

CommandError is the error of a command that started and then failed. It keeps the output, which the error text alone would lose: adb, for example, says why an installation failed on stderr only.

func (*CommandError) Error added in v1.2.0

func (e *CommandError) Error() string

Error is "run <name>: <err>", followed by the trimmed stderr when there is some.

func (*CommandError) Unwrap added in v1.2.0

func (e *CommandError) Unwrap() error

Unwrap returns the exit error of the command.

type CommandRunner added in v1.2.0

type CommandRunner interface {
	// Run runs the command and returns its stdout. When the command fails
	// the error is a *CommandError with the stdout and stderr.
	Run(ctx context.Context, name string, args ...string) ([]byte, error)
	// Start starts the command in the background; cancelling ctx kills it.
	Start(ctx context.Context, name string, args ...string) (Process, error)
	// StartStreaming starts the command in the background and writes its
	// stdout and stderr, interleaved, to out. It is for commands whose output
	// is needed while they run. out is written from other goroutines, so it
	// must be safe for that, and it must not block for long. The command
	// leads its own process group, and its process is an Interrupter.
	StartStreaming(ctx context.Context, out io.Writer, name string, args ...string) (Process, error)
}

CommandRunner runs external commands for the platform packages.

type Connection

type Connection struct {
	Logger              *logrus.Entry
	Connection          *websocket.Conn
	ResponseChannel     chan ResponseData
	ActionChannel       chan appproto.Response
	ConnectionParameter *appproto.Connect
}

func (*Connection) Close

func (c *Connection) Close()

func (*Connection) HandleMessages

func (c *Connection) HandleMessages(ctx context.Context)

func (*Connection) Send

func (c *Connection) Send(content []byte) error

type ConnectionState

type ConnectionState uint8
const (
	Disconnected ConnectionState = iota
	Connected
)

type ControlRequest added in v1.1.0

type ControlRequest struct {
	DeviceID   string
	Op         string
	X, Y       int
	ToX, ToY   int
	DurationMs int
	Text       string
	Key        string
	Lines      int
	// Since asks ControlReadLogs for the lines since this logcat time;
	// older nodes ignore it and return the most recent lines
	Since string
}

ControlRequest is a native control call in a transport-friendly form.

type ControlResponse added in v1.1.0

type ControlResponse struct {
	Lines []string
}

func ApplyControl added in v1.1.0

func ApplyControl(dev Device, req ControlRequest) (ControlResponse, error)

ApplyControl executes the request on a local device.

type Device

Device is the composite of the roles every device plays. The optional roles (Recorder, Screenshotter, FeatureExecutor, NativeScripter, and the ones in video.go and control.go) are reached with As.

ActionHandlerRegistry stays in the core: every platform gets it from generic.Device, and the device manager, the action executors and the app connection use it unconditionally on every device.

type DeviceConfig added in v1.0.4

type DeviceConfig struct {
	Connection      int
	IP              string
	Port            int
	DeviceParameter map[string]string
}

type ExecRunner added in v1.2.0

type ExecRunner struct{}

ExecRunner is the CommandRunner on top of tools/exec.

func (ExecRunner) Run added in v1.2.0

func (ExecRunner) Run(ctx context.Context, name string, args ...string) ([]byte, error)

func (ExecRunner) Start added in v1.2.0

func (ExecRunner) Start(ctx context.Context, name string, args ...string) (Process, error)

func (ExecRunner) StartStreaming added in v1.2.0

func (ExecRunner) StartStreaming(ctx context.Context, out io.Writer, name string, args ...string) (Process, error)

type FeatureExecutor added in v1.2.0

type FeatureExecutor interface {
	HasFeature(string) bool
	Execute(string)
}

FeatureExecutor runs device specific features.

type Handler

type Handler interface {
	Name() string
	Init(masterUrl string, nodeIdentifier string, authToken *string) error
	Start() error
	Stop() error
	StartDevice(string) error
	StopDevice(string) error
	GetDevices() ([]Device, error)
	RefreshDevices(bool) error
	HasDevice(Device) bool
	RegisterDevice(data RegisterData) (Device, error)
}

type Identity added in v1.2.0

type Identity interface {
	DeviceID() string
	DeviceState() State
	DeviceOSName() string
	DeviceOSVersion() string
	DeviceName() string
	DeviceParameter() map[string]string
	DeviceType() int
	PlatformType() int
	TargetVersion() string
}

Identity describes what a device is.

type InputCapable added in v1.1.0

type InputCapable interface {
	Tap(x, y int) error
	Swipe(fromX, fromY, toX, toY int, duration time.Duration) error
	InputText(text string) error
	// PressKey presses a named key ("home", "back", "enter", "menu", "delete",
	// "tab", "app_switch", "power", "volume_up", "volume_down") or, where the
	// platform supports it, a numeric key code.
	PressKey(key string) error
}

InputCapable is implemented by devices that accept native input. Coordinates are in screenshot pixels, as returned by GetScreenshot.

type InputEvent added in v1.1.0

type InputEvent struct {
	Kind      string  `json:"kind"`
	Action    string  `json:"action,omitempty"`
	PointerID int64   `json:"pointerId,omitempty"`
	X         int     `json:"x,omitempty"`
	Y         int     `json:"y,omitempty"`
	Width     int     `json:"width,omitempty"`
	Height    int     `json:"height,omitempty"`
	Key       string  `json:"key,omitempty"`
	Text      string  `json:"text,omitempty"`
	ScrollX   float64 `json:"scrollX,omitempty"`
	ScrollY   float64 `json:"scrollY,omitempty"`
}

InputEvent is low latency input sent over a running video stream. Positions are pixels of the current video frame, whose size is Width x Height; events for another size are dropped (e.g. during a rotation).

type Interrupter added in v1.2.0

type Interrupter interface {
	// Interrupt asks the process, and its children if it leads a process
	// group, to end.
	Interrupt() error
}

Interrupter is implemented by processes that can be asked to end before they are killed. The process of ExecRunner implements it.

type Locker added in v1.2.0

type Locker interface {
	Lock() error
	Unlock() error
	IsLocked() bool
}

Locker reserves a device for one test run.

type LogFollower added in v1.2.0

type LogFollower interface {
	ReadLogsSince(since string, lines int) ([]string, error)
}

LogFollower is implemented by devices that can return the log lines since a time, to follow the log. since is a logcat time, "MM-DD hh:mm:ss.mmm"; the lines at that time are included again.

type LogReader added in v1.1.0

type LogReader interface {
	// ReadLogs returns up to lines of the most recent log lines, oldest first.
	ReadLogs(lines int) ([]string, error)
}

LogReader is implemented by devices that can return their recent system log.

type LogWriter

type LogWriter interface {
	LogPerformance(checkpoint string, cpu, fps, mem, vertexCount, triangles float64, other string)
	Data(source, data string)
	// SetKey stores a key and its value for the test the writer belongs to
	SetKey(key, value string)
	Log(source, format string, params ...interface{})
	Error(source, format string, params ...interface{})
	TestProtocolId() *uint
	Device() interface{}
	Parent() LogWriter
	Passed(passed bool)
	HasPassed() bool
}

type NativeScripter added in v1.2.0

type NativeScripter interface {
	RunNativeScript(data []byte)
}

NativeScripter runs a native script on the device.

type Process added in v1.2.0

type Process interface {
	Wait() error
	Kill() error
}

Process is a started command.

type Properties

type Properties struct {
	Name         string
	DeviceID     string
	Type         string
	OS           string
	Architecture string
	App          string
}

func (*Properties) AreValid

func (p *Properties) AreValid() bool

type RealClock added in v1.2.0

type RealClock struct{}

RealClock is the Clock of the system time.

func (RealClock) After added in v1.2.0

func (RealClock) After(d time.Duration) <-chan time.Time

func (RealClock) Now added in v1.2.0

func (RealClock) Now() time.Time

type Recorder added in v1.2.0

type Recorder interface {
	StartRecording(string) error
	StopRecording() error
}

Recorder records the screen of a device.

type RegisterData

type RegisterData struct {
	ManagerType     string
	DeviceID        string
	Name            string
	DeviceOS        string
	DeviceOSVersion string
	TargetVersion   string
	DeviceOSInfos   string
	ProjectDir      string
	DeviceModel     string
	RAM             float32
	GPU             string
	SOC             string
	DeviceIP        net.IP
	Conn            *websocket.Conn
}

type ResponseData

type ResponseData struct {
	Data []byte
	Err  error
}

type Screenshotter added in v1.2.0

type Screenshotter interface {
	GetScreenshot() ([]byte, int, int, error)
}

Screenshotter takes a screenshot and returns it with its width and height.

type State

type State uint8
const (
	StateNone State = iota
	StateUnknown
	StateShutdown
	// StateRemoteDisconnected: the node doesn't see the device, e.g. an
	// unplugged USB phone or a network device that isn't connected
	StateRemoteDisconnected
	StateBooted
	StateLocked
	StateNodeDisconnected
	// StateUnauthorized: connected, but USB debugging isn't accepted on the device yet
	StateUnauthorized
)

func ParseState added in v1.2.0

func ParseState(name string) State

ParseState maps a state name, as the platforms store it and the nodes send it, to its State. Unknown names give StateUnknown. StateLocked and StateNone have no name on the wire.

This is the union of the platform mappings that exist today (androiddevice, iosdevice, iossim, macos, web, node, unityeditor). They all map an unknown name to StateUnknown, except unityeditor: it maps it to StateShutdown (G27 switches it to ParseState).

type TestLogger added in v1.2.0

type TestLogger interface {
	SetLogWriter(LogWriter)
	GetLogWriter() LogWriter
	Data(string, string)
	SetKey(key, value string)
	LogPerformance(checkpoint string, cpu, fps, mem, vertexCount, triangles float64, other string)
	Log(string, string, ...interface{})
	Error(string, string, ...interface{})
	Exception(string, string, ...interface{})
	Passed(result bool)
}

TestLogger collects the log, data and result of a test run.

type VideoInput added in v1.1.0

type VideoInput interface {
	InjectInput(ev InputEvent) error
}

VideoInput is implemented by video streams that inject input through the stream's own channel, which is much faster than device.InputCapable.

type VideoMeta added in v1.1.0

type VideoMeta struct {
	// Codec is the codec of the packets, CodecH264 or CodecMJPEG.
	Codec string `json:"codec"`
	// Width and Height of the video at the start of the stream. Rotations
	// change them; decoders take the size from the config packets.
	Width  int `json:"width"`
	Height int `json:"height"`
	// ScreenWidth and ScreenHeight are the device resolution in the natural
	// orientation, the coordinate space of device.InputCapable. Clients map a
	// position on the video to device pixels with it, swapping the two when
	// the video orientation differs. Zero when unknown.
	ScreenWidth  int `json:"screenWidth"`
	ScreenHeight int `json:"screenHeight"`
	// ViewOnly streams take no input (they don't implement VideoInput);
	// clients use the control API (device.InputCapable) instead.
	ViewOnly bool `json:"viewOnly,omitempty"`
}

VideoMeta describes a video stream.

type VideoOptions added in v1.1.0

type VideoOptions struct {
	// MaxSize limits the longer side of the video in pixels (0 = native size).
	MaxSize int
	// MaxFPS limits the frame rate (0 = unlimited).
	MaxFPS int
	// BitRate in bits per second.
	BitRate int
}

VideoOptions tune a live video stream. Zero values use the defaults of the implementation.

type VideoPacket added in v1.1.0

type VideoPacket struct {
	// Config packets carry the codec configuration (SPS/PPS) and no picture.
	Config   bool
	KeyFrame bool
	// PTS is the presentation time in microseconds (0 for config packets).
	PTS  int64
	Data []byte
}

VideoPacket is one encoded unit of a video stream. For H.264 the data is in Annex B format.

type VideoStream added in v1.1.0

type VideoStream interface {
	Meta() VideoMeta
	ReadPacket() (VideoPacket, error)
	Close() error
}

VideoStream is a running video stream. ReadPacket blocks until the next packet; it returns an error once the stream ended or was closed.

type VideoStreamRequest added in v1.1.0

type VideoStreamRequest struct {
	DeviceID string
	StreamID string
	Options  VideoOptions
}

VideoStreamRequest asks a node to stream a device's video back to the master under StreamID.

type VideoStreamer added in v1.1.0

type VideoStreamer interface {
	StartVideo(ctx context.Context, opts VideoOptions) (VideoStream, error)
}

VideoStreamer is implemented by devices that can stream their screen as encoded video. The stream ends when ctx is done or it is closed.

Directories

Path Synopsis
adb
Package adb runs adb commands for one device through a device.CommandRunner.
Package adb runs adb commands for one device through a device.CommandRunner.
scrcpy
Package scrcpy streams the screen of an Android device as H.264 video with the scrcpy server (https://github.com/Genymobile/scrcpy, Apache-2.0).
Package scrcpy streams the screen of an Android device as H.264 video with the scrcpy server (https://github.com/Genymobile/scrcpy, Apache-2.0).
Package hostinfo reads facts about the machine a node runs on (OS name and version, host name, hardware identity) through an injected command runner, so the macos and web platforms share one implementation that tests on any OS.
Package hostinfo reads facts about the machine a node runs on (OS name and version, host name, hardware identity) through an injected command runner, so the macos and web platforms share one implementation that tests on any OS.
hostinfotest
Package hostinfotest holds the test fakes shared by the macos and web platform tests.
Package hostinfotest holds the test fakes shared by the macos and web platform tests.
Package luascript runs the hub Lua scripts shared by the Android and iOS devices.
Package luascript runs the hub Lua scripts shared by the Android and iOS devices.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL