selenium

package module
v0.0.0-...-47abacc Latest Latest
Warning

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

Go to latest
Published: May 20, 2023 License: MIT Imports: 30 Imported by: 0

README

go-selenium

Go Reference Go Report Card

About

go-selenium is a library for interacting with the browserdriver by implementing W3C WebDriver recomendation using the Go programming language.

go-selenium supports the following browsers:

Installation

go get github.com/aleksslitvinovs/go-selenium

Usage

Create selenium_test.go file with the following example code:

package selenium_test

import (
	"fmt"
	"testing"
	"time"

	"github.com/aleksslitvinovs/go-selenium"
	"github.com/aleksslitvinovs/go-selenium/keys"
)

func Test(t *testing.T) {
	selenium.SetTest(MyTest)

	selenium.Run()
}

func MyTest(s *selenium.Session) {
	s.OpenURL("https://duckduckgo.com/")

	s.NewElement("#search_form_input_homepage").
		WaitFor(10 * time.Second).UntilIsVisible().
		SendKeys("theRealAlpaca/go-selenium").
		SendKeys(keys.Enter)

	result := s.NewElement("#r1-0 [data-testid=result-title-a]").
		WaitFor(10 * time.Second).UntilIsVisible().
		GetText()

	fmt.Printf("DuckDuckGo result: %s\n", result)
}

To run the, run go test.

Configuration

Even though the library is designed to work with the default configuration, it has many configurable options that are defined in .goseleniumrc.json file (generated automatically on the first run).

Automatically generated default .goseleniumrc.json:

{
  "logging": "info",
  "soft_asserts": false,
  "webdriver": {
    "browser": "chrome"
  }
}

All available configuration options:

Option Description Type Default
logging Logging level. string "info"
soft_asserts Use soft assertions, i.e., continue executing the test in case of an error. bool true
screenshot_dir Directory in which save screenshots. string ""
raise_errors_automatically Raise errors automatically when the test ends. bool true
runner object
runner.parallel_runs Number of parallel tests to execute. int 1
element object
element.selector_type Default selector type used when locating element. string css selector
element.ignore_not_found Throw error if element is not found. bool false
element.retry_timeout Timeout for trying to locate the given element. time 10s
element.poll_interval Time interval to validate element's state when using WaitFor() command. time 500ms
webdriver object
webdriver.browser Browser to use. string "chrome"
webdriver.manual_start Start browser driver process manually. bool false
webdriver.binary_path Path to browser driver binary. string "./chromedriver"
webdriver.remote_url URL with port to which WebDriver commands are sent. string "http://localhost:4444"
webdriver.timeout Time which which browser driver should be ready to accept command. time "10s"
webdriver.capabilities Browser capabilities. map[string]interface{} {}

Hooks

go-selenium provides optional before and after hooks that can be used to set up & tear down the test environment. Hooks must be set up before calling selenium.Run().

Before/after all hooks are called before/after all tests are executed. They can be set via:

Before/after each test hooks are called before/after each test is executed. They can be set via:

Helper packages

  • selenium/keys - contains list of keypress codes used for SendKeys().
  • selenium/selector - contains list of selector types used for NewElement().
  • selenium/types - contains types used for go-selenium, including, list of Webdriver error codes.
  • selenium/logger - contains logger to print out prettified logs.
Time format

Time type is defined as a string, e.g., 500ms, with the following format:

<duration><unit>

where <duration> is an integer and <unit> is one of the following time units:

  • ns - nanoseconds
  • us (or µs) - microseconds
  • ms - milliseconds
  • s - seconds
  • m - minutes
  • h - hours

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	//nolint:revive
	ErrUnsupportedPlatform = errors.Errorf(
		"unsupported platform %s %s", runtime.GOOS, runtime.GOARCH,
	)
)

Functions

func MustStopClient

func MustStopClient()

MustStopClient is a convenience function that wraps StopClient and panics in case an error is encountered.

func Run

func Run()

Run executes all set tests. If the client is not set, it sets one with the default driver based on the config settings.

func SetAfterAll

func SetAfterAll(fn func())

SetAfterAll sets the function that will be executed after all tests.

func SetAfterEach

func SetAfterEach(fn TestFunction)

SetAfterEach sets the function that will be executed after each test.

func SetBeforeAll

func SetBeforeAll(fn func())

SetBeforeAll sets the function that will be executed before all tests.

func SetBeforeEach

func SetBeforeEach(fn TestFunction)

SetBeforeEach sets the function that will be executed before each test.

func SetClient

func SetClient(d *Driver, opts *Opts) error

SetClient creates a new client instance with the provided driver. Based on the configuration settings, a driver may be started. Optionally, Opts can be provided for additional configuration.

func SetTest

func SetTest(fn TestFunction, name ...string)

SetTest sets the test function. The name is used to identify the test is optional. If no name is provided, test_<test_id> is used. If the given name is already in use, test ID is appended to the name.

func StopClient

func StopClient() error

StopClient stops the client and its driver.

Types

type Asserter

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

Asserter is a helper struct to assert the element's text, attributes, etc.

func (*Asserter) Attribute

func (a *Asserter) Attribute(attribute string) *Valuer

Attribute allows asserting the element's attributes.

func (*Asserter) Text

func (a *Asserter) Text() *Valuer

Text allows asserting the element's text.

type Driver

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

Driver resembles a browser Driver and parameters to connect to it.

func NewDriver

func NewDriver(webdriverPath string, remoteURL string) (*Driver, error)

NewDriver creates a new Driver with the supplied path to the browser driver executable and remote URL to use. If remoteURL is empty, ErrInvalidParameters error is returned.

func (*Driver) IsReady

func (d *Driver) IsReady(c *clientParams) (bool, error)

IsReady returns true if the browser driver is ready to create new sessions. An error is returned if there was an issue retrieving driver's status. TODO: make public and private methods.

func (*Driver) Start

func (d *Driver) Start(timeout *types.Time) error

Start starts the browser driver. Driver must be started within the provided timeout.

type E

type E struct {
	Selector     string `json:"value"`
	SelectorType string `json:"using"`
}

E is a helper struct that represents web element.

type Element

type Element struct {
	E
	// contains filtered or unexported fields
}

Element describes web element.

func (*Element) Clear

func (e *Element) Clear() *Element

Clear clears the text of the element.

func (*Element) Click

func (e *Element) Click() *Element

Click clicks on the element.

func (*Element) GetAttribute

func (e *Element) GetAttribute(attribute string) string

GetAttribute returns the value of the given attribute of the element. If the element does not have the given attribute, an empty string is returned.

func (*Element) GetText

func (e *Element) GetText() string

GetText returns the text of the element.

func (*Element) IsEnabled

func (e *Element) IsEnabled() bool

IsEnabled checks if the element is enabled.

func (*Element) IsPresent

func (e *Element) IsPresent() bool

IsPresent checks if the element is present in the DOM.

func (*Element) IsSelected

func (e *Element) IsSelected() bool

IsSelected checks if the element is selected.

func (*Element) IsVisible

func (e *Element) IsVisible() bool

IsVisible checks if the element is visible.

func (*Element) SendKeys

func (e *Element) SendKeys(input string) *Element

SendKeys sends the given keys to the element.

func (*Element) ShouldHave

func (e *Element) ShouldHave() *Asserter

ShouldHave returns an Asserter for the given element. The returned Asserter can be used to assert the element's text, attributes, etc.

func (*Element) WaitFor

func (e *Element) WaitFor(timeout time.Duration) *Waiter

WaitFor creates an instance of *Waiter with the provided timeout duration.

type Elements

type Elements struct {
	E
	// contains filtered or unexported fields
}

Elements describes a collection of Element type.

func (*Elements) Elements

func (ee *Elements) Elements() []*Element

Elements returns the list elements.

func (*Elements) Size

func (ee *Elements) Size() int

Size returns the number of elements.

type Handle

type Handle struct {
	ID   string `json:"handle"`
	Type string `json:"type"`
}

Handle represents a browser window or tab.

type Opts

type Opts struct {
	ConfigDirectory string
}

Opts contains configuration options for the client. TODO: Allow overwriting config values.

type Session

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

Session represents a single user agent. It describes connection between browser driver and the client.

func NewSession

func NewSession() (*Session, error)

NewSession creates a new session with the capabilities described in config.

func (*Session) AcceptAlert

func (s *Session) AcceptAlert() *Session

AcceptAlert accepts currently open alert dialog.

func (*Session) AddError

func (s *Session) AddError(err string)

AddError adds an error to the session's error list.

func (*Session) Back

func (s *Session) Back() *Session

Back navigates back in the browser history.

func (*Session) CloseWindow

func (s *Session) CloseWindow() *Session

CloseWindow closes the current browsing context. If there are no open handles for this browsing context, the session will be closed. Reference: https://www.w3.org/TR/webdriver/#close-window

func (*Session) DeleteSession

func (s *Session) DeleteSession()

DeleteSession deletes the given session.

func (*Session) DismissAlert

func (s *Session) DismissAlert() *Session

DismissAlert dismisses currently open alert dialog.

func (*Session) ExecuteScript

func (s *Session) ExecuteScript(script string, args ...string) interface{}

ExecuteScript executes user defined JavaScript function written as a string. ...args are passed to the function as arguments. Function's return value is returned as interface{}.

func (*Session) Forward

func (s *Session) Forward() *Session

Forward navigates forward in the browser history.

func (*Session) GetAlertText

func (s *Session) GetAlertText() string

GetAlertText gets text of currently open alert dialog.

func (*Session) GetCurrentURL

func (s *Session) GetCurrentURL() string

GetCurrentURL returns the current URL of the browsing context.

func (*Session) GetID

func (s *Session) GetID() string

GetID returns the session's ID.

func (*Session) GetPageSoure

func (s *Session) GetPageSoure() string

GetPageSoure returns HTML source of the current page.

func (*Session) GetTitle

func (s *Session) GetTitle() string

GetTitle returns the current page title.

func (*Session) GetWindowHandle

func (s *Session) GetWindowHandle() string

GetWindowHandle returns the current browsing context handle.

func (*Session) GetWindowHandles

func (s *Session) GetWindowHandles() []string

GetWindowHandles returns all open browsing contexts' handles.

func (*Session) NewElement

func (s *Session) NewElement(e interface{}) *Element

NewElement returns a new Element. The parameter can be either a selector ( uses session's default locator) or *E or E struct.

func (*Session) NewElements

func (s *Session) NewElements(e interface{}) *Elements

NewElements return a new Elements. The parameter can be either a selector ( uses session's default locator) or *E or E struct.

func (*Session) NewTab

func (s *Session) NewTab() *Handle

NewTab opens a new browser tab.

func (*Session) NewWindow

func (s *Session) NewWindow() *Handle

NewWindow opens a new browser window.

func (*Session) OpenURL

func (s *Session) OpenURL(url string) *Session

OpenURL opens a new window with the given URL.

func (*Session) RaiseErrors

func (s *Session) RaiseErrors() string

RaiseErrors raises all the session's errors.

func (*Session) Refresh

func (s *Session) Refresh() *Session

Refresh refreshes the current page.

func (*Session) SendAlertText

func (s *Session) SendAlertText(text string) *Session

SendAlertText sends text to currently open prompt dialog.

func (*Session) SwitchHandle

func (s *Session) SwitchHandle(handle string)

SwitchHandle switches to the handle using the provided handle ID.

func (*Session) SwitchToFrame

func (s *Session) SwitchToFrame(e *Element) *Session

SwitchToFrame switches current browsing context to the specified iframe using the provided element. If nil is provided, the session will switch to the top-level browsing context.

func (*Session) SwitchToParentFrame

func (s *Session) SwitchToParentFrame() *Session

SwitchToParentFrame switches to the parent frame of the given browsing context.

func (*Session) TakeScreenshot

func (s *Session) TakeScreenshot(name string) *Session

TakeScreenshot takes a screenshot of the current browsing context. Screenshot file is created in screenshot_path directory based on the config. The file can have .png, .jpg or .jpeg extension.

func (*Session) UseCSS

func (s *Session) UseCSS()

UseCSS sets session's locator strategy to CSS. All future NewElement calls will use CSS as the default locator strategy.

func (*Session) UseXPath

func (s *Session) UseXPath()

UseXPath sets session's locator strategy to XPath. All future NewElement calls will use XPath as the default locator strategy.

type TestFunction

type TestFunction func(s *Session)

TestFunction describes one test for the given session. It is used in selenium.Run() to execute tests.

type Valuer

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

Valuer is a helper struct to compare the actual value of an element with the expected using various comparison functions.

func (*Valuer) Contain

func (v *Valuer) Contain(expected string)

Contain asserts that the actual value of the element contains the given.

func (*Valuer) EndWith

func (v *Valuer) EndWith(expected string)

EndWith asserts that the actual value of the element ends with the given.

func (*Valuer) EqualTo

func (v *Valuer) EqualTo(expected string)

EqualTo asserts that the actual value of the element is equal to the given.

func (*Valuer) Not

func (v *Valuer) Not() *Valuer

Not negates the following assertion.

func (*Valuer) StartWith

func (v *Valuer) StartWith(expected string)

StartWith asserts that the actual value of the element starts with the given.

type Waiter

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

Waiter is a helper struct to wait for an element to be present, visible, etc.

func (*Waiter) UntilIsEnabled

func (w *Waiter) UntilIsEnabled() *Element

UntilIsEnabled waits until the element is enabled.

func (*Waiter) UntilIsNotEnabled

func (w *Waiter) UntilIsNotEnabled() *Element

UntilIsNotEnabled waits until the element is not enabled.

func (*Waiter) UntilIsNotPresent

func (w *Waiter) UntilIsNotPresent() *Element

UntilIsNotPresent waits until the element is not present.

func (*Waiter) UntilIsNotSelected

func (w *Waiter) UntilIsNotSelected() *Element

UntilIsNotSelected waits until the element is not selected.

func (*Waiter) UntilIsNotVisible

func (w *Waiter) UntilIsNotVisible() *Element

UntilIsNotVisible waits until the element is visible.

func (*Waiter) UntilIsPresent

func (w *Waiter) UntilIsPresent() *Element

UntilIsPresent waits until the element is present.

func (*Waiter) UntilIsSelected

func (w *Waiter) UntilIsSelected() *Element

UntilIsSelected waits until the element is selected.

func (*Waiter) UntilIsVisible

func (w *Waiter) UntilIsVisible() *Element

UntilIsVisible waits until the element is visible.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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