Skip to content

Instantly share code, notes, and snippets.

@bmulholland
Created June 18, 2012 22:20
Show Gist options
  • Save bmulholland/2951103 to your computer and use it in GitHub Desktop.
Save bmulholland/2951103 to your computer and use it in GitHub Desktop.
Python Webdriver add_cookie Requires Secure=False
========================================================================================= test session starts =========================================================================================
platform darwin -- Python 2.7.1 -- pytest-2.2.3 -- /usr/bin/python
collected 4 items
scripts/checkout_test.py:58: CheckoutTest.test_add_product
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB set_trace (IO-capturing turned off) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> /.../modules/pages/account/login_page.py(130)login()
-> self.driver.add_cookie({"name": "session", "value": sessionid, "path": "/", "secure": False})
(Pdb) c
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB set_trace (IO-capturing turned off) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> /.../modules/pages/account/login_page.py(132)login()
-> self.driver.add_cookie({"name": "session", "value": sessionid, "path": "/"})
(Pdb) c
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> traceback >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
self = <checkout_test.CheckoutTest testMethod=test_add_product>, method = <bound method CheckoutTest.test_add_product of <checkout_test.CheckoutTest testMethod=test_add_product>>
def setup_method(self, method):
super(CheckoutTest, self).setup_method(method)
self.driver.set_window_size(1280, 800)
# TODO: I have to load a page so that cookies can get set
# This can be sped up, however, by adding just a blank page
# (no css/js) on our domain instead of the home page
from pages.home_page import HomePage
(HomePage(self.driver)
.load()
.wait_for_load())
# Browserless login
from pages.account.login_page import LoginPage
LoginPage(self.driver).login(
"username",
"password",
> browserless=True
scripts/checkout_test.py:48:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <pages.account.login_page.LoginPage object at 0x108424090>, email = 'username', password = 'password', success = True, browserless = True
def login(self, email, password, success=True, browserless=False):
if not browserless:
self.login_email = email
self.login_password = password
self.driver.find_element_by_locator(
locators["login-submit"]).click()
if success:
from pages.home_page import HomePage
return HomePage(self.driver).wait_for_load()
else:
self.wait_for_available(locators["login-error-message"])
return self
else:
# Need to use the XMLHTTPRequest header so that kohana returns JSON
headers = {
"X-Requested-With": "XMLHttpRequest"
}
payload = {
"email": email,
"password": password,
"remember": "on"
}
r = requests.post(
("%s/user/sign-in/Customer"
% self.config.get("mysite", "base_url")),
data=payload,
headers=headers
)
# Now add the logged in session ID to the browser
sessionid = r.cookies["session"]
pytest.set_trace()
self.driver.add_cookie({"name": "session", "value": sessionid, "path": "/", "secure": False})
pytest.set_trace()
> self.driver.add_cookie({"name": "session", "value": sessionid, "path": "/"})
modules/pages/account/login_page.py:132:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <tailored.webdriver.WebDriver object at 0x1083b7f50>, cookie_dict = {'name': 'session', 'path': '/', 'value': 'fm1jqugsunlt1398lhadsl1ap2'}
def add_cookie(self, cookie_dict):
"""
Adds a cookie to your current session.
:Args:
- cookie_dict: A dictionary object, with required keys - "name" and "value";
optional keys - "path", "domain", "secure", "expiry"
Usage:
driver.add_cookie({'name' : 'foo', 'value' : 'bar'})
driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})
driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure':True})
"""
> self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
/Library/Python/2.7/site-packages/selenium-2.23.0-py2.7.egg/selenium/webdriver/remote/webdriver.py:613:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <tailored.webdriver.WebDriver object at 0x1083b7f50>, driver_command = 'addCookie'
params = {'cookie': {'name': 'session', 'path': '/', 'value': 'fm1jqugsunlt1398lhadsl1ap2'}, 'sessionId': u'1338244341561'}
def execute(self, driver_command, params=None):
"""
Sends a command to be executed by a command.CommandExecutor.
:Args:
- driver_command: The name of the command to execute as a string.
- params: A dictionary of named parameters to send with the command.
:Returns:
The command's JSON response loaded into a dictionary object.
"""
if not params:
params = {'sessionId': self.session_id}
elif 'sessionId' not in params:
params['sessionId'] = self.session_id
params = self._wrap_value(params)
response = self.command_executor.execute(driver_command, params)
if response:
> self.error_handler.check_response(response)
/Library/Python/2.7/site-packages/selenium-2.23.0-py2.7.egg/selenium/webdriver/remote/webdriver.py:155:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x1083b7610>
response = {u'class': u'org.openqa.selenium.remote.Response', u'hCode': 782001070, u'sessionId': u'1338244341561', u'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['status']
if status == ErrorCode.SUCCESS:
return
exception_class = ErrorInResponseException
if status == ErrorCode.NO_SUCH_ELEMENT:
exception_class = NoSuchElementException
elif status == ErrorCode.NO_SUCH_FRAME:
exception_class = NoSuchFrameException
elif status == ErrorCode.NO_SUCH_WINDOW:
exception_class = NoSuchWindowException
elif status == ErrorCode.STALE_ELEMENT_REFERENCE:
exception_class = StaleElementReferenceException
elif status == ErrorCode.ELEMENT_NOT_VISIBLE:
exception_class = ElementNotVisibleException
elif status == ErrorCode.INVALID_ELEMENT_STATE:
exception_class = InvalidElementStateException
elif status == ErrorCode.INVALID_SELECTOR \
or status == ErrorCode.INVALID_XPATH_SELECTOR \
or status == ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER:
exception_class = InvalidSelectiorException
elif status == ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
exception_class = ElementNotSelectableException
elif status == ErrorCode.INVALID_COOKIE_DOMAIN:
exception_class = WebDriverException
elif status == ErrorCode.UNABLE_TO_SET_COOKIE:
exception_class = WebDriverException
elif status == ErrorCode.TIMEOUT:
exception_class = TimeoutException
elif status == ErrorCode.SCRIPT_TIMEOUT:
exception_class = TimeoutException
elif status == ErrorCode.UNKNOWN_ERROR:
exception_class = WebDriverException
elif status == ErrorCode.NO_ALERT_OPEN:
exception_class = NoAlertPresentException
elif status == ErrorCode.IME_NOT_AVAILABLE:
exception_class = ImeNotAvailableException
elif status == ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
exception_class = ErrorCode.ImeActivationFailedException
else:
exception_class = WebDriverException
value = response['value']
if type(value) is str:
if exception_class == ErrorInResponseException:
raise exception_class(response, value)
raise exception_class(value)
message = ''
if 'message' in value:
message = value['message']
screen = None
if 'screen' in value:
screen = value['screen']
stacktrace = None
if 'stackTrace' in value and value['stackTrace']:
zeroeth = ''
try:
zeroeth = value['stackTrace'][0]
except:
pass
if zeroeth.has_key('methodName'):
stacktrace = "Method %s threw an error in %s" % \
(zeroeth['methodName'],
self._value_or_default(zeroeth, 'fileName', '[No file name]'))
if exception_class == ErrorInResponseException:
raise exception_class(response, message)
> raise exception_class(message, screen, stacktrace)
E WebDriverException: Message: None ; Stacktrace: Method createCookie threw an error in CookieHandler.java
/Library/Python/2.7/site-packages/selenium-2.23.0-py2.7.egg/selenium/webdriver/remote/errorhandler.py:147: WebDriverException
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> /Library/Python/2.7/site-packages/selenium-2.23.0-py2.7.egg/selenium/webdriver/remote/errorhandler.py(147)check_response()
-> raise exception_class(message, screen, stacktrace)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment