driver

package
v0.0.0-...-683b059 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2022 License: BSD-3-Clause Imports: 18 Imported by: 0

Documentation

Overview

Package driver provides components to interact with a locally-running Chrome process in various ways, including DevTools protocol and /proc monitoring.

This package works with a properly set up Chrome processes. This package does NOT support setting up / starting Chrome processes.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func PrepareForRestart

func PrepareForRestart() error

PrepareForRestart prepares for Chrome restart.

This function removes a debugging port file for a current Chrome process. By calling this function before purposefully restarting Chrome, you can reliably connect to a new Chrome process without accidentally connecting to an old Chrome process by a race condition.

func PrivateReleaseAllObjects

func PrivateReleaseAllObjects(ctx context.Context, tconn *TestConn) error

PrivateReleaseAllObjects releases all remote JavaScript objects not released yet. This function must kept private to the chrome package.

Types

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn represents a connection to a web content view, e.g. a tab.

func NewConn

func NewConn(ctx context.Context, s *cdputil.Session, id target.ID,
	la *jslog.Aggregator, pageURL string, chromeErr func(error) error) (c *Conn, retErr error)

NewConn starts a new session using sm for communicating with the supplied target. pageURL is only used when logging JavaScript console messages via lm.

func (*Conn) Call

func (c *Conn) Call(ctx context.Context, out interface{}, fn string, args ...interface{}) error

Call applies fn to given args on this connection, then stores its result to out if given. fn must be a JavaScript expression which is evaluated to a (possibly async) function under the current execution context. If the function is async, or the function returns a Promise instance, it will be awaited until settled, and the resolved value will be stored into out, or error is reported if rejected. args must be either JSON serializable value, or *chrome.JSObject which is tied to the current conn. out must be either a pointer to the JSON deserialize typed data, *chrome.JSObject, or nil (if output should be ignored). If *chrome.JSObject is passed, the caller has the responsibility to call its Release() after its use.

Examples:

// 1)  Calling a function. ret will be set to 30.
var ret int
if err := c.Call(ctx, &ret, "function(a, b) { return a + b; }", 10, 20); err != nil {
   ...

// 2) Calling async function. ret will be set whether the given app is shown.
tconn, err := cr.TestAPIConn()
...
var ret bool
if err := tconn.Call(ctx, &ret, "tast.promisify(chrome.autotestPrivate.isAppShown)", appID); err != nil {
  ...

// 3) Serialize structure. Move the mouse to (100, 200) immediately.
loc := struct {
  X double `json:"x"`
  Y double `json:"y"`
} {
  X: 100,
  Y: 200,
}
if err := tconn.Call(ctx, nil, "tast.promisify(chrome.autotestPrivate.mouseMove)", &loc, 0 /* ms */); err != nil {
  ...

// 4) Deserialize structure. Output can be JSON deserialized value.
var ret struct {
  Provisioned bool `json:"provisioned"`
  TOSNeeded bool `json:"tosNeeded"`
}
if err := tconn.Call(ctx, &ret, "tast.promisify(chrome.autotestPrivate.getArcState)"); err != nil {
  ...

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection to the target and frees related resources. Tests should typically defer calls to this method and ignore the returned error. This method does not close the web content itself; see CloseTarget for that.

func (*Conn) CloseTarget

func (c *Conn) CloseTarget(ctx context.Context) error

CloseTarget closes the web content (e.g. tab) associated with c. Close must still be called to free associated resources. Tests should not feel obligated to call this to clean up.

func (*Conn) DispatchKeyEvent

func (c *Conn) DispatchKeyEvent(ctx context.Context, args *input.DispatchKeyEventArgs) error

DispatchKeyEvent executes a key event (i.e. arrowDown, Enter)

func (*Conn) DispatchMouseEvent

func (c *Conn) DispatchMouseEvent(ctx context.Context, args *input.DispatchMouseEventArgs) error

DispatchMouseEvent executes a mouse event (i.e. mouseMoves, mousePressed, mouseReleased)

func (*Conn) Eval

func (c *Conn) Eval(ctx context.Context, expr string, out interface{}) error

Eval evaluates the JavaScript expression expr and stores its result in out. If out is a *chrome.JSObject, a reference to the result is returned. The *chrome.JSObject should get released or the memory it references will not be freed. An error is returned if the result can't be unmarshaled into out.

sum := 0
err := conn.Eval(ctx, "3 + 4", &sum)

If the expression is evaluated into a Promise instance, it will be awaited until it is settled, and the resolved value is stored in out if given.

data := make(map[string]interface{})
err := conn.Eval(ctx,
	`new Promise(function(resolve, reject) {
		runAsync(function(data) {
			if (data != null) {
				resolve(data);
			} else {
				reject("it failed");
			}
		});
	})`, &data)

func (*Conn) GetMediaPropertiesChangedObserver

func (c *Conn) GetMediaPropertiesChangedObserver(ctx context.Context) (observer media.PlayerPropertiesChangedClient, err error)

GetMediaPropertiesChangedObserver enables media logging for the current connection and retrieves a properties change observer.

func (*Conn) Navigate

func (c *Conn) Navigate(ctx context.Context, url string) error

Navigate navigates to url.

func (*Conn) PageContent

func (c *Conn) PageContent(ctx context.Context) (string, error)

PageContent returns the current top-level page content.

func (*Conn) StartProfiling

func (c *Conn) StartProfiling(ctx context.Context) error

StartProfiling enables the profiling of current connection.

func (*Conn) StopProfiling

func (c *Conn) StopProfiling(ctx context.Context) (*profiler.TakePreciseCoverageReply, error)

StopProfiling disables the profiling of current connection and returns the profiling result.

func (*Conn) WaitForExpr

func (c *Conn) WaitForExpr(ctx context.Context, expr string) error

WaitForExpr repeatedly evaluates the JavaScript expression expr until it evaluates to true. Errors returned by Eval are treated the same as expr == false.

func (*Conn) WaitForExprFailOnErr

func (c *Conn) WaitForExprFailOnErr(ctx context.Context, expr string) error

WaitForExprFailOnErr repeatedly evaluates the JavaScript expression expr until it evaluates to true. It returns immediately if Eval returns an error.

func (*Conn) WaitForExprFailOnErrWithTimeout

func (c *Conn) WaitForExprFailOnErrWithTimeout(ctx context.Context, expr string, timeout time.Duration) error

WaitForExprFailOnErrWithTimeout is the same as WaitForExprFailOnErr but will fail if timeout is exceeded.

func (*Conn) WaitForExprWithTimeout

func (c *Conn) WaitForExprWithTimeout(ctx context.Context, expr string, timeout time.Duration) error

WaitForExprWithTimeout is the same as WaitForExpr but fails if timeout is exceeded.

type JSObject

type JSObject struct {
	// contains filtered or unexported fields
}

JSObject is a reference to a JavaScript object. JSObjects must be released or they will stop the JavaScript GC from freeing the memory they reference.

func (*JSObject) Call

func (ob *JSObject) Call(ctx context.Context, out interface{}, fn string, args ...interface{}) error

Call calls the given JavaScript function this Object. The passed arguments must be of type *JSObject or be able to marshal to JSON. If fn is an arrow function, the "this" in the function body will be the window object instead of the object referred to by JSObject ob, and that will probably lead to unintended behavior. If out is given, the returned value is set. If out is a *chrome.JSObject, a reference to the result is returned. The *chrome.JSObject should get released or the memory it references will not be freed. In case of JavaScript exceptions, an error is return.

func (*JSObject) Release

func (ob *JSObject) Release(ctx context.Context) error

Release releases this object's reference to JavaScript.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session allows interacting with a locally running Chrome.

Session maintains a DevTools connection to Chrome. It also monitors a Chrome process with the browser watcher, as well as collecting JavaScript logs with jslog.

Session is similar to chrome.Chrome, but it has following notable differences:

  • Session interacts with a Chrome process already set up for debugging. It is out of its scope to set up / start Chrome processes.
  • A Session instance is tied to lifetime of a Chrome process. It maintains states that would be cleared on restarting Chrome. A Session instance cannot be reused for two different Chrome processes.

func NewSession

func NewSession(ctx context.Context, execPath, debuggingPortPath string, portWait cdputil.PortWaitOption, agg *jslog.Aggregator) (cr *Session, retErr error)

NewSession connects to a local Chrome process and creates a new Session.

func (*Session) Close

func (s *Session) Close(ctx context.Context) error

Close releases resources associated to this object.

func (*Session) CloseTarget

func (s *Session) CloseTarget(ctx context.Context, id TargetID) error

CloseTarget closes the target identified by the given id.

func (*Session) DebugAddrPort

func (s *Session) DebugAddrPort() string

DebugAddrPort returns the addr:port at which Chrome is listening for DevTools connections, e.g. "127.0.0.1:38725". This port should not be accessed from outside of this package, but it is exposed so that the port's owner can be easily identified.

func (*Session) FindTargets

func (s *Session) FindTargets(ctx context.Context, tm TargetMatcher) ([]*Target, error)

FindTargets returns the info about Targets, which satisfies the given cond condition.

func (*Session) NewConn

func (s *Session) NewConn(ctx context.Context, url string, opts ...cdputil.CreateTargetOption) (*Conn, error)

NewConn creates a new Chrome renderer and returns a connection to it. If url is empty, an empty page (about:blank) is opened. Otherwise, the page from the specified URL is opened. You can assume that the page loading has been finished when this function returns.

func (*Session) NewConnForTarget

func (s *Session) NewConnForTarget(ctx context.Context, tm TargetMatcher) (*Conn, error)

NewConnForTarget iterates through all available targets and returns a connection to the first one that is matched by tm. It polls until the target is found or ctx's deadline expires. An error is returned if no target is found, tm matches multiple targets, or the connection cannot be established.

f := func(t *Target) bool { return t.URL == "http://example.net/" }
conn, err := cr.NewConnForTarget(ctx, f)

func (*Session) SigninProfileTestAPIConn

func (s *Session) SigninProfileTestAPIConn(ctx context.Context) (*TestConn, error)

SigninProfileTestAPIConn is the same as TestAPIConn, but for the signin profile test extension.

func (*Session) StartSystemTracing

func (s *Session) StartSystemTracing(ctx context.Context, perfettoConfig []byte) error

StartSystemTracing starts trace events collection from the system tracing service using the marshaled binary protobuf trace config. Note: StopTracing should be called even if StartSystemTracing returns an error. Sometimes, the request to start tracing reaches the browser process, but there is a timeout while waiting for the reply.

func (*Session) StartTracing

func (s *Session) StartTracing(ctx context.Context, categories []string, opts ...cdputil.TraceOption) error

StartTracing starts trace events collection for the selected categories. Android categories must be prefixed with "disabled-by-default-android ", e.g. for the gfx category, use "disabled-by-default-android gfx", including the space. Note: StopTracing should be called even if StartTracing returns an error. Sometimes, the request to start tracing reaches the browser process, but there is a timeout while waiting for the reply.

func (*Session) StopTracing

func (s *Session) StopTracing(ctx context.Context) (*perfetto_proto.Trace, error)

StopTracing stops trace collection and returns the collected trace events.

func (*Session) TestAPIConn

func (s *Session) TestAPIConn(ctx context.Context) (*TestConn, error)

TestAPIConn returns a shared connection to the test API extension's background page (which can be used to access various APIs). The connection is lazily created, and this function will block until the extension is loaded or ctx's deadline is reached. The caller should not close the returned connection; it will be closed automatically by Close.

func (*Session) TracingStarted

func (s *Session) TracingStarted() bool

TracingStarted returns whether tracing has started.

func (*Session) Watcher

func (s *Session) Watcher() *browserwatcher.Watcher

Watcher returns the browser watcher associated with the session.

type Target

type Target = target.Info

Target describes a DevTools target.

type TargetID

type TargetID = target.ID

TargetID is an ID assigned to a DevTools target.

type TargetMatcher

type TargetMatcher = cdputil.TargetMatcher

TargetMatcher is a caller-provided function that matches targets with specific characteristics.

func MatchAllPages

func MatchAllPages() TargetMatcher

MatchAllPages returns a TargetMatcher that matches all targets that are pages.

func MatchTargetID

func MatchTargetID(id TargetID) TargetMatcher

MatchTargetID returns a TargetMatcher that matches targets with the supplied ID.

func MatchTargetURL

func MatchTargetURL(url string) TargetMatcher

MatchTargetURL returns a TargetMatcher that matches targets with the supplied URL.

func MatchTargetURLPrefix

func MatchTargetURLPrefix(prefix string) TargetMatcher

MatchTargetURLPrefix returns a TargetMatcher that matches targets whose URL starts with the supplied prefix.

type TestConn

type TestConn struct {
	// contains filtered or unexported fields
}

TestConn is a connection to the Tast test extension's background page.

func (*TestConn) Call

func (tconn *TestConn) Call(ctx context.Context, out interface{}, fn string, args ...interface{}) error

Call calls the javascript fn with given args. See Conn.Call for details

func (*TestConn) Eval

func (tconn *TestConn) Eval(ctx context.Context, expr string, out interface{}) error

Eval evaluates expr on the test connection. See Conn.Eval for details.

func (*TestConn) ResetAutomation

func (tconn *TestConn) ResetAutomation(ctx context.Context) error

ResetAutomation resets the automation API feature. The automation API feature is widely used to control the UI, but keeping it activated sometimes causes performance drawback on low-end devices. This method deactivates the automation API and resets internal states. See: https://crbug.com/1096719.

func (*TestConn) WaitForExpr

func (tconn *TestConn) WaitForExpr(ctx context.Context, expr string) error

WaitForExpr repeatedly evaluates the JavaScript expression expr until it evaluates to true. Errors returned by Eval are treated the same as expr == false.

func (*TestConn) WaitForExprFailOnErr

func (tconn *TestConn) WaitForExprFailOnErr(ctx context.Context, expr string) error

WaitForExprFailOnErr repeatedly evaluates the JavaScript expression expr until it evaluates to true. It returns immediately if Eval returns an error.

func (*TestConn) WaitForExprFailOnErrWithTimeout

func (tconn *TestConn) WaitForExprFailOnErrWithTimeout(ctx context.Context, expr string, timeout time.Duration) error

WaitForExprFailOnErrWithTimeout is the same as WaitForExprFailOnErr but will fail if timeout is exceeded.

func (*TestConn) WaitForExprWithTimeout

func (tconn *TestConn) WaitForExprWithTimeout(ctx context.Context, expr string, timeout time.Duration) error

WaitForExprWithTimeout is the same as WaitForExpr but fails if timeout is exceeded.

Jump to

Keyboard shortcuts

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