Last active
January 10, 2018 23:37
-
-
Save 7mp/8400868 to your computer and use it in GitHub Desktop.
Selenium driver extensions for PhantomJS and Django (and its admin)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Phantom JS test drivers for Django | |
Tips: | |
* to check a value of a (global) JS variable, one can use: | |
driver.execute_script('return <variable_name>') | |
""" | |
from django.core.urlresolvers import reverse | |
from selenium import webdriver | |
import urlparse | |
class DjangoPhantomJS(webdriver.PhantomJS): | |
""" | |
PhantomJS driver extended for the Django | |
""" | |
def __init__(self, *args, **kwargs): | |
""" | |
If not using the default testserver port, the following options can | |
be supplied: | |
* `django_host`: the IP address and the port, defaults to 127.0.0.1:8000 | |
""" | |
self.django_host = kwargs.pop('django_host', '127.0.0.1:8000') | |
super(DjangoPhantomJS, self).__init__(*args, **kwargs) | |
def get_reversed_url(self, *reverse_args, **reverse_kwargs): | |
"PhantomJS.get the url specified by Django's reverse" | |
url_path = reverse(*reverse_args, **reverse_kwargs) | |
# TODO: use urlparse for the host? | |
url_host = 'http://%s' % self.django_host | |
url = urlparse.urljoin(url_host, url_path) | |
return self.get(url) | |
class DjangoAdminPhantomJS(DjangoPhantomJS): | |
"A Selenium driver which automatically logs in to Django Admin" | |
def login(self, username, password): | |
"Log in to Django admin, assuming the default form is used" | |
self.get_reversed_url('admin:index') | |
username_field = self.find_element_by_id("id_username") | |
username_field.send_keys(username) | |
password_field = self.find_element_by_id("id_password") | |
password_field.send_keys(password) | |
# This could actually be any field | |
password_field.submit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment