pax_global_header00006660000000000000000000000064125762471760014533gustar00rootroot0000000000000052 comment=eee6a36e9280e02413edd3d805912b092c6e89c5 Ghost.py-0.2.3/000077500000000000000000000000001257624717600132505ustar00rootroot00000000000000Ghost.py-0.2.3/.gitignore000066400000000000000000000001121257624717600152320ustar00rootroot00000000000000*.pyc env build __pycache__ Ghost.py.egg-info dist *.swp *.swo .tox .idea Ghost.py-0.2.3/.gitmodules000066400000000000000000000001141257624717600154210ustar00rootroot00000000000000[submodule "docs"] path = docs url = git@github.com:jeanphix/Ghost.py.git Ghost.py-0.2.3/MANIFEST.in000066400000000000000000000003431257624717600150060ustar00rootroot00000000000000include README.rst *.py include ghost/ghost.py include ghost/test.py include ghost/ext/django/test.py recursive-include docs * recursive-exclude docs *.pyc recursive-exclude docs *.pyo prune docs/_build prune docs/_themes/.git Ghost.py-0.2.3/README.rst000066400000000000000000000016641257624717600147460ustar00rootroot00000000000000ghost.py ======== .. image:: https://drone.io/github.com/jeanphix/Ghost.py/status.png :target: https://drone.io/github.com/jeanphix/Ghost.py/latest ghost.py is a webkit web client written in python: .. code:: python from ghost import Ghost ghost = Ghost() with ghost.start() as session: page, extra_resources = session.open("http://jeanphix.me") assert page.http_status == 200 and 'jeanphix' in page.content Installation ------------ ghost.py requires either PySide_ (preferred) or PyQt_ Qt_ bindings: .. code:: bash pip install pyside pip install ghost.py --pre OSX: .. code:: bash brew install qt mkvirtualenv foo pip install -U pip # make sure pip is current pip install PySide pyside_postinstall.py -install pip install Ghost.py .. _PySide: https://pyside.github.io/ .. _PyQt: http://www.riverbankcomputing.co.uk/software/pyqt/intro .. _Qt: http://qt-project.org/ Ghost.py-0.2.3/docs/000077500000000000000000000000001257624717600142005ustar00rootroot00000000000000Ghost.py-0.2.3/docs/conf.py000066400000000000000000000154601257624717600155050ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Logbook documentation build configuration file, created by # sphinx-quickstart on Fri Jul 23 16:54:49 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os from ghost import __version__ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.extend((os.path.abspath('.'), os.path.abspath('..'))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Ghost.py' copyright = u'2014, Jean-Philippe Serafin' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = __version__ # The full version, including alpha/beta/rc tags. release = __version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. #html_theme = 'sheet' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = { # 'nosidebar': True, # } # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = ['.'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = "Ghost.py" # A shorter title for the navigation bar. Default is the same as html_title. html_short_title = "Ghost.py " + release # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True html_add_permalinks = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Ghostdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). Ghost.py-0.2.3/docs/index.rst000066400000000000000000000002501257624717600160360ustar00rootroot00000000000000.. include:: ../README.rst API ============ .. module:: ghost Ghost ----- .. autoclass:: Ghost :members: Session ------- .. autoclass:: Session :members: Ghost.py-0.2.3/ghost/000077500000000000000000000000001257624717600143745ustar00rootroot00000000000000Ghost.py-0.2.3/ghost/__init__.py000066400000000000000000000002251257624717600165040ustar00rootroot00000000000000# -*- coding: utf-8 -*- from .ghost import ( Ghost, Error, Session, TimeoutError, __version__, ) from .test import GhostTestCase Ghost.py-0.2.3/ghost/bindings.py000066400000000000000000000031331257624717600165430ustar00rootroot00000000000000# -*- coding: utf-8 -*- import sys PY3 = sys.version > '3' if PY3: unicode = str long = int bindings = ["PySide", "PyQt4"] binding = None for name in bindings: try: binding = __import__(name) if name == 'PyQt4': import sip sip.setapi('QVariant', 2) except ImportError: continue break class LazyBinding(object): class __metaclass__(type): def __getattr__(self, name): return self.__class__ def __getattr__(self, name): return self.__class__ def _import(name): if binding is None: return LazyBinding() name = "%s.%s" % (binding.__name__, name) module = __import__(name) for n in name.split(".")[1:]: module = getattr(module, n) return module QtCore = _import("QtCore") QSize = QtCore.QSize QByteArray = QtCore.QByteArray QUrl = QtCore.QUrl QDateTime = QtCore.QDateTime QtCriticalMsg = QtCore.QtCriticalMsg QtDebugMsg = QtCore.QtDebugMsg QtFatalMsg = QtCore.QtFatalMsg QtWarningMsg = QtCore.QtWarningMsg qInstallMsgHandler = QtCore.qInstallMsgHandler QtGui = _import("QtGui") QApplication = QtGui.QApplication QImage = QtGui.QImage QPainter = QtGui.QPainter QPrinter = QtGui.QPrinter QRegion = QtGui.QRegion QtNetwork = _import("QtNetwork") QNetworkRequest = QtNetwork.QNetworkRequest QNetworkAccessManager = QtNetwork.QNetworkAccessManager QNetworkCookieJar = QtNetwork.QNetworkCookieJar QNetworkProxy = QtNetwork.QNetworkProxy QNetworkCookie = QtNetwork.QNetworkCookie QSslConfiguration = QtNetwork.QSslConfiguration QSsl = QtNetwork.QSsl QtWebKit = _import('QtWebKit') Ghost.py-0.2.3/ghost/ext/000077500000000000000000000000001257624717600151745ustar00rootroot00000000000000Ghost.py-0.2.3/ghost/ext/__init__.py000066400000000000000000000000001257624717600172730ustar00rootroot00000000000000Ghost.py-0.2.3/ghost/ext/django/000077500000000000000000000000001257624717600164365ustar00rootroot00000000000000Ghost.py-0.2.3/ghost/ext/django/__init__.py000066400000000000000000000000001257624717600205350ustar00rootroot00000000000000Ghost.py-0.2.3/ghost/ext/django/test.py000066400000000000000000000004241257624717600177670ustar00rootroot00000000000000# -*- coding: utf-8 -*- try: from django.test import LiveServerTestCase except ImportError: raise Exception("Ghost.py django extension requires django...") from ghost.test import BaseGhostTestCase class GhostTestCase(LiveServerTestCase, BaseGhostTestCase): pass Ghost.py-0.2.3/ghost/ghost.py000077500000000000000000001247041257624717600161050ustar00rootroot00000000000000# -*- coding: utf-8 -*- import sys import os import time import uuid import codecs import logging import subprocess import re from functools import wraps try: from cookielib import Cookie, LWPCookieJar except ImportError: from http.cookiejar import Cookie, LWPCookieJar from contextlib import contextmanager from .logger import configure from .bindings import ( binding, QtCore, QSize, QByteArray, QUrl, QDateTime, QtCriticalMsg, QtDebugMsg, QtFatalMsg, QtWarningMsg, qInstallMsgHandler, QApplication, QImage, QPainter, QPrinter, QRegion, QtNetwork, QNetworkRequest, QNetworkAccessManager, QNetworkCookieJar, QNetworkProxy, QNetworkCookie, QSslConfiguration, QSsl, QtWebKit, ) __version__ = "0.2.3" PY3 = sys.version > '3' if PY3: unicode = str long = int basestring = str default_user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 " +\ "(KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2" class Error(Exception): """Base class for Ghost exceptions.""" pass class TimeoutError(Error): """Raised when a request times out""" pass class QTMessageProxy(object): def __init__(self, logger): self.logger = logger def __call__(self, msgType, msg): levels = { QtDebugMsg: 'debug', QtWarningMsg: 'warn', QtCriticalMsg: 'critical', QtFatalMsg: 'fatal', } getattr(self.logger, levels[msgType])(msg) class GhostWebPage(QtWebKit.QWebPage): """Overrides QtWebKit.QWebPage in order to intercept some graphical behaviours like alert(), confirm(). Also intercepts client side console.log(). """ def __init__(self, app, session): self.session = session super(GhostWebPage, self).__init__() def chooseFile(self, frame, suggested_file=None): filename = self.session._upload_file self.session.logger.debug('Choosing file %s' % filename) return filename def javaScriptConsoleMessage(self, message, line, source): """Prints client console message in current output stream.""" super(GhostWebPage, self).javaScriptConsoleMessage( message, line, source, ) log_type = "warn" if "Error" in message else "info" getattr(self.session.logger, log_type)( "%s(%d): %s" % (source or '', line, message), ) def javaScriptAlert(self, frame, message): """Notifies session for alert, then pass.""" self.session._alert = message self.session.append_popup_message(message) self.session.logger.info("alert('%s')" % message) def _get_value(self, value): if callable(value): return value() return value def javaScriptConfirm(self, frame, message): """Checks if session is waiting for confirm, then returns the right value. """ if self.session._confirm_expected is None: raise Error( 'You must specified a value to confirm "%s"' % message, ) self.session.append_popup_message(message) value = self.session._confirm_expected self.session.logger.info("confirm('%s')" % message) return self._get_value(value) def javaScriptPrompt(self, frame, message, defaultValue, result=None): """Checks if ghost is waiting for prompt, then enters the right value. """ if self.session._prompt_expected is None: raise Error( 'You must specified a value for prompt "%s"' % message, ) self.session.append_popup_message(message) value = self.session._prompt_expected self.session.logger.info("prompt('%s')" % message) value = self._get_value(value) if value == '': self.session.logger.warn( "'%s' prompt filled with empty string" % message, ) if result is None: # PySide return True, value result.append(unicode(value)) return True def set_user_agent(self, user_agent): self.user_agent = user_agent def userAgentForUrl(self, url): return self.user_agent def can_load_page(func): """Decorator that specifies if user can expect page loading from this action. If expect_loading is set to True, ghost will wait for page_loaded event. """ @wraps(func) def wrapper(self, *args, **kwargs): expect_loading = kwargs.pop('expect_loading', False) if expect_loading: self.loaded = False func(self, *args, **kwargs) return self.wait_for_page_loaded( timeout=kwargs.pop('timeout', None)) return func(self, *args, **kwargs) return wrapper class HttpResource(object): """Represents an HTTP resource. """ def __init__(self, session, reply, content): self.session = session self.url = reply.url().toString() self.content = content try: self.content = unicode(content) except UnicodeDecodeError: self.content = content self.http_status = reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) self.session.logger.info( "Resource loaded: %s %s" % (self.url, self.http_status) ) self.headers = {} for header in reply.rawHeaderList(): try: self.headers[unicode(header)] = unicode( reply.rawHeader(header)) except UnicodeDecodeError: # it will lose the header value, # but at least not crash the whole process self.session.logger.error( "Invalid characters in header {0}={1}".format( header, reply.rawHeader(header), ) ) self._reply = reply def replyReadyRead(reply): if not hasattr(reply, 'data'): reply.data = '' reply.data += reply.peek(reply.bytesAvailable()) class NetworkAccessManager(QNetworkAccessManager): """Subclass QNetworkAccessManager to always cache the reply content :param exclude_regex: A regex use to determine wich url exclude when sending a request """ def __init__(self, exclude_regex=None, *args, **kwargs): self._regex = re.compile(exclude_regex) if exclude_regex else None super(self.__class__, self).__init__(*args, **kwargs) def createRequest(self, operation, request, data): if self._regex and self._regex.findall(str(request.url().toString())): return QNetworkAccessManager.createRequest( self, QNetworkAccessManager.GetOperation, QNetworkRequest(QUrl())) reply = QNetworkAccessManager.createRequest( self, operation, request, data ) reply.readyRead.connect(lambda reply=reply: replyReadyRead(reply)) time.sleep(0.001) return reply class Ghost(object): """`Ghost` manages a Qt application. :param log_level: The optional logging level. :param log_handler: The optional logging handler. :param plugin_path: Array with paths to plugin directories (default ['/usr/lib/mozilla/plugins']) :param defaults: The defaults arguments to pass to new child sessions. """ _app = None def __init__( self, log_level=logging.WARNING, log_handler=logging.StreamHandler(sys.stderr), plugin_path=['/usr/lib/mozilla/plugins', ], defaults=None, ): if not binding: raise Exception("Ghost.py requires PySide or PyQt4") self.logger = configure( 'ghost', "Ghost", log_level, log_handler, ) if ( sys.platform.startswith('linux') and 'DISPLAY' not in os.environ ): try: os.environ['DISPLAY'] = ':99' process = ['Xvfb', ':99', '-pixdepths', '32'] FNULL = open(os.devnull, 'w') self.xvfb = subprocess.Popen( process, stdout=FNULL, stderr=subprocess.STDOUT, ) except OSError: raise Error('Xvfb is required to a ghost run outside ' + 'an X instance') self.logger.info('Initializing QT application') Ghost._app = QApplication.instance() or QApplication(['ghost']) qInstallMsgHandler(QTMessageProxy( configure( 'qt', 'QT', log_level, log_handler, ) )) if plugin_path: for p in plugin_path: Ghost._app.addLibraryPath(p) self.defaults = defaults or dict() def exit(self): self._app.quit() if hasattr(self, 'xvfb'): self.xvfb.terminate() def start(self, **kwargs): """Starts a new `Session`.""" kwargs.update(self.defaults) return Session(self, **kwargs) def __del__(self): self.exit() class Session(object): """`Session` manages a QWebPage. :param ghost: The parent `Ghost` instance. :param user_agent: The default User-Agent header. :param wait_timeout: Maximum step duration in second. :param wait_callback: An optional callable that is periodically executed until Ghost stops waiting. :param log_level: The optional logging level. :param log_handler: The optional logging handler. :param display: A boolean that tells ghost to displays UI. :param viewport_size: A tuple that sets initial viewport size. :param ignore_ssl_errors: A boolean that forces ignore ssl errors. :param plugins_enabled: Enable plugins (like Flash). :param java_enabled: Enable Java JRE. :param download_images: Indicate if the browser should download images :param exclude: A regex use to determine which url exclude when sending a request """ _alert = None _confirm_expected = None _prompt_expected = None _upload_file = None _app = None def __init__( self, ghost, user_agent=default_user_agent, wait_timeout=8, wait_callback=None, display=False, viewport_size=(800, 600), ignore_ssl_errors=True, plugins_enabled=False, java_enabled=False, javascript_enabled=True, download_images=True, show_scrollbars=True, exclude=None, network_access_manager_class=NetworkAccessManager, web_page_class=GhostWebPage, ): self.ghost = ghost self.id = str(uuid.uuid4()) self.logger = configure( 'ghost.%s' % self.id, "Ghost<%s>" % self.id, ghost.logger.level, ) self.logger.info("Starting new session") self.http_resources = [] self.wait_timeout = wait_timeout self.wait_callback = wait_callback self.ignore_ssl_errors = ignore_ssl_errors self.loaded = True self.display = display self.popup_messages = [] self.page = web_page_class(self.ghost._app, self) if network_access_manager_class is not None: self.page.setNetworkAccessManager( network_access_manager_class(exclude_regex=exclude)) QtWebKit.QWebSettings.setMaximumPagesInCache(0) QtWebKit.QWebSettings.setObjectCacheCapacities(0, 0, 0) QtWebKit.QWebSettings.globalSettings().setAttribute( QtWebKit.QWebSettings.LocalStorageEnabled, True) self.page.setForwardUnsupportedContent(True) self.page.settings().setAttribute( QtWebKit.QWebSettings.AutoLoadImages, download_images) self.page.settings().setAttribute( QtWebKit.QWebSettings.PluginsEnabled, plugins_enabled) self.page.settings().setAttribute( QtWebKit.QWebSettings.JavaEnabled, java_enabled, ) self.page.settings().setAttribute( QtWebKit.QWebSettings.JavascriptEnabled, javascript_enabled) if not show_scrollbars: self.page.mainFrame().setScrollBarPolicy( QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff, ) self.page.mainFrame().setScrollBarPolicy( QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff, ) self.set_viewport_size(*viewport_size) # Page signals self.page.loadFinished.connect(self._page_loaded) self.page.loadStarted.connect(self._page_load_started) self.page.unsupportedContent.connect(self._unsupported_content) self.manager = self.page.networkAccessManager() self.manager.finished.connect(self._request_ended) self.manager.sslErrors.connect(self._on_manager_ssl_errors) # Cookie jar self.cookie_jar = QNetworkCookieJar() self.manager.setCookieJar(self.cookie_jar) # User Agent self.page.set_user_agent(user_agent) self.page.networkAccessManager().authenticationRequired\ .connect(self._authenticate) self.page.networkAccessManager().proxyAuthenticationRequired\ .connect(self._authenticate) self.main_frame = self.page.mainFrame() class GhostQWebView(QtWebKit.QWebView): def sizeHint(self): return QSize(*viewport_size) self.webview = GhostQWebView() if plugins_enabled: self.webview.settings().setAttribute( QtWebKit.QWebSettings.PluginsEnabled, True) if java_enabled: self.webview.settings().setAttribute( QtWebKit.QWebSettings.JavaEnabled, True) self.webview.setPage(self.page) if self.display: self.show() def frame(self, selector=None): """ Set main frame as current main frame's parent. :param frame: An optional name or index of the child to descend to. """ if isinstance(selector, basestring): for frame in self.main_frame.childFrames(): if frame.frameName() == selector: self.main_frame = frame return # frame not found so we throw an exception raise LookupError( "Child frame for name '%s' not found." % selector, ) if isinstance(selector, int): try: self.main_frame = self.main_frame.childFrames()[selector] return except IndexError: raise LookupError( "Child frame at index '%s' not found." % selector, ) # we can't ascend directly to parent frame because it might have been # deleted self.main_frame = self.page.mainFrame() @can_load_page def call(self, selector, method): """Call method on element matching given selector. :param selector: A CSS selector to the target element. :param method: The name of the method to call. :param expect_loading: Specifies if a page loading is expected. """ self.logger.debug('Calling `%s` method on `%s`' % (method, selector)) element = self.main_frame.findFirstElement(selector) return element.evaluateJavaScript('this[%s]();' % repr(method)) def capture( self, region=None, selector=None, format=None, ): """Returns snapshot as QImage. :param region: An optional tuple containing region as pixel coodinates. :param selector: A selector targeted the element to crop on. :param format: The output image format. """ if format is None: format = QImage.Format_ARGB32_Premultiplied self.main_frame.setScrollBarPolicy( QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff, ) self.main_frame.setScrollBarPolicy( QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff, ) frame_size = self.main_frame.contentsSize() max_size = 23170 * 23170 if frame_size.height() * frame_size.width() > max_size: self.logger.warn("Frame size is too large.") default_size = self.page.viewportSize() if default_size.height() * default_size.width() > max_size: return None else: self.page.setViewportSize(self.main_frame.contentsSize()) self.logger.info("Frame size -> " + str(self.page.viewportSize())) image = QImage(self.page.viewportSize(), format) painter = QPainter(image) if region is None and selector is not None: region = self.region_for_selector(selector) if region: x1, y1, x2, y2 = region w, h = (x2 - x1), (y2 - y1) reg = QRegion(x1, y1, w, h) self.main_frame.render(painter, reg) else: self.main_frame.render(painter) painter.end() if region: x1, y1, x2, y2 = region w, h = (x2 - x1), (y2 - y1) image = image.copy(x1, y1, w, h) return image def capture_to( self, path, region=None, selector=None, format=None, ): """Saves snapshot as image. :param path: The destination path. :param region: An optional tuple containing region as pixel coodinates. :param selector: A selector targeted the element to crop on. :param format: The output image format. """ if format is None: format = QImage.Format_ARGB32_Premultiplied self.capture(region=region, format=format, selector=selector).save(path) def print_to_pdf( self, path, paper_size=(8.5, 11.0), paper_margins=(0, 0, 0, 0), paper_units=None, zoom_factor=1.0, ): """Saves page as a pdf file. See qt4 QPrinter documentation for more detailed explanations of options. :param path: The destination path. :param paper_size: A 2-tuple indicating size of page to print to. :param paper_margins: A 4-tuple indicating size of each margin. :param paper_units: Units for pager_size, pager_margins. :param zoom_factor: Scale the output content. """ assert len(paper_size) == 2 assert len(paper_margins) == 4 if paper_units is None: paper_units = QPrinter.Inch printer = QPrinter(mode=QPrinter.ScreenResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPaperSize(QtCore.QSizeF(*paper_size), paper_units) printer.setPageMargins(*(paper_margins + (paper_units,))) if paper_margins != (0, 0, 0, 0): printer.setFullPage(True) printer.setOutputFileName(path) if self.webview is None: self.webview = QtWebKit.QWebView() self.webview.setPage(self.page) self.webview.setZoomFactor(zoom_factor) self.webview.print_(printer) @can_load_page def click(self, selector, btn=0): """Click the targeted element. :param selector: A CSS3 selector to targeted element. :param btn: The number of mouse button. 0 - left button, 1 - middle button, 2 - right button """ if not self.exists(selector): raise Error("Can't find element to click") return self.evaluate(""" (function () { var element = document.querySelector(%s); var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1, false, false, false, false, %s, element); return element.dispatchEvent(evt); })(); """ % (repr(selector), str(btn))) @contextmanager def confirm(self, confirm=True): """Statement that tells Ghost how to deal with javascript confirm(). :param confirm: A boolean or a callable to set confirmation. """ self._confirm_expected = confirm yield self._confirm_expected = None @property def content(self, to_unicode=True): """Returns current frame HTML as a string. :param to_unicode: Whether to convert html to unicode or not """ if to_unicode: return unicode(self.main_frame.toHtml()) else: return self.main_frame.toHtml() @property def cookies(self): """Returns all cookies.""" return self.cookie_jar.allCookies() def delete_cookies(self): """Deletes all cookies.""" self.cookie_jar.setAllCookies([]) def clear_alert_message(self): """Clears the alert message""" self._alert = None @can_load_page def evaluate(self, script): """Evaluates script in page frame. :param script: The script to evaluate. """ return ( self.main_frame.evaluateJavaScript("%s" % script), self._release_last_resources(), ) def evaluate_js_file(self, path, encoding='utf-8', **kwargs): """Evaluates javascript file at given path in current frame. Raises native IOException in case of invalid file. :param path: The path of the file. :param encoding: The file's encoding. """ with codecs.open(path, encoding=encoding) as f: return self.evaluate(f.read(), **kwargs) def exists(self, selector): """Checks if element exists for given selector. :param string: The element selector. """ return not self.main_frame.findFirstElement(selector).isNull() def exit(self): """Exits all Qt widgets.""" self.logger.info("Closing session") del self.webview del self.cookie_jar del self.manager del self.main_frame del self.page self.sleep() @can_load_page def fill(self, selector, values): """Fills a form with provided values. :param selector: A CSS selector to the target form to fill. :param values: A dict containing the values. """ if not self.exists(selector): raise Error("Can't find form") resources = [] for field in values: r, res = self.set_field_value( "%s [name=%s]" % (selector, repr(field)), values[field]) resources.extend(res) return True, resources @can_load_page def fire(self, selector, event): """Fire `event` on element at `selector` :param selector: A selector to target the element. :param event: The name of the event to trigger. """ self.logger.debug('Fire `%s` on `%s`' % (event, selector)) element = self.main_frame.findFirstElement(selector) return element.evaluateJavaScript(""" var event = document.createEvent("HTMLEvents"); event.initEvent('%s', true, true); this.dispatchEvent(event); """ % event) def global_exists(self, global_name): """Checks if javascript global exists. :param global_name: The name of the global. """ return self.evaluate( '!(typeof this[%s] === "undefined");' % repr(global_name) )[0] def hide(self): """Close the webview.""" try: self.webview.close() except: raise Error("no webview to close") def load_cookies(self, cookie_storage, keep_old=False): """load from cookielib's CookieJar or Set-Cookie3 format text file. :param cookie_storage: file location string on disk or CookieJar instance. :param keep_old: Don't reset, keep cookies not overridden. """ def toQtCookieJar(PyCookieJar, QtCookieJar): allCookies = QtCookieJar.allCookies() if keep_old else [] for pc in PyCookieJar: qc = toQtCookie(pc) allCookies.append(qc) QtCookieJar.setAllCookies(allCookies) def toQtCookie(PyCookie): qc = QNetworkCookie(PyCookie.name, PyCookie.value) qc.setSecure(PyCookie.secure) if PyCookie.path_specified: qc.setPath(PyCookie.path) if PyCookie.domain != "": qc.setDomain(PyCookie.domain) if PyCookie.expires and PyCookie.expires != 0: t = QDateTime() t.setTime_t(PyCookie.expires) qc.setExpirationDate(t) # not yet handled(maybe less useful): # py cookie.rest / QNetworkCookie.setHttpOnly() return qc if cookie_storage.__class__.__name__ == 'str': cj = LWPCookieJar(cookie_storage) cj.load() toQtCookieJar(cj, self.cookie_jar) elif cookie_storage.__class__.__name__.endswith('CookieJar'): toQtCookieJar(cookie_storage, self.cookie_jar) else: raise ValueError('unsupported cookie_storage type.') def open( self, address, method='get', headers={}, auth=None, body=None, default_popup_response=None, wait=True, timeout=None, client_certificate=None, encode_url=True, user_agent=None, ): """Opens a web page. :param address: The resource URL. :param method: The Http method. :param headers: An optional dict of extra request hearders. :param auth: An optional tuple of HTTP auth (username, password). :param body: An optional string containing a payload. :param default_popup_response: the default response for any confirm/ alert/prompt popup from the Javascript (replaces the need for the with blocks) :param wait: If set to True (which is the default), this method call waits for the page load to complete before returning. Otherwise, it just starts the page load task and it is the caller's responsibilty to wait for the load to finish by other means (e.g. by calling wait_for_page_loaded()). :param timeout: An optional timeout. :param client_certificate An optional dict with "certificate_path" and "key_path" both paths corresponding to the certificate and key files :param encode_url Set to true if the url have to be encoded :param user_agent An option user agent string. :return: Page resource, and all loaded resources, unless wait is False, in which case it returns None. """ self.logger.info('Opening %s' % address) body = body or QByteArray() try: method = getattr(QNetworkAccessManager, "%sOperation" % method.capitalize()) except AttributeError: raise Error("Invalid http method %s" % method) if user_agent is not None: self.page.set_user_agent(user_agent) if client_certificate: ssl_conf = QSslConfiguration.defaultConfiguration() if "certificate_path" in client_certificate: try: certificate = QtNetwork.QSslCertificate.fromPath( client_certificate["certificate_path"], QSsl.Pem, )[0] except IndexError: raise Error( "Can't find certicate in %s" % client_certificate["certificate_path"] ) ssl_conf.setLocalCertificate(certificate) if "key_path" in client_certificate: private_key = QtNetwork.QSslKey( open(client_certificate["key_path"]).read(), QSsl.Rsa, ) ssl_conf.setPrivateKey(private_key) QSslConfiguration.setDefaultConfiguration(ssl_conf) if encode_url: request = QNetworkRequest(QUrl(address)) else: request = QNetworkRequest(QUrl.fromEncoded(address)) request.CacheLoadControl(0) for header in headers: request.setRawHeader(header, headers[header]) self._auth = auth self._auth_attempt = 0 # Avoids reccursion self.main_frame.load(request, method, body) self.loaded = False if default_popup_response is not None: self._prompt_expected = default_popup_response self._confirm_expected = default_popup_response if wait: return self.wait_for_page_loaded(timeout=timeout) def scroll_to_anchor(self, anchor): self.main_frame.scrollToAnchor(anchor) @contextmanager def prompt(self, value=''): """Statement that tells Ghost how to deal with javascript prompt(). :param value: A string or a callable value to fill in prompt. """ self._prompt_expected = value yield self._prompt_expected = None def region_for_selector(self, selector): """Returns frame region for given selector as tuple. :param selector: The targeted element. """ geo = self.main_frame.findFirstElement(selector).geometry() try: region = (geo.left(), geo.top(), geo.right(), geo.bottom()) except: raise Error("can't get region for selector '%s'" % selector) return region def save_cookies(self, cookie_storage): """Save to cookielib's CookieJar or Set-Cookie3 format text file. :param cookie_storage: file location string or CookieJar instance. """ def toPyCookieJar(QtCookieJar, PyCookieJar): for c in QtCookieJar.allCookies(): PyCookieJar.set_cookie(toPyCookie(c)) def toPyCookie(QtCookie): port = None port_specified = False secure = QtCookie.isSecure() name = str(QtCookie.name()) value = str(QtCookie.value()) v = str(QtCookie.path()) path_specified = bool(v != "") path = v if path_specified else None v = str(QtCookie.domain()) domain_specified = bool(v != "") domain = v if domain_specified: domain_initial_dot = v.startswith('.') else: domain_initial_dot = None v = long(QtCookie.expirationDate().toTime_t()) # Long type boundary on 32bit platfroms; avoid ValueError expires = 2147483647 if v > 2147483647 else v rest = {} discard = False return Cookie( 0, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, None, None, rest, ) if cookie_storage.__class__.__name__ == 'str': cj = LWPCookieJar(cookie_storage) toPyCookieJar(self.cookie_jar, cj) cj.save() elif cookie_storage.__class__.__name__.endswith('CookieJar'): toPyCookieJar(self.cookie_jar, cookie_storage) else: raise ValueError('unsupported cookie_storage type.') @can_load_page def set_field_value(self, selector, value, blur=True): """Sets the value of the field matched by given selector. :param selector: A CSS selector that target the field. :param value: The value to fill in. :param blur: An optional boolean that force blur when filled in. """ self.logger.debug('Setting value "%s" for "%s"' % (value, selector)) def _set_checkbox_value(el, value): el.setFocus() if value is True: el.setAttribute('checked', 'checked') else: el.removeAttribute('checked') def _set_checkboxes_value(els, value): for el in els: if el.attribute('value') == value: _set_checkbox_value(el, True) else: _set_checkbox_value(el, False) def _set_radio_value(els, value): for el in els: if el.attribute('value') == value: el.setFocus() el.setAttribute('checked', 'checked') def _set_text_value(el, value): el.setFocus() el.setAttribute('value', value) def _set_select_value(el, value): el.setFocus() index = 0 for option in el.findAll('option'): if option.attribute('value') == value: option.evaluateJavaScript('this.selected = true;') el.evaluateJavaScript('this.selectedIndex = %d;' % index) break index += 1 def _set_textarea_value(el, value): el.setFocus() el.setPlainText(value) res, ressources = None, [] element = self.main_frame.findFirstElement(selector) if element.isNull(): raise Error('can\'t find element for %s"' % selector) tag_name = str(element.tagName()).lower() if tag_name == "select": _set_select_value(element, value) elif tag_name == "textarea": _set_textarea_value(element, value) elif tag_name == "input": type_ = str(element.attribute('type')).lower() if type_ in [ "color", "date", "datetime", "datetime-local", "email", "hidden", "month", "number", "password", "range", "search", "tel", "text", "time", "url", "week", "", ]: _set_text_value(element, value) elif type_ == "checkbox": els = self.main_frame.findAllElements(selector) if els.count() > 1: _set_checkboxes_value(els, value) else: _set_checkbox_value(element, value) elif type_ == "radio": _set_radio_value( self.main_frame.findAllElements(selector), value, ) elif type_ == "file": self._upload_file = value res, resources = self.click(selector) self._upload_file = None else: raise Error('unsupported field tag') for event in ['input', 'change']: self.fire(selector, event) if blur: self.call(selector, 'blur') return res, ressources def set_proxy( self, type_, host='localhost', port=8888, user='', password='', ): """Set up proxy for FURTHER connections. :param type_: proxy type to use: \ none/default/socks5/https/http. :param host: proxy server ip or host name. :param port: proxy port. """ _types = { 'default': QNetworkProxy.DefaultProxy, 'none': QNetworkProxy.NoProxy, 'socks5': QNetworkProxy.Socks5Proxy, 'https': QNetworkProxy.HttpProxy, 'http': QNetworkProxy.HttpCachingProxy } if type_ is None: type_ = 'none' type_ = type_.lower() if type_ in ['none', 'default']: self.manager.setProxy(QNetworkProxy(_types[type_])) return elif type_ in _types: proxy = QNetworkProxy( _types[type_], hostName=host, port=port, user=user, password=password, ) self.manager.setProxy(proxy) else: raise ValueError( 'Unsupported proxy type: %s' % type_ + '\nsupported types are: none/socks5/http/https/default', ) def set_viewport_size(self, width, height): """Sets the page viewport size. :param width: An integer that sets width pixel count. :param height: An integer that sets height pixel count. """ self.page.setViewportSize(QSize(width, height)) def append_popup_message(self, message): self.popup_messages.append(unicode(message)) def show(self): """Show current page inside a QWebView. """ self.logger.debug('Showing webview') self.webview.show() self.sleep() def sleep(self, value=0.1): started_at = time.time() while time.time() <= (started_at + value): time.sleep(0.01) self.ghost._app.processEvents() def wait_for(self, condition, timeout_message, timeout=None): """Waits until condition is True. :param condition: A callable that returns the condition. :param timeout_message: The exception message on timeout. :param timeout: An optional timeout. """ timeout = self.wait_timeout if timeout is None else timeout started_at = time.time() while not condition(): if time.time() > (started_at + timeout): raise TimeoutError(timeout_message) self.sleep() if self.wait_callback is not None: self.wait_callback() def wait_for_alert(self, timeout=None): """Waits for main frame alert(). :param timeout: An optional timeout. """ self.wait_for(lambda: self._alert is not None, 'User has not been alerted.', timeout) msg = self._alert self._alert = None return msg, self._release_last_resources() def wait_for_page_loaded(self, timeout=None): """Waits until page is loaded, assumed that a page as been requested. :param timeout: An optional timeout. """ self.wait_for(lambda: self.loaded, 'Unable to load requested page', timeout) resources = self._release_last_resources() page = None url = self.main_frame.url().toString() url_without_hash = url.split("#")[0] for resource in resources: if url == resource.url or url_without_hash == resource.url: page = resource self.logger.info('Page loaded %s' % url) return page, resources def wait_for_selector(self, selector, timeout=None): """Waits until selector match an element on the frame. :param selector: The selector to wait for. :param timeout: An optional timeout. """ self.wait_for( lambda: self.exists(selector), 'Can\'t find element matching "%s"' % selector, timeout, ) return True, self._release_last_resources() def wait_while_selector(self, selector, timeout=None): """Waits until the selector no longer matches an element on the frame. :param selector: The selector to wait for. :param timeout: An optional timeout. """ self.wait_for( lambda: not self.exists(selector), 'Element matching "%s" is still available' % selector, timeout, ) return True, self._release_last_resources() def wait_for_text(self, text, timeout=None): """Waits until given text appear on main frame. :param text: The text to wait for. :param timeout: An optional timeout. """ self.wait_for( lambda: text in self.content, 'Can\'t find "%s" in current frame' % text, timeout, ) return True, self._release_last_resources() def _authenticate(self, mix, authenticator): """Called back on basic / proxy http auth. :param mix: The QNetworkReply or QNetworkProxy object. :param authenticator: The QAuthenticator object. """ if self._auth is not None and self._auth_attempt == 0: username, password = self._auth authenticator.setUser(username) authenticator.setPassword(password) self._auth_attempt += 1 def _page_loaded(self): """Called back when page is loaded. """ self.loaded = True self.sleep() def _page_load_started(self): """Called back when page load started. """ self.loaded = False def _release_last_resources(self): """Releases last loaded resources. :return: The released resources. """ last_resources = self.http_resources self.http_resources = [] return last_resources def _request_ended(self, reply): """Adds an HttpResource object to http_resources. :param reply: The QNetworkReply object. """ if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute): self.logger.debug("[%s] bytesAvailable()= %s" % ( str(reply.url()), reply.bytesAvailable() )) try: content = reply.data except AttributeError: content = reply.readAll() self.http_resources.append(HttpResource( self, reply, content=content, )) def _unsupported_content(self, reply): self.logger.info("Unsupported content %s" % ( str(reply.url()), )) reply.readyRead.connect( lambda reply=reply: self._reply_download_content(reply)) def _reply_download_content(self, reply): """Adds an HttpResource object to http_resources with unsupported content. :param reply: The QNetworkReply object. """ if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute): self.http_resources.append(HttpResource( self, reply, reply.readAll(), )) def _on_manager_ssl_errors(self, reply, errors): url = unicode(reply.url().toString()) if self.ignore_ssl_errors: reply.ignoreSslErrors() else: self.logger.warn('SSL certificate error: %s' % url) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.exit() Ghost.py-0.2.3/ghost/logger.py000066400000000000000000000021531257624717600162260ustar00rootroot00000000000000# -*- coding: utf-8 -*- from datetime import datetime from logging import ( Filter, Formatter, getLogger, ) class SenderFilter(Filter): def filter(self, record): record.sender = self.sender return True class MillisecFormatter(Formatter): converter = datetime.fromtimestamp def formatTime(self, record, datefmt=None): ct = self.converter(record.created) if datefmt is not None: s = ct.strftime(datefmt) else: t = ct.strftime("%Y-%m-%dT%H:%M:%S") s = "%s.%03dZ" % (t, record.msecs) return s def configure(name, sender, level, handler=None): logger = getLogger(name) # Add `ghost_id` to formater ghost_filter = SenderFilter() ghost_filter.sender = sender logger.addFilter(ghost_filter) # Set the level logger.setLevel(level) # Configure handler formater formatter = MillisecFormatter( fmt='%(asctime)s [%(levelname)-8s] %(sender)s: %(message)s', ) if handler is not None: handler.setFormatter(formatter) logger.addHandler(handler) return logger Ghost.py-0.2.3/ghost/test.py000066400000000000000000000053701257624717600157320ustar00rootroot00000000000000# -*- coding: utf-8 -*- import threading import logging import time from unittest import TestCase from wsgiref.simple_server import make_server from ghost import Ghost class ServerThread(threading.Thread): """Starts given WSGI application. :param app: The WSGI application to run. :param port: The port to run on. """ def __init__(self, app, port=5000): self.app = app self.port = port super(ServerThread, self).__init__() def run(self): self.http_server = make_server('', self.port, self.app) self.http_server.serve_forever() def join(self, timeout=None): if hasattr(self, 'http_server'): self.http_server.shutdown() del self.http_server class BaseGhostTestCase(TestCase): display = False wait_timeout = 5 viewport_size = (800, 600) log_level = logging.DEBUG def __new__(cls, *args, **kwargs): """Creates Ghost instance.""" if not hasattr(cls, 'ghost'): cls.ghost = Ghost( log_level=cls.log_level, defaults=dict( display=cls.display, viewport_size=cls.viewport_size, wait_timeout=cls.wait_timeout, ) ) return super(BaseGhostTestCase, cls).__new__(cls) def __call__(self, result=None): """Does the required setup, doing it here means you don't have to call super.setUp in subclasses. """ self._pre_setup() super(BaseGhostTestCase, self).__call__(result) self._post_teardown() def _post_teardown(self): """Deletes ghost cookies and hide UI if needed.""" self.session.exit() def _pre_setup(self): """Shows UI if needed. """ self.session = self.ghost.start() if self.display: self.session.show() class GhostTestCase(BaseGhostTestCase): """TestCase that provides a ghost instance and manage an HTTPServer running a WSGI application. """ server_class = ServerThread port = 5000 def create_app(self): """Returns your WSGI application for testing. """ raise NotImplementedError @classmethod def tearDownClass(cls): """Stops HTTPServer instance.""" cls.server_thread.join() super(GhostTestCase, cls).tearDownClass() @classmethod def setUpClass(cls): """Starts HTTPServer instance from WSGI application. """ cls.server_thread = cls.server_class(cls.create_app(), cls.port) cls.server_thread.daemon = True cls.server_thread.start() while not hasattr(cls.server_thread, 'http_server'): time.sleep(0.01) super(GhostTestCase, cls).setUpClass() Ghost.py-0.2.3/setup.cfg000066400000000000000000000001661257624717600150740ustar00rootroot00000000000000[build_sphinx] source-dir = docs/ build-dir = docs/build all_files = 1 [upload_sphinx] upload-dir = docs/build/htmlGhost.py-0.2.3/setup.py000066400000000000000000000017241257624717600147660ustar00rootroot00000000000000""" Ghost.py -------- Webkit based webclient. """ from setuptools import setup, find_packages from ghost import __version__ setup( name='Ghost.py', version=__version__, url='https://github.com/jeanphix/Ghost.py', license='mit', author='Jean-Philippe Serafin', author_email='serafinjp@gmail.com', description='Webkit based webclient.', long_description=__doc__, data_files=[('ghost', ['README.rst',])], packages=find_packages(), include_package_data=True, zip_safe=False, platforms='any', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], ) Ghost.py-0.2.3/tests/000077500000000000000000000000001257624717600144125ustar00rootroot00000000000000Ghost.py-0.2.3/tests/__init__.py000066400000000000000000000000001257624717600165110ustar00rootroot00000000000000Ghost.py-0.2.3/tests/app.py000066400000000000000000000077241257624717600155560ustar00rootroot00000000000000# -*- coding: utf-8 -*- import sys import os from flask import ( abort, flash, Flask, jsonify, make_response, redirect, render_template, request, Response, url_for, ) from werkzeug.datastructures import Headers PY3 = sys.version > '3' app = Flask(__name__) app.config['CSRF_ENABLED'] = False app.config['SECRET_KEY'] = 'asecret' @app.route('/', methods=['get', 'post']) def home(): if request.method == 'POST': flash('Form successfully sent.') file = request.files.get('simple-file') if file is not None: file.save(os.path.join( os.path.dirname(__file__), "uploaded_%s" % file.filename )) return redirect(url_for('home')) return render_template('home.html') @app.route('/echo/') def echo(arg): return render_template('echo.html', arg=arg) @app.route('/no-cache') def no_cache(): response = make_response("No cache for me.", 200) response.headers['Cache-Control'] = ( 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0' ) return response @app.route('/cookie') def cookie(): resp = make_response('Response text') resp.set_cookie('mycookies', 'mycookie value') return resp @app.route('/set/cookie') def set_cookie(): resp = make_response('Response text') resp.set_cookie('_path', value='/get/', path='/get/') resp.set_cookie('_path_fail', value='/set/', path='/set/') resp.set_cookie('_domain', value='127.0.0.1') resp.set_cookie('_secure_fail', value='sslonly', secure=True) resp.set_cookie('_expires', value='2147483647', expires=2147483647) return resp @app.route('/get/cookie') def get_cookie(): cookies = { '_expires': '2147483647', '_domain': '127.0.0.1', '_path': '/get/', } # make sure only what we expect is received. if cookies != request.cookies: return make_response('FAIL') # print request.cookies else: return make_response('OK') @app.route('/protected') def protected(): return abort(403) @app.route('/settimeout') def settimeout(): return render_template('settimeout.html') @app.route('/items.json') def items(): return jsonify(items=['second item', 'third item']) def _check_auth(username, password): return username == 'admin' and password == 'secret' @app.route('/basic-auth') def basic_auth(): auth = request.authorization if auth is None or not _check_auth(auth.username, auth.password): return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) return '

successfully authenticated

' @app.route('/send-file') def send_file(): h = Headers() h.add('Content-type', 'application/octet-stream', charset='utf8') h.add('Content-disposition', 'attachment', filename='name.tar.gz') file_path = os.path.join(os.path.dirname(__file__), 'static', 'foo.tar.gz') if PY3: f = open(file_path, 'r', encoding='latin-1') else: f = open(file_path, 'r') return Response(f, headers=h) @app.route('/url-hash') def url_hash(): return render_template('url_hash.html') @app.route('/url-hash-header') def url_hash_header(): response = make_response("Redirecting.", 302) response.headers['Location'] = url_for('echo', arg='Welcome') + "#/" return response @app.route('/many-assets') def many_assets(): return render_template( 'many_assets.html', css=['css%s' % i for i in range(0, 5)], js=['js%s' % i for i in range(0, 5)] ) @app.route('/js/.js') def js_assets(name=None): return 'var foo = "%s";' % name @app.route('/css/.css') def css_assets(name=None): return 'P.%s { color: red; };' % name @app.route('/dump') def dump(): return jsonify(dict(headers=dict(request.headers))) if __name__ == '__main__': app.run() Ghost.py-0.2.3/tests/ghost000077700000000000000000000000001257624717600170152../ghost/ustar00rootroot00000000000000Ghost.py-0.2.3/tests/requirements.txt000066400000000000000000000000061257624717600176720ustar00rootroot00000000000000Flask Ghost.py-0.2.3/tests/run.py000077500000000000000000000411201257624717600155710ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import json import logging import unittest try: import cookielib except ImportError: from http import cookiejar as cookielib from app import app from ghost import GhostTestCase from ghost.ghost import default_user_agent PY3 = sys.version > '3' PORT = 5000 base_url = 'http://localhost:%s/' % PORT class GhostTest(GhostTestCase): port = PORT display = False log_level = logging.INFO @classmethod def create_app(cls): return app def test_open(self): page, resources = self.session.open(base_url) self.assertEqual(page.url, base_url) self.assertTrue("Ghost.py" in self.session.content) def test_open_page_with_no_cache_headers(self): page, resources = self.session.open("%sno-cache" % base_url) self.assertIsNotNone(page.content) self.assertIn("cache for me", page.content) def test_open_403(self): page, resources = self.session.open("%sprotected" % base_url) self.assertEqual(resources[0].http_status, 403) def test_open_404(self): page, resources = self.session.open("%s404" % base_url) self.assertEqual(page.http_status, 404) def test_evaluate(self): self.session.open(base_url) self.assertEqual(self.session.evaluate("x='ghost'; x;")[0], 'ghost') def test_extra_resource_content(self): page, resources = self.session.open(base_url) self.assertIn('globals alert', resources[4].content) def test_extra_resource_binaries(self): page, resources = self.session.open(base_url) self.assertEqual( resources[5].content.__class__.__name__, 'QByteArray', ) def test_wait_for_selector(self): page, resources = self.session.open(base_url) success, resources = self.session.click("#update-list-button") success, resources = self.session\ .wait_for_selector("#list li:nth-child(2)") self.assertEqual(resources[0].url, "%sitems.json" % base_url) def test_sleep(self): page, resources = self.session.open("%s" % base_url) result, _ = self.session.evaluate("window.result") self.assertEqual(result, False) self.session.sleep(4) result, _ = self.session.evaluate("window.result") self.assertEqual(result, True) def test_wait_for_text(self): page, resources = self.session.open(base_url) self.session.click("#update-list-button") success, resources = self.session.wait_for_text("second item") def test_wait_for_timeout(self): self.session.open("%s" % base_url) self.assertRaises(Exception, self.session.wait_for_text, "undefined") def test_fill(self): self.session.open(base_url) values = { 'text': 'Here is a sample text.', 'email': 'my@awesome.email', 'textarea': 'Here is a sample text.\nWith several lines.', 'checkbox': True, 'select': 'two', "radio": "first choice" } self.session.fill('form', values) for field in ['text', 'email', 'textarea']: value, resssources = self.session\ .evaluate('document.getElementById("%s").value' % field) self.assertEqual(value, values[field]) value, resources = self.session.evaluate( 'document.getElementById("checkbox").checked') self.assertEqual(value, True) value, resources = self.session.evaluate( "document.querySelector('option[value=two]').selected;") self.assertTrue(value) value, resources = self.session.evaluate( 'document.getElementById("radio-first").checked') self.assertEqual(value, True) value, resources = self.session.evaluate( 'document.getElementById("radio-second").checked') self.assertEqual(value, False) def test_form_submission(self): self.session.open(base_url) values = { 'text': 'Here is a sample text.', } self.session.fill('form', values) page, resources = self.session.call( 'form', 'submit', expect_loading=True, ) self.assertIn('Form successfully sent.', self.session.content) def test_global_exists(self): self.session.open("%s" % base_url) self.assertTrue(self.session.global_exists('myGlobal')) def test_resource_headers(self): page, resources = self.session.open(base_url) self.assertEqual( page.headers['Content-Type'], 'text/html; charset=utf-8', ) def test_click_link(self): page, resources = self.session.open(base_url) page, resources = self.session.click('a', expect_loading=True) self.assertEqual(page.url, "%secho/link" % base_url) def test_cookies(self): self.session.open("%scookie" % base_url) self.assertEqual(len(self.session.cookies), 1) def test_delete_cookies(self): self.session.open("%scookie" % base_url) self.session.delete_cookies() self.assertEqual(len(self.session.cookies), 0) def test_save_load_cookies(self): self.session.delete_cookies() self.session.open("%sset/cookie" % base_url) self.session.save_cookies('testcookie.txt') self.session.delete_cookies() self.session.load_cookies('testcookie.txt') self.session.open("%sget/cookie" % base_url) self.assertTrue('OK' in self.session.content) def test_load_cookies_expire_is_none(self): self.session.delete_cookies() jar = cookielib.CookieJar() cookie = cookielib.Cookie(version=0, name='Name', value='1', port=None, port_specified=False, domain='www.example.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False) jar.set_cookie(cookie) self.session.load_cookies(jar) def test_wait_for_alert(self): self.session.open(base_url) self.session.click('#alert-button') msg, resources = self.session.wait_for_alert() self.assertEqual(msg, 'this is an alert') def test_confirm(self): self.session.open(base_url) with self.session.confirm(): self.session.click('#confirm-button') msg, resources = self.session.wait_for_alert() self.assertEqual(msg, 'you confirmed!') def test_no_confirm(self): self.session.open(base_url) with self.session.confirm(False): self.session.click('#confirm-button') msg, resources = self.session.wait_for_alert() self.assertEqual(msg, 'you denied!') def test_confirm_callable(self): self.session.open(base_url) with self.session.confirm(lambda: False): self.session.click('#confirm-button') msg, resources = self.session.wait_for_alert() self.assertEqual(msg, 'you denied!') def test_prompt(self): self.session.open(base_url) with self.session.prompt('my value'): self.session.click('#prompt-button') value, resources = self.session.evaluate('promptValue') self.assertEqual(value, 'my value') def test_prompt_callable(self): self.session.open(base_url) with self.session.prompt(lambda: 'another value'): self.session.click('#prompt-button') value, resources = self.session.evaluate('promptValue') self.assertEqual(value, 'another value') def test_popup_messages_collection(self): self.session.open(base_url, default_popup_response=True) self.session.click('#confirm-button') self.assertIn('this is a confirm', self.session.popup_messages) self.session.click('#prompt-button') self.assertIn('Prompt ?', self.session.popup_messages) self.session.click('#alert-button') self.assertIn('this is an alert', self.session.popup_messages) def test_prompt_default_value_true(self): self.session.open(base_url, default_popup_response=True) self.session.click('#confirm-button') msg, resources = self.session.wait_for_alert() self.assertEqual(msg, 'you confirmed!') def test_prompt_default_value_false(self): self.session.open(base_url, default_popup_response=False) self.session.click('#confirm-button') msg, resources = self.session.wait_for_alert() self.assertEqual(msg, 'you denied!') def test_capture_to(self): self.session.open(base_url) self.session.capture_to('test.png') self.assertTrue(os.path.isfile('test.png')) os.remove('test.png') def test_region_for_selector(self): self.session.open(base_url) x1, y1, x2, y2 = self.session.region_for_selector('h1') self.assertEqual(x1, 30) self.assertEqual(y1, 20) self.assertEqual(x2, 329) self.assertEqual(y2, 59) def test_capture_selector_to(self): self.session.open(base_url) self.session.capture_to('test.png', selector='h1') self.assertTrue(os.path.isfile('test.png')) os.remove('test.png') def test_set_field_value_checkbox_true(self): self.session.open(base_url) self.session.set_field_value('[name=checkbox]', True) value, resssources = self.session.evaluate( 'document.getElementById("checkbox").checked') self.assertEqual(value, True) def test_set_field_value_checkbox_false(self): self.session.open(base_url) self.session.set_field_value('[name=checkbox]', False) value, resssources = self.session.evaluate( 'document.getElementById("checkbox").checked') self.assertEqual(value, False) def test_set_field_value_checkbox_multiple(self): self.session.open(base_url) self.session.set_field_value( '[name=multiple-checkbox]', 'second choice', ) value, resources = self.session.evaluate( 'document.getElementById("multiple-checkbox-first").checked') self.assertEqual(value, False) value, resources = self.session.evaluate( 'document.getElementById("multiple-checkbox-second").checked') self.assertEqual(value, True) def test_set_field_value_email(self): expected = 'my@awesome.email' self.session.open(base_url) self.session.set_field_value('[name=email]', expected) value, resssources = self.session\ .evaluate('document.getElementById("email").value') self.assertEqual(value, expected) def test_set_field_value_text(self): expected = 'sample text' self.session.open(base_url) self.session.set_field_value('[name=text]', expected) value, resssources = self.session\ .evaluate('document.getElementById("text").value') self.assertEqual(value, expected) def test_set_field_value_radio(self): self.session.open(base_url) self.session.set_field_value('[name=radio]', 'first choice') value, resources = self.session.evaluate( 'document.getElementById("radio-first").checked') self.assertEqual(value, True) value, resources = self.session.evaluate( 'document.getElementById("radio-second").checked') self.assertEqual(value, False) def test_set_field_value_textarea(self): expected = 'sample text\nanother line' self.session.open(base_url) self.session.set_field_value('[name=textarea]', expected) value, resssources = self.session\ .evaluate('document.getElementById("textarea").value') self.assertEqual(value, expected) def test_set_field_value_select(self): self.session.open(base_url) self.session.set_field_value('[name=select]', 'two') value, resources = self.session.evaluate( "document.querySelector('option[value=two]').selected;") self.assertTrue(value) value, resources = self.session.evaluate( "document.querySelector('option[value=one]').selected;") self.assertFalse(value) def test_set_field_value_simple_file_field(self): self.session.open(base_url) self.session.set_field_value( '[name=simple-file]', os.path.join(os.path.dirname(__file__), 'static', 'blackhat.jpg'), ) page, resources = self.session.call( 'form', 'submit', expect_loading=True, ) file_path = os.path.join( os.path.dirname(__file__), 'uploaded_blackhat.jpg') self.assertTrue(os.path.isfile(file_path)) os.remove(file_path) def test_basic_http_auth_success(self): page, resources = self.session.open( "%sbasic-auth" % base_url, auth=('admin', 'secret'), ) self.assertEqual(page.http_status, 200) def test_basic_http_auth_error(self): page, resources = self.session.open( "%sbasic-auth" % base_url, auth=('admin', 'wrongsecret'), ) self.assertEqual(page.http_status, 401) def test_unsupported_content(self): page, resources = self.session.open("%ssend-file" % base_url) file_path = os.path.join( os.path.dirname(__file__), 'static', 'foo.tar.gz', ) if PY3: f = open(file_path, 'r', encoding='latin-1') else: f = open(file_path, 'r') foo = f.read(1024) f.close() self.assertEqual(resources[0].content, foo) def test_url_with_hash(self): page, resources = self.session.open(base_url) self.session.evaluate('document.location.hash = "test";') self.assertIsNotNone(page) self.assertTrue("Ghost.py" in self.session.content) def test_url_with_hash_header(self): page, resources = self.session.open("%surl-hash-header" % base_url) self.assertIsNotNone(page) self.assertTrue("Welcome" in self.session.content) def test_many_assets(self): page, resources = self.session.open("%smany-assets" % base_url) page, resources = self.session.open("%smany-assets" % base_url) def test_frame_ascend(self): session = self.session session.open(base_url) session.frame('first-frame') self.assertIn('frame 1', session.content) self.assertNotIn('Ghost.py', session.content) session.frame() self.assertNotIn('frame 1', session.content) self.assertIn('Ghost.py', session.content) def test_frame_descend_by_name(self): session = self.session session.open(base_url) self.assertNotIn('frame 1', session.content) session.frame('first-frame') self.assertIn('frame 1', session.content) def test_frame_descend_by_name_invalid(self): session = self.session session.open(base_url) self.assertRaises(LookupError, session.frame, 'third-frame') def test_frame_descend_by_index(self): session = self.session session.open(base_url) self.assertNotIn('frame 2', session.content) session.frame(1) self.assertIn('frame 2', session.content) def test_frame_descend_by_index_invalid(self): session = self.session session.open(base_url) self.assertRaises(LookupError, session.frame, 10) def test_set_user_agent(self): def get_user_agent(session, **kwargs): page, resources = self.session.open( "%sdump" % base_url, **kwargs ) data = json.loads(page.content) return data['headers']['User-Agent'] session = self.session self.assertEqual(get_user_agent(session), default_user_agent) new_agent = 'New Agent' self.assertEqual( get_user_agent(session, user_agent=new_agent), new_agent, ) def test_exclude_regex(self): session = self.ghost.start(exclude="\.(jpg|css)") page, resources = session.open(base_url) url_loaded = [r.url for r in resources] self.assertFalse( "%sstatic/styles.css" % base_url in url_loaded) self.assertFalse( "%sstatic/blackhat.jpg" % base_url in url_loaded) session.exit() if __name__ == '__main__': unittest.main() Ghost.py-0.2.3/tests/static/000077500000000000000000000000001257624717600157015ustar00rootroot00000000000000Ghost.py-0.2.3/tests/static/app.js000066400000000000000000000033421257624717600170210ustar00rootroot00000000000000/*globals alert, confirm, prompt*/ var promptValue = null, result = false; window.addEventListener('DOMContentLoaded', function () { "use strict"; var alertButton = document.getElementById('alert-button'), confirmButton = document.getElementById('confirm-button'), promptButton = document.getElementById('prompt-button'), updateListButton = document.getElementById('update-list-button'); alertButton.addEventListener('click', function (e) { alert('this is an alert'); e.preventDefault(); }, false); confirmButton.addEventListener('click', function (e) { if (confirm('this is a confirm')) { alert('you confirmed!'); } else { alert('you denied!'); } e.preventDefault(); }, false); promptButton.addEventListener('click', function (e) { promptValue = prompt("Prompt ?"); e.preventDefault(); }, false); updateListButton.addEventListener('click', function (e) { var request = new XMLHttpRequest(); request.onreadystatechange = function () { if (this.readyState === this.DONE) { var data = JSON.parse(this.response), list = document.getElementById('list'); data.items.forEach(function (item) { var li = document.createElement('li'); li.innerHTML = item; list.appendChild(li); }); } }; request.open('GET', updateListButton.href, true); request.send(null); e.preventDefault(); }, false); window.setTimeout( function () { window.result = true; }, 3000 ); }, false); Ghost.py-0.2.3/tests/static/blackhat.jpg000066400000000000000000000135601257624717600201610ustar00rootroot00000000000000JFIFddDucky<Adobed       ,,   !1AQaq"2RBr#3CbƒS$4 ?H"RUd\¦G3óO~sV\t=u-t,/l׻OSs`b[%ռʌuNຮᩁd|y=۳7۠!oc|yE8ۏPO9hǽn5$Lbȷz*voZgjQѠ71Xss\_(ۖ:|Sʸc5$9vJzUkF_'7$\S^?>8L7o:ﳋn_M߈ lZwŭ-X׍pH56|о|s/Ez$[W:Ͼ\ʽ%r`qɸ^l){X״e*Qi;Z?&5"ߔ޼<ΔȺl/ܥUn|N;nT@>i:טgΙg'j719|;7m8_cڪZ_9C_uS*v,L Jz`ZVm@(4\d_j@Vs]z@mSeH>WG&RpYfv|z6/o~}yݘu~҂hM]8 [* z)=ړ׳OHxqmzNxN`Kras<\m]ؾIK6%u8hk^S^i@1ZxN'֠aVghN…V,gHmw_?8z.e:@pQl USx}WfݠC질M@)ٴ{~ z,Z:@-7F6oxO395{1MqCܸ|(isK {%՜_;%ՐRXI=RQuO ^J#ҠB P/© /X ;zQ~`*!m@s':syw:W,+ќڃhבg\Wq-嫱TR|XY˒-ۏ R_@uUyO$u|.֎,YsϜ8rn_ҝmG04k58cecrTv^ƟTd_zsvR˒)M[@H-M*l`J6-/`Od=Pֽ MWEnCm.hWVt^?'grK 5ڽn 8ڿ ⌀_Ayyҵ< [R}^-Kv/4|/yLs3rSZWnY5^q~x?8zӮrg6Vwlrw+xk9/:@ߠ}M7 *>{O׼zvzh`tPoP1w״J JQڀ$ voEN##"f\.vX֞_y{˝QrY6+T_z)5Uڐv=Sҽ?0,;~' in)ֽazr52reA}V-[[@&,F@eJX~,]6 UZSMB_@]Gf8u~p!қh1t:y53YW0g"̜el؞KyzŞK%(WZ_ei/oUNcr^Cji,2i\`$]@&wd3uoJ*:`Y>%QѦ@*vD4P,@*V*5y'j[n3ES@{#<$9'=6*Ekr$?[䯜{\+Pºu{@( -8jc_M|9?y} Ϋ^ Ou@>%: s@Zhtݠ`VuU* ƹ#)oM軀U QsW3\q.F5:J |.[VX昑uV_u=x.%>\I\<5*s9n\TWXq0*^ e7/8ŜF缻w jjH *e-5׸ @+OUV`RA{Ώ KR=ma*Ykgj}^ƟGu<2.p~n"߻)~ꄸht'GMeلy(imV Ԝ@ֺQih 4bҮT@V;R|@{@g(ŴPw\U_`ɰM/(L ' ݷX &tzWO^06;#vyWe16 C [w^@O A$ӣZ</ˏ.6o.R_ OǁH>;̮IÓ!8GW0& ܦwg}Ƶt)v;ӷ/ܷkon􏕞]av54,ڍQD0qȷZkxw~PW1o@tTyQ)mu7,u*qӪ=>o#ܴ۳rPmxI}i]k_ d=_X?^ǥ8@SDh ^ +8ހ▴c%8'E[1ے9i䩴~GŸ^ }Otw1F=וB[{(LLKXUK@fYȶ}G+Όf*2Uu?YV\4Y>RTsjqub/vOQ\䳶ڷvPkb^ k9Nuv@ֹmvZӧ`jZn`O¸4vh |;sJ@%pGl[eot3C\_ 1@x~]xEQ| E(d􇔹Yw-v{x@>Xq]PmjͫQ . ܵn⤻yGr\Uxы)p:-n6l9e$ISm@잋6[ӹ̰~йjR}P 2%D_`Ly->)ShrXLZWx)PQ2 >g~I;o&oht1wPxv1%x@伯!~2dVpoܲ𦗀&_a-m=qW-_~?3{^ߑUOOC9[[]sX>Ka_qQK9 {{ arg }} Ghost.py-0.2.3/tests/templates/home.html000066400000000000000000000100551257624717600202270ustar00rootroot00000000000000

Ghost.py

{% with messages = get_flashed_messages() %} {% if messages %}
    {% for message in messages %}
  • {{ message }}
  • {% endfor %}
{% endif %} {% endwith %}

Links

link

Forms

Javascripts

  • first item

Update list

Frames

Resources

Ghost.py-0.2.3/tests/templates/many_assets.html000066400000000000000000000005761257624717600216340ustar00rootroot00000000000000 {% for f in js %} {% endfor %} {% for f in css %} {% endfor %}

Many assets

Ghost.py-0.2.3/tests/uploaded_000066400000000000000000000000001257624717600162570ustar00rootroot00000000000000Ghost.py-0.2.3/tox.ini000066400000000000000000000010331257624717600145600ustar00rootroot00000000000000# Tox (http://tox.testrun.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = py27 sitepackages = True [testenv] commands = # Currently assuming that PySide is already installed, because builds fail for me on OS X 10.6.8, so I'm using pyside in Hombrew pip install --use-mirrors -r {toxinidir}/tests/requirements.txt {toxinidir}/tests/run.py -v