selenium

package module
v0.0.0-...-08d59e5 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2015 License: MIT Imports: 14 Imported by: 0

README

============================================== go-selenium - Selenium WebDriver client for Go

status

go-selenium is a Selenium WebDriver client for Go.

Note: the public API is experimental and subject to change until further notice.

Usage

Documentation: go-selenium on Sourcegraph.

Example: see example_test.go:

package selenium_test

import (
	"fmt"
	"sourcegraph.com/sourcegraph/go-selenium"
)

func ExampleFindElement() {
	var webDriver selenium.WebDriver
	var err error
	caps := selenium.Capabilities(map[string]interface{}{"browserName": "firefox"})
	if webDriver, err = selenium.NewRemote(caps, "http://localhost:4444/wd/hub"); err != nil {
		fmt.Printf("Failed to open session: %s\n", err)
		return
	}
	defer webDriver.Quit()

	err = webDriver.Get("https://sourcegraph.com/sourcegraph/go-selenium")
	if err != nil {
		fmt.Printf("Failed to load page: %s\n", err)
		return
	}

	if title, err := webDriver.Title(); err == nil {
		fmt.Printf("Page title: %s\n", title)
	} else {
		fmt.Printf("Failed to get page title: %s", err)
		return
	}

	var elem selenium.WebElement
	elem, err = webDriver.FindElement(selenium.ByCSSSelector, ".repo .name")
	if err != nil {
		fmt.Printf("Failed to find element: %s\n", err)
		return
	}

	if text, err := elem.Text(); err == nil {
		fmt.Printf("Repository: %s\n", text)
	} else {
		fmt.Printf("Failed to get text of element: %s\n", err)
		return
	}

	// output:
	// Page title: go-selenium - Sourcegraph
	// Repository: go-selenium
}

The WebDriverT and WebElementT interfaces make test code cleaner. Each method in WebDriver and WebElement has a corresponding method in the *T interfaces that omits the error from the return values and instead calls t.Fatalf upon encountering an error. For example:

package mytest

import (
  "sourcegraph.com/sourcegraph/go-selenium"
  "testing"
)

var caps selenium.Capabilities
var executorURL = "http://localhost:4444/wd/hub"

// An example test using the WebDriverT and WebElementT interfaces. If you use the non-*T
// interfaces, you must perform error checking that is tangential to what you are testing,
// and you have to destructure results from method calls.
func TestWithT(t *testing.T) {
  wd, _ := selenium.NewRemote(caps, executor)

  // Call .T(t) to obtain a WebDriverT from a WebDriver (or to obtain a WebElementT from
  // a WebElement).
  wdt := wd.T(t)

  // Calls `t.Fatalf("Get: %s", err)` upon failure.
  wdt.Get("http://example.com")

  // Calls `t.Fatalf("FindElement(by=%q, value=%q): %s", by, value, err)` upon failure.
  elem := wdt.FindElement(selenium.ByCSSSelector, ".foo")

  // Calls `t.Fatalf("Text: %s", err)` if the `.Text()` call fails.
  if elem.Text() != "bar" {
    t.Fatalf("want elem text %q, got %q", "bar", elem.Text())
  }
}

See remote_test.go for more usage examples.

Running tests

Start Selenium WebDriver and run go test. To see all available options, run go test -test.h.

TODO

  • Support Firefox profiles

Contributors

License

go-selenium is distributed under the Eclipse Public License.

Documentation

Overview

A Selenium WebDriver client for browser testing of Web applications.

Index

Constants

View Source
const (
	ById              = "id"
	ByXPATH           = "xpath"
	ByLinkText        = "link text"
	ByPartialLinkText = "partial link text"
	ByName            = "name"
	ByTagName         = "tag name"
	ByClassName       = "class name"
	ByCSSSelector     = "css selector"
)

Element finding options

View Source
const (
	LeftButton = iota
	MiddleButton
	RightButton
)

Mouse buttons

View Source
const (
	NullKey       = string('\ue000')
	CancelKey     = string('\ue001')
	HelpKey       = string('\ue002')
	BackspaceKey  = string('\ue003')
	TabKey        = string('\ue004')
	ClearKey      = string('\ue005')
	ReturnKey     = string('\ue006')
	EnterKey      = string('\ue007')
	ShiftKey      = string('\ue008')
	ControlKey    = string('\ue009')
	AltKey        = string('\ue00a')
	PauseKey      = string('\ue00b')
	EscapeKey     = string('\ue00c')
	SpaceKey      = string('\ue00d')
	PageUpKey     = string('\ue00e')
	PageDownKey   = string('\ue00f')
	EndKey        = string('\ue010')
	HomeKey       = string('\ue011')
	LeftArrowKey  = string('\ue012')
	UpArrowKey    = string('\ue013')
	RightArrowKey = string('\ue014')
	DownArrowKey  = string('\ue015')
	InsertKey     = string('\ue016')
	DeleteKey     = string('\ue017')
	SemicolonKey  = string('\ue018')
	EqualsKey     = string('\ue019')
	Numpad0Key    = string('\ue01a')
	Numpad1Key    = string('\ue01b')
	Numpad2Key    = string('\ue01c')
	Numpad3Key    = string('\ue01d')
	Numpad4Key    = string('\ue01e')
	Numpad5Key    = string('\ue01f')
	Numpad6Key    = string('\ue020')
	Numpad7Key    = string('\ue021')
	Numpad8Key    = string('\ue022')
	Numpad9Key    = string('\ue023')
	MultiplyKey   = string('\ue024')
	AddKey        = string('\ue025')
	SeparatorKey  = string('\ue026')
	SubstractKey  = string('\ue027')
	DecimalKey    = string('\ue028')
	DivideKey     = string('\ue029')
	F1Key         = string('\ue031')
	F2Key         = string('\ue032')
	F3Key         = string('\ue033')
	F4Key         = string('\ue034')
	F5Key         = string('\ue035')
	F6Key         = string('\ue036')
	F7Key         = string('\ue037')
	F8Key         = string('\ue038')
	F9Key         = string('\ue039')
	F10Key        = string('\ue03a')
	F11Key        = string('\ue03b')
	F12Key        = string('\ue03c')
	MetaKey       = string('\ue03d')
)

Keys

View Source
const (
	SUCCESS = 0
)

Variables

View Source
var Log = log.New(os.Stderr, "[selenium] ", log.Ltime|log.Lmicroseconds)
View Source
var Trace bool

Functions

This section is empty.

Types

type Build

type Build struct {
	Version, Revision, Time string
}

Build object, part of Status return.

type Capabilities

type Capabilities map[string]interface{}
Browser capabilities, see

http://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object

type Cookie struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Path   string `json:"path"`
	Domain string `json:"domain"`
	Secure bool   `json:"secure"`
	// Expiry is sometimes in the form 1475462512.161885 (chromedriver)
	Expiry interface{} `json:"expiry"`
}

Cookie

type FirefoxProfile

type FirefoxProfile struct {
	Root string
}

type OS

type OS struct {
	Arch, Name, Version string
}

OS object, part of Status return.

type Point

type Point struct {
	X, Y float64
}

Point

type Session

type Session struct {
	Id           string
	Capabilities Capabilities
}

An active session.

type Size

type Size struct {
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
}

Size

type Status

type Status struct {
	Build `json:"build"`
	OS    `json:"os"`
}

Information retured by Status method.

type TestingT

type TestingT interface {
	Fatalf(fmt string, v ...interface{})
}

TestingT is a subset of the testing.T interface (to avoid needing to import "testing", which registers global command-line flags).

type WebDriver

type WebDriver interface {
	/* Status (info) on server */
	Status() (*Status, error)

	/* List of actions on the server. */
	Sessions() ([]Session, error)

	/* Start a new session, return session id */
	NewSession() (string, error)

	/* Current session capabilities */
	Capabilities() (Capabilities, error)
	/* Set the amount of time, in milliseconds, that asynchronous scripts are permitted to run before they are aborted. */
	SetAsyncScriptTimeout(ms uint) error
	/* Set the amount of time, in milliseconds, the driver should wait when searching for elements. */
	SetImplicitWaitTimeout(ms uint) error

	// IME
	/* List all available engines on the machine. */
	AvailableEngines() ([]string, error)
	/* Get the name of the active IME engine. */
	ActiveEngine() (string, error)
	/* Indicates whether IME input is active at the moment. */
	IsEngineActivated() (bool, error)
	/* De-activates the currently-active IME engine. */
	DeactivateEngine() error
	/* Make an engines active */
	ActivateEngine(engine string) error

	/* Quit (end) current session */
	Quit() error

	// Page information and manipulation
	/* Return id of current window handle. */
	CurrentWindowHandle() (string, error)
	/* Return ids of current open windows. */
	WindowHandles() ([]string, error)
	/* Current url. */
	CurrentURL() (string, error)
	/* Page title. */
	Title() (string, error)
	/* Get page source. */
	PageSource() (string, error)
	/* Close current window. */
	Close() error
	/* Switch to frame, frame parameter can be name or id. */
	SwitchFrame(frame string) error
	/* Switch to parent frame */
	SwitchFrameParent() error
	/* Swtich to window. */
	SwitchWindow(name string) error
	/* Close window. */
	CloseWindow(name string) error
	/* Get window size */
	WindowSize(name string) (*Size, error)
	/* Get window position */
	WindowPosition(name string) (*Point, error)

	// ResizeWindow resizes the named window.
	ResizeWindow(name string, to Size) error

	// Navigation
	/* Open url. */
	Get(url string) error
	/* Move forward in history. */
	Forward() error
	/* Move backward in history. */
	Back() error
	/* Refresh page. */
	Refresh() error

	// Finding element(s)
	/* Find, return one element. */
	FindElement(by, value string) (WebElement, error)
	/* Find, return list of elements. */
	FindElements(by, value string) ([]WebElement, error)
	/* Current active element. */
	ActiveElement() (WebElement, error)

	// Shortcut for FindElement(ByCSSSelector, sel)
	Q(sel string) (WebElement, error)
	// Shortcut for FindElements(ByCSSSelector, sel)
	QAll(sel string) ([]WebElement, error)

	// Cookies
	/* Get all cookies */
	GetCookies() ([]Cookie, error)
	/* Add a cookies */
	AddCookie(cookie *Cookie) error
	/* Delete all cookies */
	DeleteAllCookies() error
	/* Delete a cookie */
	DeleteCookie(name string) error

	// Mouse
	/* Click mouse button, button should be on of RightButton, MiddleButton or
	LeftButton.
	*/
	Click(button int) error
	/* Dobule click */
	DoubleClick() error
	/* Mouse button down */
	ButtonDown() error
	/* Mouse button up */
	ButtonUp() error

	// Misc
	/* Send modifier key to active element.
	modifier can be one of ShiftKey, ControlKey, AltKey, MetaKey.
	*/
	SendModifier(modifier string, isDown bool) error
	Screenshot() ([]byte, error)

	// Alerts
	/* Dismiss current alert. */
	DismissAlert() error
	/* Accept current alert. */
	AcceptAlert() error
	/* Current alert text. */
	AlertText() (string, error)
	/* Set current alert text. */
	SetAlertText(text string) error

	// Scripts
	/* Execute a script. */
	ExecuteScript(script string, args []interface{}) (interface{}, error)
	/* Execute a script async. */
	ExecuteScriptAsync(script string, args []interface{}) (interface{}, error)

	// Get a WebDriverT of this element that has methods that call t.Fatalf upon
	// encountering errors instead of using multiple returns to indicate errors.
	// The argument t is typically a *testing.T, but here it's a similar
	// interface to avoid needing to import "testing" (which registers global
	// command-line flags).
	T(t TestingT) WebDriverT
}

func NewRemote

func NewRemote(capabilities Capabilities, executor string) (WebDriver, error)

Create new remote client, this will also start a new session.

capabilities - the desired capabilities, see http://goo.gl/SNlAk
executor - the URL to the Selenim server

type WebDriverT

type WebDriverT interface {
	WebDriver() WebDriver

	NewSession() string

	SetAsyncScriptTimeout(ms uint)
	SetImplicitWaitTimeout(ms uint)
	Quit()

	CurrentWindowHandle() string
	WindowHandles() []string
	CurrentURL() string
	Title() string
	PageSource() string
	Close()
	SwitchFrame(frame string)
	SwitchFrameParent()
	SwitchWindow(name string)
	CloseWindow(name string)
	WindowSize(name string) *Size
	WindowPosition(name string) *Point
	ResizeWindow(name string, to Size)

	Get(url string)
	Forward()
	Back()
	Refresh()

	FindElement(by, value string) WebElementT
	FindElements(by, value string) []WebElementT
	ActiveElement() WebElement

	// Shortcut for FindElement(ByCSSSelector, sel)
	Q(sel string) WebElementT
	// Shortcut for FindElements(ByCSSSelector, sel)
	QAll(sel string) []WebElementT

	GetCookies() []Cookie
	AddCookie(cookie *Cookie)
	DeleteAllCookies()
	DeleteCookie(name string)

	Click(button int)
	DoubleClick()
	ButtonDown()
	ButtonUp()

	SendModifier(modifier string, isDown bool)
	Screenshot() []byte

	DismissAlert()
	AcceptAlert()
	AlertText() string
	SetAlertText(text string)

	ExecuteScript(script string, args []interface{}) interface{}
	ExecuteScriptAsync(script string, args []interface{}) interface{}
}

A single-return-value interface to WebDriverT that is useful when using WebDrivers in test code. Obtain a WebDriverT by calling webDriver.T(t), where t *testing.T is the test handle for the current test. The methods of WebDriverT call wt.t.Fatalf upon encountering errors instead of using multiple returns to indicate errors.

type WebElement

type WebElement interface {

	/* Click on element */
	Click() error
	/* Send keys (type) into element */
	SendKeys(keys string) error
	/* Submit */
	Submit() error
	/* Clear */
	Clear() error
	/* Move mouse to relative coordinates */
	MoveTo(xOffset, yOffset int) error

	/* Find children, return one element. */
	FindElement(by, value string) (WebElement, error)
	/* Find children, return list of elements. */
	FindElements(by, value string) ([]WebElement, error)

	// Shortcut for FindElement(ByCSSSelector, sel)
	Q(sel string) (WebElement, error)
	// Shortcut for FindElements(ByCSSSelector, sel)
	QAll(sel string) ([]WebElement, error)

	/* Element name */
	TagName() (string, error)
	/* Text of element */
	Text() (string, error)
	/* Check if element is selected. */
	IsSelected() (bool, error)
	/* Check if element is enabled. */
	IsEnabled() (bool, error)
	/* Check if element is displayed. */
	IsDisplayed() (bool, error)
	/* Get element attribute. */
	GetAttribute(name string) (string, error)
	/* Element location. */
	Location() (*Point, error)
	/* Element location once it has been scrolled into view.
	   Note: This is considered an internal command and should only be used to determine an element's location for correctly generating native events.*/
	LocationInView() (*Point, error)
	/* Element size */
	Size() (*Size, error)
	/* Get element CSS property value. */
	CSSProperty(name string) (string, error)

	// Get a WebElementT of this element that has methods that call t.Fatalf
	// upon encountering errors instead of using multiple returns to indicate
	// errors. The argument t is typically a *testing.T, but here it's a similar
	// interface to avoid needing to import "testing" (which registers global
	// command-line flags).
	T(t TestingT) WebElementT
}

type WebElementT

type WebElementT interface {
	WebElement() WebElement

	Click()
	SendKeys(keys string)
	Submit()
	Clear()
	MoveTo(xOffset, yOffset int)

	FindElement(by, value string) WebElementT
	FindElements(by, value string) []WebElementT

	// Shortcut for FindElement(ByCSSSelector, sel)
	Q(sel string) WebElementT
	// Shortcut for FindElements(ByCSSSelector, sel)
	QAll(sel string) []WebElementT

	TagName() string
	Text() string
	IsSelected() bool
	IsEnabled() bool
	IsDisplayed() bool
	GetAttribute(name string) string
	Location() *Point
	LocationInView() *Point
	Size() *Size
	CSSProperty(name string) string
}

A single-return-value interface to WebElement that is useful when using WebElements in test code. Obtain a WebElementT by calling webElement.T(t), where t *testing.T is the test handle for the current test. The methods of WebElementT call wt.fatalf upon encountering errors instead of using multiple returns to indicate errors.

Jump to

Keyboard shortcuts

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