• Stars
    star
    250
  • Rank 156,887 (Top 4 %)
  • Language
    Python
  • License
    MIT License
  • Created about 10 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

pytest splinter and selenium integration for anyone interested in browser interaction in tests

Splinter plugin for the pytest runner

Join the chat at https://gitter.im/pytest-dev/pytest-splinter Documentation Status

Install pytest-splinter

pip install pytest-splinter

Features

The plugin provides a set of fixtures to use splinter for browser testing with pytest

Fixtures

  • browser
    Get the splinter's Browser. Fixture is underneath session scoped, so browser process is started once per test session, but the state of the browser will be clean (current page is blank, cookies clean).
  • session_browser
    The same as browser except the lifetime. This fixture is session-scoped so will only be finalized at the end of the whole test session. Useful if you want to speedup your test suite paying with reduced test isolation.
  • browser_instance_getter
    Function to create an instance of the browser. This fixture is required only if you need to have multiple instances of the Browser in a single test at the same time. Example of usage:
@pytest.fixture
def admin_browser(request, browser_instance_getter):
    """Admin browser fixture."""
    # browser_instance_getter function receives parent fixture -- our admin_browser
    return browser_instance_getter(request, admin_browser)

def test_2_browsers(browser, admin_browser):
    """Test using 2 browsers at the same time."""
    browser.visit('http://google.com')
    admin_browser.visit('http://admin.example.com')
  • splinter_selenium_implicit_wait
    Implicit wait timeout to be passed to Selenium webdriver. Fixture gets the value from the command-line option splinter-implicit-wait (see below)
  • splinter_wait_time
    Explicit wait timeout (for waiting for explicit condition via wait_for_condition). Fixture gets the value from the command-line option splinter-wait-time (see below)
  • splinter_selenium_speed
    Speed for Selenium, if not 0 then it will sleep between each selenium command. Useful for debugging/demonstration. Fixture gets the value from the command-line option splinter-speed (see below)
  • splinter_selenium_socket_timeout
    Socket timeout for communication between the webdriver and the browser. Fixture gets the value from the command-line option splinter-socket-timeout (see below)
  • splinter_webdriver
    Splinter's webdriver name to use. Fixture gets the value from the command-line option splinter-webdriver (see below). To make pytest-splinter always use certain webdriver, override a fixture in your conftest.py file:
import pytest

@pytest.fixture(scope='session')
def splinter_webdriver():
    """Override splinter webdriver name."""
    return 'chrome'
  • splinter_remote_url
    Splinter's webdriver remote url to use (optional). Fixture gets the value from the command-line option splinter-remote-url (see below). Will be used only if selected webdriver name is 'remote'.
  • splinter_session_scoped_browser
    pytest-splinter should use single browser instance per test session. Fixture gets the value from the command-line option splinter-session-scoped-browser (see below)
  • splinter_file_download_dir
    Directory, to which browser will automatically download the files it will experience during browsing. For example when you click on some download link. By default it's a temporary directory. Automatic downloading of files is only supported for firefox driver at the moment.
  • splinter_download_file_types
    Comma-separated list of content types to automatically download. By default it's the all known system mime types (via mimetypes standard library).
  • splinter_browser_load_condition
    Browser load condition, python function which should return True. If function returns False, it will be run several times, until timeout below reached.
  • splinter_browser_load_timeout
    Browser load condition timeout in seconds, after this timeout the exception WaitUntilTimeout will be raised.
  • splinter_wait_time
    Browser explicit wait timeout in seconds, after this timeout the exception WaitUntilTimeout will be raised.
  • splinter_firefox_profile_preferences
    Firefox profile preferences, a dictionary which is passed to selenium webdriver's profile_preferences
  • splinter_firefox_profile_directory
    Firefox profile directory to use as template for firefox profile created by selenium. By default, it's an empty directly inside pytest_splinter/profiles/firefox
  • splinter_driver_kwargs
    Webdriver keyword arguments, a dictionary which is passed to selenium webdriver's constructor (after applying firefox preferences)
import pytest
from pathlib import Path

@pytest.fixture
def splinter_driver_kwargs():
    """
    Webdriver kwargs for Firefox.
    https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.firefox.webdriver
    """
    return {"service_log_path": Path("/log/directory/geckodriver.log")}

The snippet below configures Chrome to ignore certificate errors and sets a specific window size

import pytest
from selenium import webdriver

@pytest.fixture(scope='session')
def splinter_driver_kwargs():
    """Override Chrome WebDriver options"""
    chrome_options = webdriver.ChromeOptions()

    # List of Chromium Command Line Switches
    # https://peter.sh/experiments/chromium-command-line-switches/
    chrome_options.add_argument("--window-size=1440,1200")
    chrome_options.add_argument("--ignore-ssl-errors=yes")
    chrome_options.add_argument("--ignore-certificate-errors")

    return {"options": chrome_options}
  • splinter_window_size
    Size of the browser window on browser initialization. Tuple in form (<width>, <height>). Default is (1366, 768)
  • splinter_screenshot_dir
    pytest-splinter browser screenshot directory. This fixture gets the value from the command-line option splinter-screenshot-dir (see below).
  • splinter_make_screenshot_on_failure
    Should pytest-splinter take browser screenshots on test failure? This fixture gets the value from the command-line option splinter-make-screenshot-on-failure (see below).
  • splinter_screenshot_encoding
    Encoding of the html screenshot on test failure. UTF-8 by default.
  • splinter_screenshot_getter_html
    Function to get browser html screenshot. By default, it saves browser.html with given path and splinter_screenshot_encoding encoding.
  • splinter_screenshot_getter_png
    Function to get browser image (png) screenshot. By default, it calls browser.save_sceenshot with given path.
  • splinter_driver_executable
    Filesystem path of the webdriver executable. This fixture gets the value from the command-line option splinter-webdriver-executable (see below).
  • splinter_browser_class
    Class to use for browser instance. Defaults to pytest_splinter.plugin.Browser.
  • splinter_clean_cookies_urls
    List of additional urls to clean cookies on. By default, during the preparation of the browser for the test, pytest-splinter only cleans cookies for the last visited url from previous test, as it's not possible to clean all cookies from all domains at once via webdriver protocol, by design. This limitation can be worked around if you know the list of urls, the domains for which you need to clean cookies (for example https://facebook.com). If so, you can override this fixture and put those urls there, and pytest-splinter will visit each of them and will clean the cookies for each domain.
  • splinter_headless
    Run Chrome in headless mode. Defaults to false. http://splinter.readthedocs.io/en/latest/drivers/chrome.html#using-headless-option-for-chrome

Command-line options

  • --splinter-implicit-wait

    Selenium webdriver implicit wait. Seconds (default: 5).

  • --splinter-speed

    selenium webdriver speed (from command to command). Seconds (default: 0).

  • --splinter-socket-timeout

    Selenium webdriver socket timeout for for communication between the webdriver and the browser. Seconds (default: 120).

  • --splinter-webdriver

    Webdriver name to use. (default: firefox). Options:

    • firefox
    • remote
    • chrome

    For more details refer to the documentation for splinter and selenium.

  • --splinter-remote-url

    Webdriver remote url to use. (default: None). Will be used only if selected webdriver name is 'remote'.

    For more details refer to the documentation for splinter and selenium.

  • --splinter-session-scoped-browser

    pytest-splinter should use a single browser instance per test session. Choices are 'true' or 'false' (default: 'true').

  • --splinter-make-screenshot-on-failure

    pytest-splinter should take browser screenshots on test failure. Choices are 'true' or 'false' (default: 'true').

  • --splinter-screenshot-dir

    pytest-splinter browser screenshot directory. Defaults to the current directory.

  • --splinter-webdriver-executable

    Filesystem path of the webdriver executable. Used by chrome driver. Defaults to the None in which case the shell PATH variable setting determines the location of the executable.

  • --splinter-headless

    Override splinter_headless fixture. Choices are 'true' or 'false', default: 'true'. http://splinter.readthedocs.io/en/latest/drivers/chrome.html#using-headless-option-for-chrome https://splinter.readthedocs.io/en/latest/drivers/firefox.html#using-headless-option-for-firefox

Browser fixture

As mentioned above, browser is a fixture made by creating splinter's Browser object, but with some overrides.

  • visit
    Added possibility to wait for condition on each browser visit by having a fixture.
  • wait_for_condition
    Method copying selenium's wait_for_condition, with difference that condition is in python, so there you can do whatever you want, and not only execute javascript via browser.evaluate_script.

Automatic screenshots on test failure

When your functional test fails, it's important to know the reason. This becomes hard when tests are being run on the continuous integration server, where you cannot debug (using --pdb). To simplify things, a special behaviour of the browser fixture is available, which takes a screenshot on test failure and puts it in a folder with the a naming convention compatible to the jenkins plugin. The html content of the browser page is also stored, this can be useful for debugging the html source.

Creating screenshots is fully compatible with pytest-xdist plugin and will transfer the screenshots from the worker nodes through the communication channel automatically.

If a test (using the browser fixture) fails, you should get a screenshot files in the following path:

<splinter-screenshot-dir>/my.dotted.name.test.package/test_name-browser.png
<splinter-screenshot-dir>/my.dotted.name.test.package/test_name-browser.html

The splinter-screenshot-dir for storing the screenshot is generated by a fixture and can be provided through a command line argument, as described above at the configuration options section.

Taking screenshots on test failure is enabled by default. It can be controlled through the splinter_make_screenshot_on_failure fixture, where return False skips it. You can also disable it via a command line argument:

pytest tests/functional --splinter-make-screenshot-on-failure=false

In case taking a screenshot fails, a pytest warning will be issued, which can be viewed using the -rw argument for pytest.

Python3 support

Python3 is supported, check if you have recent version of splinter as it was added recently.

Example

test_your_test.py:

def test_some_browser_stuff(browser):
    """Test using real browser."""
    url = "http://www.google.com"
    browser.visit(url)
    browser.fill('q', 'splinter - python acceptance testing for web applications')
    # Find and click the 'search' button
    button = browser.find_by_name('btnK')
    # Interact with elements
    button.click()
    assert browser.is_text_present('splinter.cobrateam.info'), "splinter.cobrateam.info wasn't found... We need to"
    ' improve our SEO techniques'

Contact

If you have questions, bug reports, suggestions, etc. please create an issue on the GitHub project page.

License

This software is licensed under the MIT license

See License file

© 2014 Anatoly Bubenkov, Paylogic International and others.

More Repositories

1

pytest

The pytest framework makes it easy to write small tests, yet scales to support complex functional testing
Python
11,150
star
2

pytest-testinfra

Testinfra test your infrastructures
Python
2,306
star
3

pytest-mock

Thin-wrapper around the mock package for easier use with pytest
Python
1,725
star
4

pytest-cov

Coverage plugin for pytest.
Python
1,647
star
5

pytest-xdist

pytest plugin for distributed testing and loop-on-failures testing modes.
Python
1,318
star
6

pytest-asyncio

Asyncio support for pytest
Python
1,293
star
7

pytest-django

A Django plugin for pytest.
Python
1,286
star
8

pytest-bdd

BDD library for the py.test runner
Python
1,248
star
9

pluggy

A minimalist production ready plugin system
Python
1,136
star
10

pytest-html

Plugin for generating HTML reports for pytest results
Python
649
star
11

pyfakefs

Provides a fake file system that mocks the Python file system modules.
Python
596
star
12

pytest-randomly

🎲 Pytest plugin to randomly order tests and control random.seed
Python
573
star
13

pytest-flask

A set of pytest fixtures to test Flask applications
Python
471
star
14

pytest-qt

pytest plugin for Qt (PyQt5/PyQt6 and PySide2/PySide6) application testing
Python
376
star
15

pytest-rerunfailures

a pytest plugin that re-runs failed tests up to -n times to eliminate flakey failures
Python
351
star
16

pytest-factoryboy

factory_boy integration the pytest runner
Python
348
star
17

pytest-selenium

Plugin for running Selenium with pytest
Python
325
star
18

cookiecutter-pytest-plugin

A Cookiecutter template for pytest plugins 💻
Python
281
star
19

pytest-describe

Describe-style plugin for the pytest framework
Python
201
star
20

pytest-timeout

Python
193
star
21

pytest-subtests

unittest subTest() support and subtests fixture
Python
177
star
22

pytest-repeat

pytest plugin for repeating test execution
Python
158
star
23

pytest-order

pytest plugin that allows to customize the test execution order
Python
145
star
24

pytest-instafail

py.test plugin to show failures instantly
Python
130
star
25

unittest2pytest

helps rewriting Python `unittest` test-cases into `pytest` test-cases
Python
125
star
26

pytest-cpp

Use pytest's runner to discover and execute C++ tests
C++
114
star
27

pytest-github-actions-annotate-failures

Pytest plugin to annotate failed tests with a workflow command for GitHub Actions
Python
109
star
28

pytest-env

pytest plugin to set environment variables in pytest.ini or pyproject.toml file
Python
103
star
29

pytest-xprocess

pytest external process plugin
Python
94
star
30

pytest-reportlog

Replacement for the --resultlog option, focused in simplicity and extensibility
Python
75
star
31

pytest-variables

Plugin for providing variables to pytest tests/fixtures
Python
73
star
32

execnet

distributed Python deployment and communication
Python
72
star
33

pytest-play

pytest plugin that let you automate actions and assertions with test metrics reporting executing plain YAML files
Python
68
star
34

pytest-messenger

Pytest-messenger report plugin for all popular messengers like: Slack, DingTalk, Telegram
Python
67
star
35

py

Python development support library (note: maintenance only)
Python
66
star
36

pytest-random-order

pytest plugin to randomise the order of tests with some control over the randomness
Python
65
star
37

pytest-print

pytest-print adds the printer fixture you can use to print messages to the user (directly to the pytest runner, not stdout)
Python
63
star
38

pytest-mimesis

Mimesis integration with the pytest test runner. This plugin provider useful fixtures based on providers from Mimesis.
Python
62
star
39

pytest-services

Collection of fixtures and utility functions to run service processes for your tests
Python
58
star
40

pytest-forked

extracted --boxed from pytest-xdist to ensure backward compat
Python
58
star
41

pytest-runner

Python
57
star
42

pytest-metadata

Plugin for accessing test session metadata
Python
55
star
43

iniconfig

Python
49
star
44

apipkg

Python
48
star
45

pytest-twisted

test twisted code with pytest
Python
45
star
46

pytest-stress

A Pytest plugin that allows you to loop tests for a user defined amount of time.
Python
40
star
47

pytest-freezer

Pytest plugin providing a fixture interface for spulec/freezegun
Python
40
star
48

pytest-incremental

py-test plugin: an incremental test runner
Python
40
star
49

pytest-faker

faker integration the pytest test runner
Python
38
star
50

nose2pytest

Scripts to convert Python Nose tests to PyTest
Python
35
star
51

pytest-base-url

pytest plugin for URL based tests
Python
35
star
52

pytest-cloud

Distributed tests planner plugin for pytest testing framework.
Python
35
star
53

plugincompat

Test execution and compatibility checks for pytest plugins
CSS
34
star
54

pytest-fixture-tools

Pytest fixture tools
Python
32
star
55

pytest-faulthandler

py.test plugin that activates the fault handler module during testing
Python
27
star
56

pytest-echo

pytest plugin to dump environment variables, package version and generic attributes.
Python
21
star
57

pytest-localserver

py.test plugin to test server connections locally. This repository was migrated from Bitbucket.
Python
19
star
58

pytest-inline

pytest-inline is a pytest plugin for writing inline tests.
Python
14
star
59

pytest-nunit

An Nunit output plugin for Pytest
Python
10
star
60

design

Graphic design for Pytest project
9
star
61

pytest-plus

pytest-plus adds new features to pytest
Python
9
star
62

pytest-bpdb

pytest plugin for dropping to bpdb on test failures
Python
6
star
63

blog.pytest.org

Repository for the official pytest blog
Python
4
star
64

pytest-tcpclient

pytest mocking of TCP clients
Python
3
star
65

meta

Used for generic pytest organization issues, stuff that can impact multiple projects.
2
star
66

pytest-talks

public pytest talks and workshops - meant to help user groups spin up talks and workshops
HTML
1
star
67

regendoc

Python
1
star
68

sprint

pytest development sprint 2024
1
star