Giter Club home page Giter Club logo

pytest-selenium's Introduction

pytest-selenium's People

Contributors

asottile avatar beyondevil avatar birdsarah avatar bobsilverberg avatar codingjoe avatar d3x avatar davehunt avatar delirious-lettuce avatar dosas avatar isaulv avatar jenselme avatar jlaska avatar jrbenny35 avatar muckt avatar nfk avatar nicoddemus avatar noamkush avatar philippselenium avatar pre-commit-ci[bot] avatar retornam avatar rohitanand1614 avatar ronnypfannschmidt avatar santiycr avatar sashakruglov avatar seandst avatar stephendonner avatar tltx avatar vaidik avatar wlach avatar zac-hd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytest-selenium's Issues

pytest-selenium can not work with Firefox geckodriver

As Firefox support geckodriver, as listed in
https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver

How to reproduce that

py.test --base-url http://<myapp-ip>:8081 --host selenium-host --port 4444  --driver Remote --capability browserName firefox  --capability marionette true mytest

The error looks like

  @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)

What's the best way for pytest selenium test in long operation objects

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

When used with Appium I can not add a screenshot of the report.html

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/

At the end I want to do exactly that:
Image of Report

Remove the default driver

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.

--firefox-preferences option is not working properly

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

UnboundLocalError: local variable 'log_types' referenced before assignment in 1.0b4

Hi,

I have upgraded pytest-selenium from 1.0b2 to 1.0b4. The error in command prompt I got is different between both.

1.0b2
1 0b2

1.0b4
1 0b4

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.

Allow plugins that provide proxies to override the proxy configuration

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.

INTERNALERROR: KeyError: 'startdir'

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.

Selenium plugin listed twice

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.

Fix deprecation warning

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

Question: Shorten the browserName command

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.

Clean up command line options

I'd like to revisit and clean up the existing command line options. Here are the current options, with some suggestions for improvements:

  • --baseurl - Rename to --base-url
  • --skipurlcheck - I think we should remove this. I believe it was added for testing sites that are not http(s) such as about:support, etc. I would be inclined to reimplement this as a protocol check in _verify_base_url
  • --host - leave this as it is
  • --port - leave this as it is
  • --driver - leave this as it is for now, but I'd like to have a local default - we could potentially determine which browsers are present and conveniently pick one. I don't think we should assume the user will have a Selenium server running
  • --capability - leave this as it is
  • --chromepath - rename to --driver-path
  • --firefoxpath - rename to --driver-path
  • --firefoxpref - rename to --firefox-pref
  • --profilepath rename to --firefox-profile
  • --extension rename to --browser-extension
  • --chromeopts - rename to repeatable --chrome-option argument
  • --operapath - rename to --driver-path
  • --browsername - remove and document using --capability for Grid, Sauce Labs, and BrowserStack
  • --browserver - remove and document using --capability for Grid, Sauce Labs, and BrowserStack
  • --platform - remove and document using --capability for Grid, Sauce Labs, and BrowserStack
  • --build - replace with environment variable (BUILD_ID in Jenkins, TRAVIS_BUILD_NUMBER in Travis, etc)
  • --untrusted - remove and revisit in the future if it's needed
  • --proxyhost - rename to --proxy-host
  • --proxyport - rename to --proxy-port
  • --eventlistener - rename to --event-listener
  • --sensitiveurl - rename to --sensitive-url and allow configuration from environment variable
  • --destructive - leave this as it is

Safari Support

Why isn't Safari supported, and might this change anytime soon?

Revisit command line capability support

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?

About the Selenium scenarios Testing

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()

Possible to only create a report on failure

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

Explicit wait is not wait the amount of time required

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?

Damaged screenshot files saved in HTML report assets folder on OSX

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.

Possible to skip _verify_base_url check?

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?

always have Element is not clickable at point

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)

Setting firefox-profile in conftest

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.

[Question] fail to get base_url from setup.cfg

Hi,

I have added "base_url" on setup.cfg. But when I run tests, the value from base_url is failed to inject to my script. But it is work fine if I supply "--base-url" on command line.

base url

Please help me to check if I have missing some thing. Thank you

Support for Chrome

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

Move sensitive configuration options into separate files

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.

Add a recipe to conda-forge

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.

Session scoped selenium fixture

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

Review Opera driver support

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.

Allow `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables

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.

base_url not working without @pytest.mark.nondestructive

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:

  • the test is skipped (not executed)

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.

Catch WebDriver exceptions when attempting to gather debug

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.

Review PhantomJS driver support

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.

start_driver fails randomly

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

Implement cloud providers as plugins

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.

Typo on documentation

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

Specify driver and driver-path in ini file

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?

pytest sometimes failed with The browser appears to have exited before we could connect[Random failure]

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

Review Chrome driver support

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.

Question: FF/ Chrome unable to bypass self sign SSL certificate

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:

  • FF 47.0.1
  • pytest 3.0.3
  • pytest-selenium 1.5.0
  • selenium 3.0.1

How to specify log level setting for geckodriver in pytest

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

Prevent firefox launching the "learnmore" page

I guess this is a two part issue:

  1. How can I prevent firefox from launching the learn more page every time it opens - it's wasting time and bandwidth on my tests
  2. Can we add this as a flag into pytest-selenium?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.