pytest-selenium is a plugin for pytest that provides support for running Selenium based tests.
pytest-dev / pytest-selenium Goto Github PK
View Code? Open in Web Editor NEWPlugin for running Selenium with pytest
License: Other
Plugin for running Selenium with pytest
License: Other
As Firefox support geckodriver, as listed in
https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver
py.test --base-url http://<myapp-ip>:8081 --host selenium-host --port 4444 --driver Remote --capability browserName firefox --capability marionette true mytest
@pytest.fixture
def selenium(request):
"""Returns a WebDriver instance based on options and capabilities"""
driver_type = request.config.getoption('driver')
if driver_type is None:
raise pytest.UsageError('--driver must be specified')
driver_fixture = '{0}_driver'.format(driver_type.lower())
> driver = request.getfuncargvalue(driver_fixture)
/usr/lib/python2.7/site-packages/pytest_selenium/pytest_selenium.py:82:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/lib/python2.7/site-packages/pytest_selenium/drivers/remote.py:41: in remote_driver
browser_profile=firefox_profile)
/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py:90: in __init__
self.start_session(desired_capabilities, browser_profile)
/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py:177: in start_session
response = self.execute(Command.NEW_SESSION, capabilities)
/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py:236: in execute
self.error_handler.check_response(response)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x160ea90>
response = {'status': 500, 'value': '{"state":"unhandled error","sessionId":null,"hCode":536781276,"value":{"localizedMessage":"T...3,"class":"java.lang.IllegalStateException","screen":null},"class":"org.openqa.selenium.remote.Response","status":13}'}
def check_response(self, response):
"""
Checks that a JSON response from the WebDriver does not have an error.
:Args:
- response - The JSON response from the WebDriver server as a dictionary
object.
:Raises: If the response contains an error message.
"""
status = response.get('status', None)
if status is None or status == ErrorCode.SUCCESS:
return
value = None
message = response.get("message", "")
screen = response.get("screen", "")
stacktrace = None
if isinstance(status, int):
value_json = response.get('value', None)
if value_json and isinstance(value_json, basestring):
import json
try:
value = json.loads(value_json)
status = value.get('error', None)
if status is None:
status = value["status"]
message = value["value"]
if not isinstance(message, basestring):
value = message
try:
message = message['message']
except TypeError:
message = None
else:
message = value.get('message', None)
except ValueError:
pass
exception_class = ErrorInResponseException
if status in ErrorCode.NO_SUCH_ELEMENT:
exception_class = NoSuchElementException
elif status in ErrorCode.NO_SUCH_FRAME:
exception_class = NoSuchFrameException
elif status in ErrorCode.NO_SUCH_WINDOW:
exception_class = NoSuchWindowException
elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
exception_class = StaleElementReferenceException
elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
exception_class = ElementNotVisibleException
elif status in ErrorCode.INVALID_ELEMENT_STATE:
exception_class = InvalidElementStateException
elif status in ErrorCode.INVALID_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER:
exception_class = InvalidSelectorException
elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
exception_class = ElementNotSelectableException
elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
exception_class = WebDriverException
elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
exception_class = WebDriverException
elif status in ErrorCode.TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.SCRIPT_TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.UNKNOWN_ERROR:
exception_class = WebDriverException
elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
exception_class = UnexpectedAlertPresentException
elif status in ErrorCode.NO_ALERT_OPEN:
exception_class = NoAlertPresentException
elif status in ErrorCode.IME_NOT_AVAILABLE:
exception_class = ImeNotAvailableException
elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
exception_class = ImeActivationFailedException
elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
exception_class = MoveTargetOutOfBoundsException
else:
exception_class = WebDriverException
if value == '' or value is None:
value = response['value']
if isinstance(value, basestring):
if exception_class == ErrorInResponseException:
raise exception_class(response, value)
raise exception_class(value)
if message == "" and 'message' in value:
message = value['message']
screen = None
if 'screen' in value:
screen = value['screen']
stacktrace = None
if 'stackTrace' in value and value['stackTrace']:
stacktrace = []
try:
for frame in value['stackTrace']:
line = self._value_or_default(frame, 'lineNumber', '')
file = self._value_or_default(frame, 'fileName', '<anonymous>')
if line:
file = "%s:%s" % (file, line)
meth = self._value_or_default(frame, 'methodName', '<anonymous>')
if 'className' in frame:
meth = "%s.%s" % (frame['className'], meth)
msg = " at %s (%s)"
msg = msg % (meth, file)
stacktrace.append(msg)
except TypeError:
pass
if exception_class == ErrorInResponseException:
raise exception_class(response, message)
elif exception_class == UnexpectedAlertPresentException and 'alert' in value:
raise exception_class(message, screen, stacktrace, value['alert'].get('text'))
> raise exception_class(message, screen, stacktrace)
E WebDriverException: Message: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/jgraham/wires. The latest version can be downloaded from https://github.com/jgraham/wires
E Stacktrace:
E at com.google.common.base.Preconditions.checkState (Preconditions.java:199)
E at org.openqa.selenium.remote.service.DriverService.findExecutable (DriverService.java:109)
E at org.openqa.selenium.firefox.GeckoDriverService.access$0 (GeckoDriverService.java:1)
E at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable (GeckoDriverService.java:80)
E at org.openqa.selenium.remote.service.DriverService$Builder.build (DriverService.java:296)
E at org.openqa.selenium.firefox.MarionetteDriver.setupService (MarionetteDriver.java:94)
E at org.openqa.selenium.firefox.MarionetteDriver.<init> (MarionetteDriver.java:71)
E at org.openqa.selenium.firefox.MarionetteDriver.<init> (MarionetteDriver.java:49)
E at sun.reflect.NativeConstructorAccessorImpl.newInstance0 (NativeConstructorAccessorImpl.java:-2)
E at sun.reflect.NativeConstructorAccessorImpl.newInstance (NativeConstructorAccessorImpl.java:62)
E at sun.reflect.DelegatingConstructorAccessorImpl.newInstance (DelegatingConstructorAccessorImpl.java:45)
E at java.lang.reflect.Constructor.newInstance (Constructor.java:423)
E at org.openqa.selenium.remote.server.FirefoxDriverProvider.callConstructor (FirefoxDriverProvider.java:91)
E at org.openqa.selenium.remote.server.FirefoxDriverProvider.newInstance (FirefoxDriverProvider.java:66)
E at org.openqa.selenium.remote.server.DefaultDriverFactory.newInstance (DefaultDriverFactory.java:60)
E at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call (DefaultSession.java:222)
E at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call (DefaultSession.java:1)
E at java.util.concurrent.FutureTask.run (FutureTask.java:266)
E at org.openqa.selenium.remote.server.DefaultSession$1.run (DefaultSession.java:176)
E at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1142)
E at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:617)
E at java.lang.Thread.run (Thread.java:745)
Hi All,
I am using the pytest selenium and test one software, right now, I found a problem.
in unittest python, it always have setUpClass and tearDownClass, while in py.test it all changed to fixture,
I am confused by one issue, my requirements like below:
I have a selenium test case: create one app, and start app, stop app, and suspend app
For above operation, I have like blew:
Class APPOPS:
def start_app(self):
...
def stop_app(self):
...
Both those need app existed first, so I need to create app for all those tests, I want to make start_app and stop_app share the same app, which can reduce test time(let's forget test random run case first).
for setUpClass, it is easy for me
for fixture it always in separate file, like conftest.py
, the problem is that is it good way to do create app logic in confest.py
file? I didn't think it is good to do that. As create app is so special, it should not be put in conftest.py general like that
Do you suggest other better ways ? Thanks
Hello everyone,
I am trying using this the plugin with Appium Python Library and Selenium Grid. But I have a question. I am trying add a screenshot etc. in report.html like robot framework but I can't do it. I can take screenshot anywhere of code except error.
My running code:
py.test --driver Remote --capability platform ANDROID --html=report.html ~/testdatafile/tests/
Currently we default to the 'Remote' driver, which could suggest a preference of starting a Selenium server. Instead I would suggest removing the default, and failing with a list of accepted drivers if none is specified.
When trying to use --firefox-preference from command line or from pytest.ini like this:
"C:\automated_test_scripts\tests>pytest -v -s --firefox-preference="browser.helperApps.neverAsk.openFile"="application/excel" test_login.py"
i got error:
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: argument --firefox-preference: expected 2 argument(s).
I tried different combination and all the time i got the same error.
I using a synthax in command line from >pytest -h
Hi,
I have upgraded pytest-selenium from 1.0b2 to 1.0b4. The error in command prompt I got is different between both.
Both error generated was because URL is blank while I try to get the page title. I was using local remote Firefox driver when getting this error.
Personally I think the error for 1.0b4 is due to the plugin crashed after web driver throwing exception.
I didn't have chance to try with 1.0b3. Sorry for that.
Instead of the fixture returning a custom object with properties, we should simplify and just implement a 'selenium' fixture that returns the Selenium client object.
I'd like proxy plugins such as pytest-browsermob-proxy and pytest-zap to influence the proxy configured by the Selenium instance. Any proxy configured directly by users of pytest-selenium should become an upstream proxy in the third-party plugins, thus creating a proxy chain. Ideally, the third-party proxy plugins would also inherit proxy configuration from each other, so we can have more than two proxies in a chain.
Hi, I'm using py.test and django. After installing pytest-selenium
, I got the following error.
Can anyone shed some light on this?
$ py.test
Test session starts (platform: darwin, Python 3.5.2, pytest 3.0.2, pytest-sugar 0.7.1)
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/main.py", line 94, in wrap_session
INTERNALERROR> config.hook.pytest_sessionstart(session=session)
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 724, in __call__
INTERNALERROR> return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 338, in _hookexec
INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 333, in <lambda>
INTERNALERROR> _MultiCall(methods, kwargs, hook.spec_opts).execute()
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 596, in execute
INTERNALERROR> res = hook_impl.function(*args)
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/pytest_sugar.py", line 217, in pytest_sessionstart
INTERNALERROR> lines = self.config.hook.pytest_report_header(config=self.config)
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 724, in __call__
INTERNALERROR> return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 338, in _hookexec
INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 333, in <lambda>
INTERNALERROR> _MultiCall(methods, kwargs, hook.spec_opts).execute()
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 593, in execute
INTERNALERROR> args = [all_kwargs[argname] for argname in hook_impl.argnames]
INTERNALERROR> File "/Users/jon/.virtualenvs/webapp/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 593, in <listcomp>
INTERNALERROR> args = [all_kwargs[argname] for argname in hook_impl.argnames]
INTERNALERROR> KeyError: 'startdir'
I tested this with both selenium 3.0.0b2 and 2.53.6 -- same error. When I uninstalled pytest-selenium
the error went away.
Here's an example project, sorry it's so big but it's the quickest way to get where I am now.
To reproduce, pip install -r requirements/test.txt && pip install -r requirements/local.txt
, then py.test
I also had to properly space line 49 in /Users/jon/.virtualenvs/example/lib/python3.5/site-packages/selenium/webdriver/safari/webdriver.py
to fall under the if statement, per this commit.
Hi,
When using pytest-selenium and running my test, I see this at the start:
platform darwin -- Python 3.4.3 -- py-1.4.30 -- pytest-2.7.2
rootdir: /bokeh/bokeh, inifile: setup.cfg
plugins: html, selenium, selenium, variables
collected 410 items
I think it's disconcerting that the plugins line reads: plugins: html, selenium, selenium, variables
I think it comes from having the separate safety.py
file.
I have pytest==2.8.4
and pytest-selenium==1.0
installed.
When I run py.test
, I get the following warning:
WI1 /home/username/.virtualenvs/login/lib/python3.4/site-packages/pytest_selenium/pytest_selenium.py:90
'pytest_runtest_makereport' hook uses deprecated __multicall__ argument
Hi,
Currently I run this test command below:
py.test --driver Remote --capability browserName firefox --html=Results\report.html
However, can I ask to add a feature to accept shorten browser name?
Example:
for firefox, it can accept firefox, ff
for chrome, it is accept command with chrome, gc
Thank you.
I'd like to revisit and clean up the existing command line options. Here are the current options, with some suggestions for improvements:
Why isn't Safari supported, and might this change anytime soon?
At the moment we accept capabilities on the command line using --capability=key:value
and we cast the value to an integer or a boolean if it looks like one. This means we can't specify a value that looks like an integer but we want to be treated as a string. It also means we can't specify lists or dictionaries as values.
Previously, in pytest-mozwebqa we had a --capabilties=json
command line option, which took a string representation of a JSON object and created a dictionary from that in Python. If I recall correctly, the problems this cause were that string escaping turned out to be a real pain across platforms, and we had to specify all of the capabilities in one command line option.
I'd like to solicit suggestions on how we can improve this. Doing so will allow us to replace the Chrome options with capabilities on the command line, and replace the Sauce Labs tags configuration option with command line capabilties.
Any thoughts @bobsilverberg, @justinpotts?
Hi May i consult about the
Selenium testing scenarios
Maybe we need a incremental steps for the selenium testing ,
but i have tried that the selenium plugin in class when a new test init it will reopen a new browser.
how could using incremental with parameter ?
seems selenium plugin is a function not a class so i don't know the sample of it
Thanks
import pytest
import unittest
scenario1 = ('basic', {'attribute': 'value'})
scenario2 = ('advanced', {'attribute': 'value2'})
@pytest.mark.incremental
class TestSelenium():
scenarios = [scenario1, scenario2]
@pytest.fixture(autouse=True)
def init_browser(self,SeleniumBase):
self.SeleniumBase = SeleniumBase
#yield # everything after 'yield' is executed on tear-down
#self.browser.quit()
def test_demo1(self, attribute):
print(attribute)
self.SeleniumBase.open("https://www.google.com.tw")
print(self.SeleniumBase.currentUrl()+ "aaaa")
def test_demo2(self, attribute):
print(attribute)
print(self.SeleniumBase.currentUrl()+ "bbbbbb")
here is my basecode of SeleniumBaseClass
class SeleniumBaseClass(object):
def __init__(self,driver):
self.driver = driver
print("AAAA")
def open(self,URL):
self.driver.get(URL)
self.driver.maximize_window()
def currentUrl(self):
return self.driver.current_url
def locateElement(self, loc):
try:
print(loc)
element = WebDriverWait(self.driver,10).until(EC.visibility_of_element_located(loc))
return element
except:
print ("cannot find {0} element".format(loc))
def send_key_with_Element(self,loc,value):
self.locateElement(loc).clear()
self.locateElement(loc).send_keys(value)
def click_with_Element(self,loc):
self.locateElement(loc).click()
Hi,
Wonder if its possible to only generate a report when a test returns as a failure ?
Had a look at the docs and only see info relating too selenium_capture_debug
thanks
Browser Version:
OS Version:
I have a dynamic page written with jQuery. My page changes a lot and I need to wait in order to give time to the page to render some elements that are necessary for test a specific procedure.
What's happening and even if I am using these lines of code:
WebDriverWait(selenium, 30).until(EC.text_to_be_present_in_element((By.ID, "topnav"), 'My account'))
selenium.find_element_by_id("user-info").click()
In the second line when I try to click on the element that should be present on the page, the code is raising a Not Visible Exception.
I have seen that sometimes this can happen but it is a very unpredictable behaviour because sometimes it works and sometimes it does not work.
Do you have any ideas?
The PNG files that pytest-selenium writes to the "assets" folder that it creates in support of its HTML report cannot be opened on OSX 10.11.6. This is pytest-selenium 1.3.1 with selenium 2.53.6 as installed via pip, running under Python 3.5.1 and using --driver Firefox.
The images are displayed as broken image icons in the report, and attempts to open the PNG files directly produce "The file (long, randomized name).png could not be opened โฆ it may be damaged or use a file format that Preview doesn't recognize" from Preview. The image files are not empty; one of them is 111 KB in size and the other is 3.8 MB.
When I use the WebDriver's save_screenshot method (from the "selenium" fixture) directly at the end of my tests, it saves undamaged and correct screenshot PNG images (36 KB and 1.3 MB). In this case, the tests are successful, while I intentionally made tests fail in order to produce screenshots in pytest-selenium's HTML report.
My tests dynamically start their own server and so the _verify_base_url check seems to fail.
Is it possible to skip it? If not, would you be up for an option to skip it?
I have following version installed
pytest==2.9.2
pytest-selenium==1.3.1
selenium == 2.53.0
And have my app test like below:
26 def click_app_save_button(self):
27 save_elem = self.selenium.find_element(*self._app_save_button_locator)
28 ActionChains(self.selenium).move_to_element(save_elem).click().perform()
Hit errors like below:
02:59:00.034 INFO - Executing: [find element: By.cssSelector: button.btn.green])
02:59:00.453 INFO - Done: [find element: By.cssSelector: button.btn.green]
02:59:00.509 INFO - Executing: [mousemove: 11 false])
02:59:00.607 INFO - Done: [mousemove: 11 false]
02:59:00.661 INFO - Executing: [click: nothing])
02:59:00.693 WARN - Exception thrown
org.openqa.selenium.WebDriverException: Element is not clickable at point (477.25, 588). Other element would receive the click: <div style="z-index: 10050;" class="modal-scrollable"></div> (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 30 milliseconds
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: '5963827d09ef', ip: '172.17.0.4', os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0-123.el7.x86_64', java.version: '1.8.0_03-Ubuntu'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=45.0.2, platform=LINUX, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 7085aa70-86d2-417f-9ec2-a2bf40572cd5
at sun.reflect.GeneratedConstructorAccessor37.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at org.openqa.selenium.remote.RemoteExecuteMethod.execute(RemoteExecuteMethod.java:35)
at org.openqa.selenium.remote.RemoteMouse.click(RemoteMouse.java:59)
at org.openqa.selenium.support.events.internal.EventFiringMouse.click(EventFiringMouse.java:42)
at org.openqa.selenium.remote.server.handler.interactions.ClickInSession.call(ClickInSession.java:40)
at org.openqa.selenium.remote.server.handler.interactions.ClickInSession.call(ClickInSession.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:176)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
02:59:00.693 WARN - Exception: Element is not clickable at point (477.25, 588). Other element would receive the click: <div style="z-index: 10050;" class="modal-scrollable"></div> (WARNING: The server did not provide any stacktrace information)
I'm not sure what this option is meant to do, but I was surprised when it removed the screenshot from my test failure report. Can you clarify each of the options to selenium_exclude_debug
I'm currently setting the profile via command line with --firefox-profile=PATH, but am wondering if it is possible to do so with a fixture. I was looking through the codebase and saw --firefox-path is set via firefox-profile in pytest_selenium.py. I also saw this ticket relating to defining preferences #86
So I set up my fixture like so, but it seems to not use the correct profile
@pytest.fixture
def firefox_profile(firefox_profile):
firefox_profile = '[PATH]'
return firefox_profile
Edit: So it turns out the set up I have in conftest works fine, the issue is being caused by an additional pytest_addoption I'm passing through.
Selenium and splinter happily open Chrome on my computer, which suggests I've installed dependencies properly, but pytest-splinter won't start with Chrome. The Chrome window opens and closes immediately, re-opens and re-closes immediately, etc. While the flashing effect is nice, it isn't particularly useful ;-)
I found out that I keep hitting the except (IOError, HTTPException, WebDriverException):
code path in prepare_browser
which closes the browser and restarts it.
Here's a stack trace of how I end up there.
WebDriverException Traceback (most recent call last)
/Users/myk/.virtualenvs/amalfi/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py in set_window_size(self, width, height, windowHandle)
844 'width': int(width),
845 'height': int(height),
--> 846 'windowHandle': windowHandle})
847
848 def get_window_size(self, windowHandle='current'):
/Users/myk/.virtualenvs/amalfi/lib/python3.5/site-packages/pytest_splinter/webdriver_patches.py in execute(self, driver_command, params)
54
55 def execute(self, driver_command, params=None):
---> 56 result = self._base_execute(driver_command, params)
57 speed = self.get_speed()
58 if speed > 0:
/Users/myk/.virtualenvs/amalfi/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py in execute(self, driver_command, params)
234 response = self.command_executor.execute(driver_command, params)
235 if response:
--> 236 self.error_handler.check_response(response)
237 response['value'] = self._unwrap_value(
238 response.get('value', None))
/Users/myk/.virtualenvs/amalfi/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
190 elif exception_class == UnexpectedAlertPresentException and 'alert' in value:
191 raise exception_class(message, screen, stacktrace, value['alert'].get('text'))
--> 192 raise exception_class(message, screen, stacktrace)
193
194 def _value_or_default(self, obj, key, default):
WebDriverException: Message: unknown error: No current window
JavaScript stack:
Error: No current window
at checkForExtensionError (chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/background.js:14:17)
at null.callback (chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/background.js:67:5)
at safeCallbackApply (extensions::sendRequest:21:15)
at handleResponse (extensions::sendRequest:74:7)
(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),platform=Mac OS X 10.11.6 x86_64)
Here's my current workaround:
@pytest.fixture(scope='session')
def splinter_window_size(splinter_webdriver, splinter_window_size):
"""
Prevent pytest-splinter from crashing with Chrome.
"""
if splinter_webdriver == 'chrome':
return None
return splinter_window_size
At the moment usernames and keys for services like Sauce Labs, BrowserStack and TestingBot can either be set via environment variables or in the shared pytest configuration file. Using the configuration file means both private and public options are shared. It can also be difficult to manage when the configuration file is checked into source control and you don't want to expose your credentials to others.
I think it makes sense to add support for new configuration files such as .saucelabs
, .browserstack
, and .testingbot
to hold these sensitive values. These should be able to be stored in the project directory (and can easily be ignored from version control), any parent directory, or the user's home directory. The files should be discovered in this order and the first match should take priority, allowing projects to override user defaults.
I mainly use conda to install pytest-selenium.
I currently build my own binaries and upload them to mine and the bokeh conda channels.
I'd like to propose adding a recipe to conda-forge - https://conda-forge.github.io/
I'm happy to take the lead on this, but obviously wanted to get comments first.
Hi!
Is there any way to use only one selenium instance for running various tests? I found that the selenium fixture is scoped by default as function level. But I could not found any way to overtake this using any pytest functionality.
Thanks
Opera has changed substantially since I last tested it, and I suspect that we may need to improve the experience. At very least we should provide a decent guide to getting Opera configured for running tests. We should also see if there's a way to get the Opera tests running on Travis-CI.
Currently, when setting up saucelabs with pytest-selenium, you can provide the environment variables SAUCELABS_USERNAME
and SAUCELABS_API_KEY
. If you need to use SauceLabs connect (which I do) then when setting up travis you provide the same information but with slightly differently named environment variable SAUCE_USERNAME
and SAUCE_ACCESS_KEY
https://docs.travis-ci.com/user/sauce-connect/#Setting-up-Sauce-Connect.
I don't want to get rid of the existing env names, it would be nice if I could also use SAUCE_USERNAME
and SAUCE_ACCESS_KEY
too.
Hi,
I tried to setup a base_url
configuration following step by step the latest documentation:
Providing the base_url
configuration using a setup.cfg
file or using the command line option --base-url
didn't worked for me. Let's suppose to have a base_url
option set to http://google.com
.
Dummy test code:
def test_dummy(base_url, selenium):
assert 1
Expected result (try with py.test --driver Firefox
plus setup.cfg
for example):
base_url
should be equals to http://google.com
Instead I got:
I had a look at the pytest-selenium
tests and I've seen that you've been using a @pytest.mark.nondestructive
decorator and now it works fine:
import pytest
@pytest.mark.nondestructive
def test_dummy(base_url, selenium):
assert 1
So my question is: is there a problem with the documentation or this is a bug?
Thanks in advance.
If Selenium or the browser instance has crashed, it's not possible to gather debug. We should catch any WebDriver exceptions in pytest_runtest_makereport
to make sure generating the report doesn't cause further exceptions. It would also be good to include details of the exception to indicate why we failed to gather debug.
We may need to improve the experience when running against PhantomJS. At very least we should provide a decent guide to getting PhantomJS configured for running tests. We should also see if there's a way to get the PhantomJS tests running on Travis-CI.
I'm experiencing random failures. Since it seems things happen before the actual test logic is started, I assume it's an issue with selenium/pytest-selenium. Is there a better way to debug the problem?
The timeout comes from using pytest-timeout.
@pytest.fixture
def selenium(request, capabilities):
"""Returns a WebDriver instance based on options and capabilities"""
from .driver import start_driver
> driver = start_driver(request.node, capabilities)
/usr/local/lib/python2.7/dist-packages/pytest_selenium/pytest_selenium.py:75:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/local/lib/python2.7/dist-packages/pytest_selenium/driver.py:26: in start_driver
options.driver.lower()))(item, _capabilities)
/usr/local/lib/python2.7/dist-packages/pytest_selenium/driver.py:51: in chrome_driver
return webdriver.Chrome(**kwargs)
/usr/local/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py:67: in __init__
desired_capabilities=desired_capabilities)
/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py:87: in __init__
self.start_session(desired_capabilities, browser_profile)
/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py:141: in start_session
'desiredCapabilities': desired_capabilities,
/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py:199: in execute
response = self.command_executor.execute(driver_command, params)
/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/remote_connection.py:395: in execute
return self._request(command_info[0], url, body=data)
/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/remote_connection.py:426: in _request
resp = self._conn.getresponse()
/usr/lib/python2.7/httplib.py:1127: in getresponse
response.begin()
/usr/lib/python2.7/httplib.py:453: in begin
version, status, reason = self._read_status()
/usr/lib/python2.7/httplib.py:409: in _read_status
line = self.fp.readline(_MAXLINE + 1)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <socket._fileobject object at 0x7faae15b6bd0>, size = 65537
def readline(self, size=-1):
buf = self._rbuf
buf.seek(0, 2) # seek end
if buf.tell() > 0:
# check if we already have it in our buffer
buf.seek(0)
bline = buf.readline(size)
if bline.endswith('\n') or len(bline) == size:
self._rbuf = StringIO()
self._rbuf.write(buf.read())
return bline
del bline
if size < 0:
# Read until \n or EOF, whichever comes first
if self._rbufsize <= 1:
# Speed up unbuffered case
buf.seek(0)
buffers = [buf.read()]
self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
data = None
recv = self._sock.recv
while True:
try:
while data != "\n":
data = recv(1)
if not data:
break
buffers.append(data)
except error, e:
# The try..except to catch EINTR was moved outside the
# recv loop to avoid the per byte overhead.
if e.args[0] == EINTR:
continue
raise
break
return "".join(buffers)
buf.seek(0, 2) # seek end
self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
while True:
try:
data = self._sock.recv(self._rbufsize)
except error, e:
if e.args[0] == EINTR:
continue
raise
if not data:
break
nl = data.find('\n')
if nl >= 0:
nl += 1
buf.write(data[:nl])
self._rbuf.write(data[nl:])
del data
break
buf.write(data)
return buf.getvalue()
else:
# Read until size bytes or \n or EOF seen, whichever comes first
buf.seek(0, 2) # seek end
buf_len = buf.tell()
if buf_len >= size:
buf.seek(0)
rv = buf.read(size)
self._rbuf = StringIO()
self._rbuf.write(buf.read())
return rv
self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
while True:
try:
> data = self._sock.recv(self._rbufsize)
E Failed: Timeout >600s
/usr/lib/python2.7/socket.py:480: Failed
Hi,
Currently if I want to generate HTML report, I need to add "--html" on command line, will it possible to adding this on setup.cfg?
Thanks.
I think it would make sense for the various cloud providers (Sauce Labs, BrowserStack, TestingBot) to be reimplemented as plugins. This would give more flexibility than the current implementation as each provider has different features and API models. I'm not sure of the best approach, but suspect that we could implement custom hooks in the main plugin to support these additional driver plugins.
from documentation in testing bot section:
py.test --driver TestingBot --capability browserName firefox --capability browserName 39 --capability platform WIN8
correction should be
py.test --driver TestingBot --capability browserName firefox --capability version 39 --capability platform WIN8
It's cumbersome to always have to keep type --driver
and --driver-path
on the command line, or to have to add yet another wrapper script to fire up py.test with these options specified.
Is there a reason these couldn't be added as ini file options in addition to command line options?
Am curious about https://github.com/davehunt/pytest-selenium/blob/master/pytest_selenium/pytest_selenium.py#L46
It reads:
url = config.option.base_url or config.getini('selenium_base_url')
getini
is available for configuration - shouldn't it be all or nothing for consistency.selenium_base_url
and not base_url
?I applied pytest-selenium in our project, and found a strange issue, the UI test could sometimes failed without any reason, (maybe 1 failure in 10 times)
Environment is:
Firefox 45.0.2
pytest-selenium==1.3.1
selenium==2.53.6
Following is the error message:
.E
==================================== ERRORS ====================================
request = <SubRequest 'selenium' for <Function 'test_app_edit'>>
@pytest.fixture
def selenium(request):
"""Returns a WebDriver instance based on options and capabilities"""
driver_type = request.config.getoption('driver')
if driver_type is None:
raise pytest.UsageError('--driver must be specified')
driver_fixture = '{0}_driver'.format(driver_type.lower())
> driver = request.getfuncargvalue(driver_fixture)
/usr/lib/python2.7/site-packages/pytest_selenium/pytest_selenium.py:82:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/lib/python2.7/site-packages/pytest_selenium/drivers/firefox.py:46: in firefox_driver
return Firefox(**kwargs)
/usr/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py:80: in __init__
self.binary, timeout)
/usr/lib/python2.7/site-packages/selenium/webdriver/firefox/extension_connection.py:52: in __init__
self.binary.launch_browser(self.profile, timeout=timeout)
/usr/lib/python2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py:68: in launch_browser
self._wait_until_connectable(timeout=timeout)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <selenium.webdriver.firefox.firefox_binary.FirefoxBinary object at 0x2885450>
timeout = 30
def _wait_until_connectable(self, timeout=30):
"""Blocks until the extension is connectable in the firefox."""
count = 0
while not utils.is_connectable(self.profile.port):
if self.process.poll() is not None:
# Browser has exited
raise WebDriverException(
> "The browser appears to have exited "
"before we could connect. If you specified a log_file in "
"the FirefoxBinary constructor, check it for details.")
E WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.
/usr/lib/python2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py:99: WebDriverException
!!!!!!!!!!!!!!!!!!!! Interrupted: stopping after 1 failures !!!!!!!!!!!!!!!!!!!!
====================== 3 passed, 1 error in 39.18 seconds ======================
I can not tell how to reproduce that, that's what puzzled me also.
Given that it have error trace from pytest_selenium, I did not think it was from selenium itself. So open a issue here.
Thanks
I haven't used the Chrome support for a long time, and I suspect that we may need to improve the experience. At very least we should provide a decent guide to getting Chrome configured for running tests. We should also see if there's a way to get the Chrome tests running on Travis-CI.
It says on the installation page of the documentation that python 2.6 or 2.7 is required. It seems that the tests pass for quite a few python versions.
Hi,
First of all I would like to applogise, because I am not sure this issue is causing by selenium 3 itself or other components issue, please forgive me to spare your time when you reading this.
I have configure selenium 3 in grid setup, then I try to run my existing test script. But my browsers (FF/ Chrome) were unable to bypass self sign SSL certificate error.
However If I configure grid setup with selenium 2.53.1 and my test script just run well.
I have no idea what is the problem and how to fix it. Please share your though if possible, thank you.
Here is my environment setup:
Hi, recently, I have found issue in geckodriver when run with pytest-selenium.
However, geckodriver developer need trace-level log setting.
While run with pytest. how to set options like this below:
https://github.com/mozilla/geckodriver#log-object
{"moz:firefoxOptions": {"log": {"level": "trace"}}}
Which can help me to provide trace logs to geckodriver developers to debug issue.
Thanks
I guess this is a two part issue:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.