wsgi_intercept-1.4.1/0000755000076500000240000000000012772441264014774 5ustar cdentstaff00000000000000wsgi_intercept-1.4.1/docs/0000755000076500000240000000000012772441264015724 5ustar cdentstaff00000000000000wsgi_intercept-1.4.1/docs/.gitignore0000644000076500000240000000000712640224734017704 0ustar cdentstaff00000000000000_build wsgi_intercept-1.4.1/docs/_static/0000755000076500000240000000000012772441264017352 5ustar cdentstaff00000000000000wsgi_intercept-1.4.1/docs/_static/.gitignore0000644000076500000240000000000012640224734021323 0ustar cdentstaff00000000000000wsgi_intercept-1.4.1/docs/_templates/0000755000076500000240000000000012772441264020061 5ustar cdentstaff00000000000000wsgi_intercept-1.4.1/docs/_templates/.gitignore0000644000076500000240000000000012640224734022032 0ustar cdentstaff00000000000000wsgi_intercept-1.4.1/docs/conf.py0000644000076500000240000002456012640466071017227 0ustar cdentstaff00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # wsgi_intercept documentation build configuration file, created by # sphinx-quickstart on Fri May 16 13:03:52 2014. # # 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 import os # 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.insert(0, os.path.abspath('.')) docroot = os.path.abspath('..') sys.path.insert(0, docroot) # -- 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', 'sphinx.ext.doctest', ] # 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 = 'wsgi_intercept' copyright = '2015, Titus Brown, Kumar McMillan, Chris Dent, Sasha Hart' # 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 = '0.6.2' # The full version, including alpha/beta/rc tags. #release = '0.6.2' # 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 = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- 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 = 'default' # 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 = {} # 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 = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # 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'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # 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 # 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 = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'wsgi_interceptdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'wsgi_intercept.tex', 'wsgi\\_intercept Documentation', 'Titus Brown, Kumar McMillan, Chris Dent', '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 # 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). man_pages = [ ('index', 'wsgi_intercept', 'wsgi_intercept Documentation', ['Titus Brown, Kumar McMillan, Chris Dent'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'wsgi_intercept', 'wsgi_intercept Documentation', 'Titus Brown, Kumar McMillan, Chris Dent', 'wsgi_intercept', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = 'wsgi_intercept' epub_author = 'Titus Brown, Kumar McMillan, Chris Dent' epub_publisher = 'Titus Brown, Kumar McMillan, Chris Dent' epub_copyright = '2015, Titus Brown, Kumar McMillan, Chris Dent' # The basename for the epub file. It defaults to the project name. #epub_basename = 'wsgi_intercept' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True wsgi_intercept-1.4.1/docs/http_client.rst0000644000076500000240000000232712640224734020772 0ustar cdentstaff00000000000000http_client_intercept ===================== .. automodule:: wsgi_intercept.http_client_intercept .. warning:: This intercept will fail to install if you access access HTTPConnection or HTTPSConnection before the intercept is installed. For example, do not use "from http.client import HTTPConnection". Instead, "import http.client" and reference http.client.HTTPConnection after the intercept is installed. Example: .. testcode:: try: import http.client as http_lib except ImportError: import httplib as http_lib from wsgi_intercept import ( http_client_intercept, add_wsgi_intercept, remove_wsgi_intercept ) def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Whee'] def make_app(): return app host, port = 'localhost', 80 http_client_intercept.install() add_wsgi_intercept(host, port, make_app) HTTPConnection = http_lib.HTTPConnection client = HTTPConnection(host) client.request('GET', '/') response = client.getresponse() content = response.read() assert content == b'Whee' remove_wsgi_intercept(host, port) http_client_intercept.uninstall() wsgi_intercept-1.4.1/docs/httplib2.rst0000644000076500000240000000123512640224734020202 0ustar cdentstaff00000000000000httplib2_intercept ================== .. automodule:: wsgi_intercept.httplib2_intercept Example: .. testcode:: import httplib2 from wsgi_intercept import httplib2_intercept, add_wsgi_intercept def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Whee'] def make_app(): return app host, port = 'localhost', 80 url = 'http://{0}:{1}/'.format(host, port) httplib2_intercept.install() add_wsgi_intercept(host, port, make_app) http = httplib2.Http() resp, content = http.request(url) assert content == b'Whee' httplib2_intercept.uninstall() wsgi_intercept-1.4.1/docs/index.rst0000644000076500000240000000054012673010314017550 0ustar cdentstaff00000000000000================================ Documentation for wsgi_intercept ================================ .. automodule:: wsgi_intercept Examples ======== .. toctree:: :maxdepth: 1 interceptor http_client httplib2 requests urllib3 urllib Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` wsgi_intercept-1.4.1/docs/interceptor.rst0000644000076500000240000000111212640466071021004 0ustar cdentstaff00000000000000 Interceptor =========== .. automodule:: wsgi_intercept.interceptor :members: Example using `httplib2`, others are much the same: .. testcode:: import httplib2 from wsgi_intercept.interceptor import Httplib2Interceptor def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Whee'] def make_app(): return app http = httplib2.Http() with Httplib2Interceptor(make_app, host='localhost', port=80) as url: resp, content = http.request(url) assert content == b'Whee' wsgi_intercept-1.4.1/docs/Makefile0000644000076500000240000001521212640224734017360 0ustar cdentstaff00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/wsgi_intercept.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/wsgi_intercept.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/wsgi_intercept" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/wsgi_intercept" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." wsgi_intercept-1.4.1/docs/requests.rst0000644000076500000240000000117712640224734020332 0ustar cdentstaff00000000000000requests_intercept ================== .. automodule:: wsgi_intercept.requests_intercept Example: .. testcode:: import requests from wsgi_intercept import requests_intercept, add_wsgi_intercept def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Whee'] def make_app(): return app host, port = 'localhost', 80 url = 'http://{0}:{1}/'.format(host, port) requests_intercept.install() add_wsgi_intercept(host, port, make_app) resp = requests.get(url) assert resp.content == b'Whee' requests_intercept.uninstall() wsgi_intercept-1.4.1/docs/urllib.rst0000644000076500000240000000141412640224734017742 0ustar cdentstaff00000000000000urllib_intercept ================ .. automodule:: wsgi_intercept.urllib_intercept Example: .. testcode:: try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen from wsgi_intercept import ( urllib_intercept, add_wsgi_intercept, remove_wsgi_intercept ) def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Whee'] def make_app(): return app host, port = 'localhost', 80 url = 'http://{0}:{1}/'.format(host, port) urllib_intercept.install_opener() add_wsgi_intercept(host, port, make_app) stream = urlopen(url) content = stream.read() assert content == b'Whee' remove_wsgi_intercept() wsgi_intercept-1.4.1/docs/urllib3.rst0000644000076500000240000000123712771214240020024 0ustar cdentstaff00000000000000urllib3_intercept ================== .. automodule:: wsgi_intercept.urllib3_intercept Example: .. testcode:: import urllib3 from wsgi_intercept import urllib3_intercept, add_wsgi_intercept pool = urllib3.PoolManager() def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Whee'] def make_app(): return app host, port = 'localhost', 80 url = 'http://{0}:{1}/'.format(host, port) urllib3_intercept.install() add_wsgi_intercept(host, port, make_app) resp = pool.request('GET', url) assert resp.data == b'Whee' urllib3_intercept.uninstall() wsgi_intercept-1.4.1/LICENSE0000644000076500000240000000210612640224734015773 0ustar cdentstaff00000000000000The MIT License Copyright (c) 2012-2015 wsgi-intercept contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. wsgi_intercept-1.4.1/Makefile0000644000076500000240000000172412771214240016427 0ustar cdentstaff00000000000000.PHONY: test clean reclean tagv pypi release docs default: @echo "Pick a target (e.g., clean, test)" clean: find wsgi_intercept test -name "*.py[co]" |xargs rm || true find wsgi_intercept test -type d -name "__pycache__" |xargs rmdir || true rm -r dist || true rm -r build || true rm -r wsgi_intercept.egg-info || true rm *.bundle || true rm -r *-bundle* || true cd docs && make clean reclean: find wsgi_intercept test -name "*.py[co]" |xargs rm || true find wsgi_intercept test -type d -name "__pycache__" |xargs rmdir || true rm -r dist || true rm -r build || true rm -r wsgi_intercept.egg-info || true rm *.bundle || true rm -r *-bundle* || true cd docs && make clean test: tox --skip-missing-interpreters doctest: cd docs && make doctest tagv: git tag -a \ -m v`python setup.py --version` \ v`python setup.py --version` git push origin master --tags pypi: python setup.py sdist upload docs: tox -edocs release: clean test tagv reclean pypi wsgi_intercept-1.4.1/MANIFEST.in0000644000076500000240000000006212772441023016521 0ustar cdentstaff00000000000000include LICENSE Makefile recursive-include docs * wsgi_intercept-1.4.1/PKG-INFO0000644000076500000240000001600712772441264016075 0ustar cdentstaff00000000000000Metadata-Version: 1.1 Name: wsgi_intercept Version: 1.4.1 Summary: wsgi_intercept installs a WSGI application in place of a real URI for testing. Home-page: http://pypi.python.org/pypi/wsgi_intercept Author: Titus Brown, Kumar McMillan, Chris Dent, Sasha Hart Author-email: cdent@peermore.com License: MIT License Description: Installs a WSGI application in place of a real host for testing. Introduction ============ Testing a WSGI application sometimes involves starting a server at a local host and port, then pointing your test code to that address. Instead, this library lets you intercept calls to any specific host/port combination and redirect them into a `WSGI application`_ importable by your test program. Thus, you can avoid spawning multiple processes or threads to test your Web app. Supported Libaries ================== ``wsgi_intercept`` works with a variety of HTTP clients in Python 2.7, 3.3 and beyond, and in pypy. * urllib2 * urllib.request * httplib * http.client * httplib2 * requests * urllib3 How Does It Work? ================= ``wsgi_intercept`` works by replacing ``httplib.HTTPConnection`` with a subclass, ``wsgi_intercept.WSGI_HTTPConnection``. This class then redirects specific server/port combinations into a WSGI application by emulating a socket. If no intercept is registered for the host and port requested, those requests are passed on to the standard handler. The easiest way to use an intercept is to import an appropriate subclass of ``~wsgi_intercept.interceptor.Interceptor`` and use that as a context manager over web requests that use the library associated with the subclass. For example:: import httplib2 from wsgi_intercept.interceptor import Httplib2Interceptor from mywsgiapp import app def load_app(): return app http = httplib2.Http() with Httplib2Interceptor(load_app, host='example.com', port=80) as url: response, content = http.request('%s%s' % (url, '/path')) assert response.status == 200 The interceptor class may aslo be used directly to install intercepts. See the module documentation for more information. Older versions required that the functions ``add_wsgi_intercept(host, port, app_create_fn, script_name='')`` and ``remove_wsgi_intercept(host,port)`` be used to specify which URLs should be redirected into what applications. These methods are still available, but the ``Interceptor`` classes are likely easier to use for most use cases. .. note:: ``app_create_fn`` is a *function object* returning a WSGI application; ``script_name`` becomes ``SCRIPT_NAME`` in the WSGI app's environment, if set. .. note:: If ``http_proxy`` or ``https_proxy`` is set in the environment this can cause difficulties with some of the intercepted libraries. If requests or urllib is being used, these will raise an exception if one of those variables is set. .. note:: If ``wsgi_intercept.STRICT_RESPONSE_HEADERS`` is set to ``True`` then response headers sent by an application will be checked to make sure they are of the type ``str`` native to the version of Python, as required by pep 3333. The default is ``False`` (to preserve backwards compatibility) Install ======= :: pip install -U wsgi_intercept Packages Intercepted ==================== Unfortunately each of the HTTP client libraries use their own specific mechanism for making HTTP call-outs, so individual implementations are needed. At this time there are implementations for ``httplib2``, ``urllib3`` and ``requests`` in both Python 2 and 3, ``urllib2`` and ``httplib`` in Python 2 and ``urllib.request`` and ``http.client`` in Python 3. If you are using Python 2 and need support for a different HTTP client, require a version of ``wsgi_intercept<0.6``. Earlier versions include support for ``webtest``, ``webunit`` and ``zope.testbrowser``. The best way to figure out how to use interception is to inspect `the tests`_. More comprehensive documentation available upon request. .. _the tests: https://github.com/cdent/wsgi-intercept/tree/master/test History ======= Pursuant to Ian Bicking's `"best Web testing framework"`_ post, Titus Brown put together an `in-process HTTP-to-WSGI interception mechanism`_ for his own Web testing system, twill. Because the mechanism is pretty generic -- it works at the httplib level -- Titus decided to try adding it into all of the *other* Python Web testing frameworks. The Python 2 version of wsgi-intercept was the result. Kumar McMillan later took over maintenance. The current version is tested with Python 2.7, 3.3, 3.4, 3.5 and pypy and was assembled by `Chris Dent`_. Testing and documentation improvements from `Sasha Hart`_. .. _"best Web testing framework": http://blog.ianbicking.org/best-of-the-web-app-test-frameworks.html .. _in-process HTTP-to-WSGI interception mechanism: http://www.advogato.org/person/titus/diary.html?start=119 .. _WSGI application: http://www.python.org/peps/pep-3333.html .. _Chris Dent: https://github.com/cdent .. _Sasha Hart: https://github.com/sashahart Project Home ============ This project lives on `GitHub`_. Please submit all bugs, patches, failing tests, et cetera using the Issue Tracker. Additional documentation is available on `Read The Docs`_. .. _GitHub: http://github.com/cdent/wsgi-intercept .. _Read The Docs: http://wsgi-intercept.readthedocs.org/en/latest/ Platform: UNKNOWN Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Topic :: Internet :: WWW/HTTP :: WSGI Classifier: Topic :: Software Development :: Testing wsgi_intercept-1.4.1/README0000644000076500000240000001201512772441256015654 0ustar cdentstaff00000000000000Installs a WSGI application in place of a real host for testing. Introduction ============ Testing a WSGI application sometimes involves starting a server at a local host and port, then pointing your test code to that address. Instead, this library lets you intercept calls to any specific host/port combination and redirect them into a `WSGI application`_ importable by your test program. Thus, you can avoid spawning multiple processes or threads to test your Web app. Supported Libaries ================== ``wsgi_intercept`` works with a variety of HTTP clients in Python 2.7, 3.3 and beyond, and in pypy. * urllib2 * urllib.request * httplib * http.client * httplib2 * requests * urllib3 How Does It Work? ================= ``wsgi_intercept`` works by replacing ``httplib.HTTPConnection`` with a subclass, ``wsgi_intercept.WSGI_HTTPConnection``. This class then redirects specific server/port combinations into a WSGI application by emulating a socket. If no intercept is registered for the host and port requested, those requests are passed on to the standard handler. The easiest way to use an intercept is to import an appropriate subclass of ``~wsgi_intercept.interceptor.Interceptor`` and use that as a context manager over web requests that use the library associated with the subclass. For example:: import httplib2 from wsgi_intercept.interceptor import Httplib2Interceptor from mywsgiapp import app def load_app(): return app http = httplib2.Http() with Httplib2Interceptor(load_app, host='example.com', port=80) as url: response, content = http.request('%s%s' % (url, '/path')) assert response.status == 200 The interceptor class may aslo be used directly to install intercepts. See the module documentation for more information. Older versions required that the functions ``add_wsgi_intercept(host, port, app_create_fn, script_name='')`` and ``remove_wsgi_intercept(host,port)`` be used to specify which URLs should be redirected into what applications. These methods are still available, but the ``Interceptor`` classes are likely easier to use for most use cases. .. note:: ``app_create_fn`` is a *function object* returning a WSGI application; ``script_name`` becomes ``SCRIPT_NAME`` in the WSGI app's environment, if set. .. note:: If ``http_proxy`` or ``https_proxy`` is set in the environment this can cause difficulties with some of the intercepted libraries. If requests or urllib is being used, these will raise an exception if one of those variables is set. .. note:: If ``wsgi_intercept.STRICT_RESPONSE_HEADERS`` is set to ``True`` then response headers sent by an application will be checked to make sure they are of the type ``str`` native to the version of Python, as required by pep 3333. The default is ``False`` (to preserve backwards compatibility) Install ======= :: pip install -U wsgi_intercept Packages Intercepted ==================== Unfortunately each of the HTTP client libraries use their own specific mechanism for making HTTP call-outs, so individual implementations are needed. At this time there are implementations for ``httplib2``, ``urllib3`` and ``requests`` in both Python 2 and 3, ``urllib2`` and ``httplib`` in Python 2 and ``urllib.request`` and ``http.client`` in Python 3. If you are using Python 2 and need support for a different HTTP client, require a version of ``wsgi_intercept<0.6``. Earlier versions include support for ``webtest``, ``webunit`` and ``zope.testbrowser``. The best way to figure out how to use interception is to inspect `the tests`_. More comprehensive documentation available upon request. .. _the tests: https://github.com/cdent/wsgi-intercept/tree/master/test History ======= Pursuant to Ian Bicking's `"best Web testing framework"`_ post, Titus Brown put together an `in-process HTTP-to-WSGI interception mechanism`_ for his own Web testing system, twill. Because the mechanism is pretty generic -- it works at the httplib level -- Titus decided to try adding it into all of the *other* Python Web testing frameworks. The Python 2 version of wsgi-intercept was the result. Kumar McMillan later took over maintenance. The current version is tested with Python 2.7, 3.3, 3.4, 3.5 and pypy and was assembled by `Chris Dent`_. Testing and documentation improvements from `Sasha Hart`_. .. _"best Web testing framework": http://blog.ianbicking.org/best-of-the-web-app-test-frameworks.html .. _in-process HTTP-to-WSGI interception mechanism: http://www.advogato.org/person/titus/diary.html?start=119 .. _WSGI application: http://www.python.org/peps/pep-3333.html .. _Chris Dent: https://github.com/cdent .. _Sasha Hart: https://github.com/sashahart Project Home ============ This project lives on `GitHub`_. Please submit all bugs, patches, failing tests, et cetera using the Issue Tracker. Additional documentation is available on `Read The Docs`_. .. _GitHub: http://github.com/cdent/wsgi-intercept .. _Read The Docs: http://wsgi-intercept.readthedocs.org/en/latest/ wsgi_intercept-1.4.1/setup.cfg0000644000076500000240000000017512772441264016620 0ustar cdentstaff00000000000000[pep8] ignore = E128,E127,E126 [flake8] ignore = E128,E127,E126 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 wsgi_intercept-1.4.1/setup.py0000644000076500000240000000256312772440740016512 0ustar cdentstaff00000000000000 from setuptools import setup, find_packages VERSION = '1.4.1' CLASSIFIERS = """ Environment :: Web Environment Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python :: 2 Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.3 Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Topic :: Internet :: WWW/HTTP :: WSGI Topic :: Software Development :: Testing """.strip().splitlines() META = { 'name': 'wsgi_intercept', 'version': VERSION, 'author': 'Titus Brown, Kumar McMillan, Chris Dent, Sasha Hart', 'author_email': 'cdent@peermore.com', 'description': 'wsgi_intercept installs a WSGI application in place of a ' 'real URI for testing.', # What will the name be? 'url': 'http://pypi.python.org/pypi/wsgi_intercept', 'long_description': open('README').read(), 'license': 'MIT License', 'classifiers': CLASSIFIERS, 'packages': find_packages(), 'install_requires': [ 'six', ], 'extras_require': { 'testing': [ 'pytest>=2.4', 'httplib2', 'requests>=2.0.1', 'urllib3>=1.11.0', ], 'docs': [ 'sphinx', ], }, } if __name__ == '__main__': setup(**META) wsgi_intercept-1.4.1/wsgi_intercept/0000755000076500000240000000000012772441264020022 5ustar cdentstaff00000000000000wsgi_intercept-1.4.1/wsgi_intercept/__init__.py0000644000076500000240000005101212772437557022144 0ustar cdentstaff00000000000000"""Installs a WSGI application in place of a real host for testing. Introduction ============ Testing a WSGI application sometimes involves starting a server at a local host and port, then pointing your test code to that address. Instead, this library lets you intercept calls to any specific host/port combination and redirect them into a `WSGI application`_ importable by your test program. Thus, you can avoid spawning multiple processes or threads to test your Web app. Supported Libaries ================== ``wsgi_intercept`` works with a variety of HTTP clients in Python 2.7, 3.3 and beyond, and in pypy. * urllib2 * urllib.request * httplib * http.client * httplib2 * requests * urllib3 How Does It Work? ================= ``wsgi_intercept`` works by replacing ``httplib.HTTPConnection`` with a subclass, ``wsgi_intercept.WSGI_HTTPConnection``. This class then redirects specific server/port combinations into a WSGI application by emulating a socket. If no intercept is registered for the host and port requested, those requests are passed on to the standard handler. The easiest way to use an intercept is to import an appropriate subclass of ``~wsgi_intercept.interceptor.Interceptor`` and use that as a context manager over web requests that use the library associated with the subclass. For example:: import httplib2 from wsgi_intercept.interceptor import Httplib2Interceptor from mywsgiapp import app def load_app(): return app http = httplib2.Http() with Httplib2Interceptor(load_app, host='example.com', port=80) as url: response, content = http.request('%s%s' % (url, '/path')) assert response.status == 200 The interceptor class may aslo be used directly to install intercepts. See the module documentation for more information. Older versions required that the functions ``add_wsgi_intercept(host, port, app_create_fn, script_name='')`` and ``remove_wsgi_intercept(host,port)`` be used to specify which URLs should be redirected into what applications. These methods are still available, but the ``Interceptor`` classes are likely easier to use for most use cases. .. note:: ``app_create_fn`` is a *function object* returning a WSGI application; ``script_name`` becomes ``SCRIPT_NAME`` in the WSGI app's environment, if set. .. note:: If ``http_proxy`` or ``https_proxy`` is set in the environment this can cause difficulties with some of the intercepted libraries. If requests or urllib is being used, these will raise an exception if one of those variables is set. .. note:: If ``wsgi_intercept.STRICT_RESPONSE_HEADERS`` is set to ``True`` then response headers sent by an application will be checked to make sure they are of the type ``str`` native to the version of Python, as required by pep 3333. The default is ``False`` (to preserve backwards compatibility) Install ======= :: pip install -U wsgi_intercept Packages Intercepted ==================== Unfortunately each of the HTTP client libraries use their own specific mechanism for making HTTP call-outs, so individual implementations are needed. At this time there are implementations for ``httplib2``, ``urllib3`` and ``requests`` in both Python 2 and 3, ``urllib2`` and ``httplib`` in Python 2 and ``urllib.request`` and ``http.client`` in Python 3. If you are using Python 2 and need support for a different HTTP client, require a version of ``wsgi_intercept<0.6``. Earlier versions include support for ``webtest``, ``webunit`` and ``zope.testbrowser``. The best way to figure out how to use interception is to inspect `the tests`_. More comprehensive documentation available upon request. .. _the tests: https://github.com/cdent/wsgi-intercept/tree/master/test History ======= Pursuant to Ian Bicking's `"best Web testing framework"`_ post, Titus Brown put together an `in-process HTTP-to-WSGI interception mechanism`_ for his own Web testing system, twill. Because the mechanism is pretty generic -- it works at the httplib level -- Titus decided to try adding it into all of the *other* Python Web testing frameworks. The Python 2 version of wsgi-intercept was the result. Kumar McMillan later took over maintenance. The current version is tested with Python 2.7, 3.3, 3.4, 3.5 and pypy and was assembled by `Chris Dent`_. Testing and documentation improvements from `Sasha Hart`_. .. _"best Web testing framework": http://blog.ianbicking.org/best-of-the-web-app-test-frameworks.html .. _in-process HTTP-to-WSGI interception mechanism: http://www.advogato.org/person/titus/diary.html?start=119 .. _WSGI application: http://www.python.org/peps/pep-3333.html .. _Chris Dent: https://github.com/cdent .. _Sasha Hart: https://github.com/sashahart Project Home ============ This project lives on `GitHub`_. Please submit all bugs, patches, failing tests, et cetera using the Issue Tracker. Additional documentation is available on `Read The Docs`_. .. _GitHub: http://github.com/cdent/wsgi-intercept .. _Read The Docs: http://wsgi-intercept.readthedocs.org/en/latest/ """ from __future__ import print_function import sys import traceback from io import BytesIO # Don't use six here because it is unquote_to_bytes that we want in # Python 3. try: from urllib.parse import unquote_to_bytes as url_unquote except ImportError: from urllib import unquote as url_unquote import six from six.moves.http_client import HTTPConnection, HTTPSConnection # Set this to True to cause response headers from the intercepted # app to be confirmed as bytestrings, behaving as some wsgi servers. STRICT_RESPONSE_HEADERS = False debuglevel = 0 # 1 basic # 2 verbose #### # # Specify which hosts/ports to target for interception to a given WSGI app. # # For simplicity's sake, intercept ENTIRE host/port combinations; # intercepting only specific URL subtrees gets complicated, because we don't # have that information in the HTTPConnection.connect() function that does the # redirection. # # format: key=(host, port), value=(create_app, top_url) # # (top_url becomes the SCRIPT_NAME) _wsgi_intercept = {} def add_wsgi_intercept(host, port, app_create_fn, script_name=''): """ Add a WSGI intercept call for host:port, using the app returned by app_create_fn with a SCRIPT_NAME of 'script_name' (default ''). """ _wsgi_intercept[(host, port)] = (app_create_fn, script_name) def remove_wsgi_intercept(*args): """ Remove the WSGI intercept call for (host, port). If no arguments are given, removes all intercepts """ global _wsgi_intercept if len(args) == 0: _wsgi_intercept = {} else: key = (args[0], args[1]) if key in _wsgi_intercept: del _wsgi_intercept[key] # # make_environ: behave like a Web server. Take in 'input', and behave # as if you're bound to 'host' and 'port'; build an environment dict # for the WSGI app. # # This is where the magic happens, folks. # def make_environ(inp, host, port, script_name): """ Take 'inp' as if it were HTTP-speak being received on host:port, and parse it into a WSGI-ok environment dictionary. Return the dictionary. Set 'SCRIPT_NAME' from the 'script_name' input, and, if present, remove it from the beginning of the PATH_INFO variable. """ # # parse the input up to the first blank line (or its end). # environ = {} method_line = inp.readline() if six.PY3: method_line = method_line.decode('ISO-8859-1') content_type = None content_length = None cookies = [] for line in inp: if not line.strip(): break k, v = line.strip().split(b':', 1) v = v.lstrip() # Make header value a "native" string. PEP 3333 requires that # string-like things in headers be of type `str`. Much of the # time this isn't a problem but the SimpleCookie library does # type checking against `type("")`. v = str(v.decode('ISO-8859-1')) # # take care of special headers, and for the rest, put them # into the environ with HTTP_ in front. # if k.lower() == b'content-type': content_type = v elif k.lower() == b'content-length': content_length = v elif k.lower() == b'cookie' or k.lower() == b'cookie2': cookies.append(v) else: h = k.upper() h = h.replace(b'-', b'_') environ['HTTP_' + h.decode('ISO-8859-1')] = v if debuglevel >= 2: print('HEADER:', k, v) # # decode the method line # if debuglevel >= 2: print('METHOD LINE:', method_line) method, url, protocol = method_line.split(' ') # Store the URI as requested by the user, without modification # so that PATH_INFO munging can be corrected. environ['REQUEST_URI'] = url environ['RAW_URI'] = url # clean the script_name off of the url, if it's there. if not url.startswith(script_name): script_name = '' # @CTB what to do -- bad URL. scrap? else: url = url[len(script_name):] url = url.split('?', 1) path_info = url_unquote(url[0]) query_string = "" if len(url) == 2: query_string = url[1] if debuglevel: print("method: %s; script_name: %s; path_info: %s; query_string: %s" % (method, script_name, path_info, query_string)) r = inp.read() inp = BytesIO(r) # # fill out our dictionary. # # In Python3 turn the bytes of the path info into a string of # latin-1 code points, because that's what the spec says we must # do to be like a server. Later various libraries will be forced # to decode and then reencode to get the UTF-8 that everyone # wants. if six.PY3: path_info = path_info.decode('latin-1') environ.update({ "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": inp, # to read for POSTs "wsgi.errors": BytesIO(), "wsgi.multithread": 0, "wsgi.multiprocess": 0, "wsgi.run_once": 0, "PATH_INFO": path_info, "REMOTE_ADDR": '127.0.0.1', "REQUEST_METHOD": method, "SCRIPT_NAME": script_name, "SERVER_NAME": host, "SERVER_PORT": port, "SERVER_PROTOCOL": protocol, }) # # query_string, content_type & length are optional. # if query_string: environ['QUERY_STRING'] = query_string if content_type: environ['CONTENT_TYPE'] = content_type if debuglevel >= 2: print('CONTENT-TYPE:', content_type) if content_length: environ['CONTENT_LENGTH'] = content_length if debuglevel >= 2: print('CONTENT-LENGTH:', content_length) # # handle cookies. # if cookies: environ['HTTP_COOKIE'] = "; ".join(cookies) if debuglevel: print('WSGI environ dictionary:', environ) return environ class WSGIAppError(Exception): """ An exception that wraps any Exception raised by the WSGI app that is called. This is done for two reasons: it ensures that intercepted libraries (such as requests) which use exceptions to trigger behaviors are not interfered with by exceptions from the WSGI app. It also helps to define a solid boundary, akin to the network boundary between server and client, in the testing environment. """ def __init__(self, error, exc_info): Exception.__init__(self) self.error = error self.exception_type = exc_info[0] self.exception_value = exc_info[1] self.traceback = exc_info[2] def __str__(self): frame = traceback.extract_tb(self.traceback)[-1] formatted = "{0!r} at {1}:{2}".format( self.error, frame[0], frame[1], ) return formatted # # fake socket for WSGI intercept stuff. # class wsgi_fake_socket: """ Handle HTTP traffic and stuff into a WSGI application object instead. Note that this class assumes: 1. 'makefile' is called (by the response class) only after all of the data has been sent to the socket by the request class; 2. non-persistent (i.e. non-HTTP/1.1) connections. """ def __init__(self, app, host, port, script_name, https=False): self.app = app # WSGI app object self.host = host self.port = port self.script_name = script_name # SCRIPT_NAME (app mount point) self.inp = BytesIO() # stuff written into this "socket" self.write_results = [] # results from the 'write_fn' self.results = None # results from running the app self.output = BytesIO() # all output from the app, incl headers self.https = https def makefile(self, *args, **kwargs): """ 'makefile' is called by the HTTPResponse class once all of the data has been written. So, in this interceptor class, we need to: 1. build a start_response function that grabs all the headers returned by the WSGI app; 2. create a wsgi.input file object 'inp', containing all of the traffic; 3. build an environment dict out of the traffic in inp; 4. run the WSGI app & grab the result object; 5. concatenate & return the result(s) read from the result object. """ # dynamically construct the start_response function for no good reason. self.headers = [] def start_response(status, headers, exc_info=None): # construct the HTTP request. self.output.write( b"HTTP/1.0 " + status.encode('ISO-8859-1') + b"\n") # Keep the reference of the headers list to write them only # when the whole application have been processed self.headers = headers return self.write_results.append # construct the wsgi.input file from everything that's been # written to this "socket". inp = BytesIO(self.inp.getvalue()) # build the environ dictionary. environ = make_environ(inp, self.host, self.port, self.script_name) if self.https: environ['wsgi.url_scheme'] = 'https' # run the application. try: app_result = self.app(environ, start_response) except Exception as error: raise WSGIAppError(error, sys.exc_info()) self.result = iter(app_result) # send the headers for k, v in self.headers: if STRICT_RESPONSE_HEADERS: if not (isinstance(k, str) and isinstance(v, str)): raise TypeError( "Header has a key '%s' or value '%s' " "which is not a native str." % (k, v)) try: k = k.encode('ISO-8859-1') except AttributeError: pass try: v = v.encode('ISO-8859-1') except AttributeError: pass self.output.write(k + b': ' + v + b"\n") self.output.write(b'\n') ### # read all of the results. the trick here is to get the *first* # bit of data from the app via the generator, *then* grab & return # the data passed back from the 'write' function, and then return # the generator data. this is because the 'write' fn doesn't # necessarily get called until the first result is requested from # the app function. try: generator_data = None try: generator_data = next(self.result) finally: for data in self.write_results: self.output.write(data) if generator_data: try: self.output.write(generator_data) except TypeError as exc: raise TypeError('bytes required in response: %s' % exc) while 1: data = next(self.result) self.output.write(data) except StopIteration: pass if hasattr(app_result, 'close'): app_result.close() if debuglevel >= 2: print("***", self.output.getvalue(), "***") # return the concatenated results. return BytesIO(self.output.getvalue()) def sendall(self, content): """ Save all the traffic to self.inp. """ if debuglevel >= 2: print(">>>", content, ">>>") try: self.inp.write(content) except TypeError: self.inp.write(content.encode('utf-8')) def close(self): "Do nothing, for now." pass # # WSGI_HTTPConnection # class WSGI_HTTPConnection(HTTPConnection): """ Intercept all traffic to certain hosts & redirect into a WSGI application object. """ def get_app(self, host, port): """ Return the app object for the given (host, port). """ key = (host, int(port)) app, script_name = None, None if key in _wsgi_intercept: (app_fn, script_name) = _wsgi_intercept[key] app = app_fn() return app, script_name def connect(self): """ Override the connect() function to intercept calls to certain host/ports. If no app at host/port has been registered for interception then a normal HTTPConnection is made. """ if debuglevel: sys.stderr.write('connect: %s, %s\n' % (self.host, self.port,)) try: (app, script_name) = self.get_app(self.host, self.port) if app: if debuglevel: sys.stderr.write('INTERCEPTING call to %s:%s\n' % (self.host, self.port,)) self.sock = wsgi_fake_socket(app, self.host, self.port, script_name) else: HTTPConnection.connect(self) except Exception: if debuglevel: # intercept & print out tracebacks traceback.print_exc() raise # # WSGI_HTTPSConnection # class WSGI_HTTPSConnection(HTTPSConnection, WSGI_HTTPConnection): """ Intercept all traffic to certain hosts & redirect into a WSGI application object. """ def get_app(self, host, port): """ Return the app object for the given (host, port). """ key = (host, int(port)) app, script_name = None, None if key in _wsgi_intercept: (app_fn, script_name) = _wsgi_intercept[key] app = app_fn() return app, script_name def connect(self): """ Override the connect() function to intercept calls to certain host/ports. If no app at host/port has been registered for interception then a normal HTTPSConnection is made. """ if debuglevel: sys.stderr.write('connect: %s, %s\n' % (self.host, self.port,)) try: (app, script_name) = self.get_app(self.host, self.port) if app: if debuglevel: sys.stderr.write('INTERCEPTING call to %s:%s\n' % (self.host, self.port,)) self.sock = wsgi_fake_socket(app, self.host, self.port, script_name, https=True) else: try: import ssl if not hasattr(self, 'key_file'): self.key_file = None if not hasattr(self, 'cert_file'): self.cert_file = None if not hasattr(self, '_context'): try: self._context = ssl.create_default_context() except AttributeError: self._context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) self._context.options |= ssl.OP_NO_SSLv2 if not hasattr(self, 'check_hostname'): self._check_hostname = ( self._context.verify_mode != ssl.CERT_NONE ) else: self._check_hostname = self.check_hostname except (ImportError, AttributeError): pass HTTPSConnection.connect(self) except Exception: if debuglevel: # intercept & print out tracebacks traceback.print_exc() raise wsgi_intercept-1.4.1/wsgi_intercept/_urllib3.py0000644000076500000240000000302112771214240022072 0ustar cdentstaff00000000000000"""Common code of urllib3 and requests intercepts.""" import os import sys from . import WSGI_HTTPConnection, WSGI_HTTPSConnection, wsgi_fake_socket wsgi_fake_socket.settimeout = lambda self, timeout: None def make_urllib3_override(HTTPConnectionPool, HTTPSConnectionPool, HTTPConnection, HTTPSConnection): class HTTP_WSGIInterceptor(WSGI_HTTPConnection, HTTPConnection): def __init__(self, *args, **kwargs): if 'strict' in kwargs and sys.version_info > (3, 0): kwargs.pop('strict') WSGI_HTTPConnection.__init__(self, *args, **kwargs) HTTPConnection.__init__(self, *args, **kwargs) class HTTPS_WSGIInterceptor(WSGI_HTTPSConnection, HTTPSConnection): is_verified = True def __init__(self, *args, **kwargs): if 'strict' in kwargs and sys.version_info > (3, 0): kwargs.pop('strict') WSGI_HTTPSConnection.__init__(self, *args, **kwargs) HTTPSConnection.__init__(self, *args, **kwargs) def install(): if 'http_proxy' in os.environ or 'https_proxy' in os.environ: raise RuntimeError( 'http_proxy or https_proxy set in environment, please unset') HTTPConnectionPool.ConnectionCls = HTTP_WSGIInterceptor HTTPSConnectionPool.ConnectionCls = HTTPS_WSGIInterceptor def uninstall(): HTTPConnectionPool.ConnectionCls = HTTPConnection HTTPSConnectionPool.ConnectionCls = HTTPSConnection return install, uninstall wsgi_intercept-1.4.1/wsgi_intercept/http_client_intercept.py0000644000076500000240000000232212735004465024762 0ustar cdentstaff00000000000000"""Intercept HTTP connections that use httplib (Py2) or http.client (Py3). """ try: import http.client as http_lib except ImportError: import httplib as http_lib from . import WSGI_HTTPConnection, WSGI_HTTPSConnection try: from http.client import ( HTTPConnection as OriginalHTTPConnection, HTTPSConnection as OriginalHTTPSConnection ) except ImportError: from httplib import ( HTTPConnection as OriginalHTTPConnection, HTTPSConnection as OriginalHTTPSConnection ) class HTTP_WSGIInterceptor(WSGI_HTTPConnection, http_lib.HTTPConnection): pass class HTTPS_WSGIInterceptor(WSGI_HTTPSConnection, http_lib.HTTPSConnection, HTTP_WSGIInterceptor): def __init__(self, host, **kwargs): self.host = host try: self.port = kwargs['port'] except KeyError: self.port = None HTTP_WSGIInterceptor.__init__(self, host, **kwargs) def install(): http_lib.HTTPConnection = HTTP_WSGIInterceptor http_lib.HTTPSConnection = HTTPS_WSGIInterceptor def uninstall(): http_lib.HTTPConnection = OriginalHTTPConnection http_lib.HTTPSConnection = OriginalHTTPSConnection wsgi_intercept-1.4.1/wsgi_intercept/httplib2_intercept.py0000644000076500000240000000371212650437527024206 0ustar cdentstaff00000000000000"""Intercept HTTP connections that use `httplib2 `_. """ import sys from httplib2 import (SCHEME_TO_CONNECTION, HTTPConnectionWithTimeout, HTTPSConnectionWithTimeout) from . import (HTTPConnection, HTTPSConnection, WSGI_HTTPConnection, WSGI_HTTPSConnection) HTTPInterceptorMixin = WSGI_HTTPConnection HTTPSInterceptorMixin = WSGI_HTTPSConnection class HTTP_WSGIInterceptorWithTimeout(HTTPInterceptorMixin, HTTPConnectionWithTimeout): def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None, source_address=None): # In Python3 strict is deprecated if sys.version_info[0] < 3: HTTPConnection.__init__(self, host, port=port, strict=strict, timeout=timeout, source_address=source_address) else: HTTPConnection.__init__(self, host, port=port, timeout=timeout, source_address=source_address) class HTTPS_WSGIInterceptorWithTimeout(HTTPSInterceptorMixin, HTTPSConnectionWithTimeout): def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None, ca_certs=None, source_address=None, disable_ssl_certificate_validation=False): # ignore proxy_info and ca_certs # In Python3 strict is deprecated if sys.version_info[0] < 3: HTTPSConnection.__init__(self, host, port=port, strict=strict, timeout=timeout, source_address=source_address) else: HTTPSConnection.__init__(self, host, port=port, timeout=timeout, source_address=source_address) def install(): SCHEME_TO_CONNECTION['http'] = HTTP_WSGIInterceptorWithTimeout SCHEME_TO_CONNECTION['https'] = HTTPS_WSGIInterceptorWithTimeout def uninstall(): SCHEME_TO_CONNECTION['http'] = HTTPConnectionWithTimeout SCHEME_TO_CONNECTION['https'] = HTTPSConnectionWithTimeout wsgi_intercept-1.4.1/wsgi_intercept/interceptor.py0000644000076500000240000000670312766014771022742 0ustar cdentstaff00000000000000"""Context manager based WSGI interception. """ from importlib import import_module from uuid import uuid4 from six.moves.urllib import parse as urlparse import wsgi_intercept class Interceptor(object): """A convenience class over the guts of wsgi_intercept. An Interceptor subclass provides a clean entry point to the wsgi_intercept functionality in two ways: by encapsulating the interception addition and removal in methods and by providing a context manager that automates the process of addition and removal. Each Interceptor subclass is associated with a specific http library. Each class may be passed a url or a host and a port. If no args are passed a hostname will be automatically generated and the resulting url will be returned by the context manager. """ def __init__(self, app, host=None, port=80, prefix=None, url=None): assert app if (not host and not url): host = str(uuid4()) self.app = app if url: self._init_from_url(url) self.url = url else: self.host = host self.port = int(port) self.script_name = prefix or '' self.url = self._url_from_primitives() self._module = import_module('.%s' % self.MODULE_NAME, package='wsgi_intercept') def __enter__(self): self.install_intercept() return self.url def __exit__(self, exc_type, value, traceback): self.uninstall_intercept() def _url_from_primitives(self): if self.port == 443: scheme = 'https' else: scheme = 'http' if self.port and self.port not in [443, 80]: port = ':%s' % self.port else: port = '' netloc = self.host + port return urlparse.urlunsplit((scheme, netloc, self.script_name, None, None)) def _init_from_url(self, url): port = None parsed_url = urlparse.urlsplit(url) if ':' in parsed_url.netloc: host, port = parsed_url.netloc.split(':') else: host = parsed_url.netloc if not port: if parsed_url.scheme == 'https': port = 443 else: port = 80 path = parsed_url.path if path == '/' or not path: self.script_name = '' else: self.script_name = path self.host = host self.port = int(port) def install_intercept(self): self._module.install() wsgi_intercept.add_wsgi_intercept(self.host, self.port, self.app, script_name=self.script_name) def uninstall_intercept(self): wsgi_intercept.remove_wsgi_intercept(self.host, self.port) self._module.uninstall() class HttpClientInterceptor(Interceptor): """Interceptor for httplib and http.client.""" MODULE_NAME = 'http_client_intercept' class Httplib2Interceptor(Interceptor): """Interceptor for httplib2.""" MODULE_NAME = 'httplib2_intercept' class RequestsInterceptor(Interceptor): """Interceptor for requests.""" MODULE_NAME = 'requests_intercept' class Urllib3Interceptor(Interceptor): """Interceptor for requests.""" MODULE_NAME = 'urllib3_intercept' class UrllibInterceptor(Interceptor): """Interceptor for urllib2 and urllib.request.""" MODULE_NAME = 'urllib_intercept' wsgi_intercept-1.4.1/wsgi_intercept/requests_intercept.py0000644000076500000240000000111412673010314024305 0ustar cdentstaff00000000000000"""Intercept HTTP connections that use `requests `_. """ from requests.packages.urllib3.connectionpool import (HTTPConnectionPool, HTTPSConnectionPool) from requests.packages.urllib3.connection import (HTTPConnection, HTTPSConnection) from ._urllib3 import make_urllib3_override install, uninstall = make_urllib3_override(HTTPConnectionPool, HTTPSConnectionPool, HTTPConnection, HTTPSConnection) wsgi_intercept-1.4.1/wsgi_intercept/tests/0000755000076500000240000000000012772441264021164 5ustar cdentstaff00000000000000wsgi_intercept-1.4.1/wsgi_intercept/tests/__init__.py0000644000076500000240000000034612772437557023312 0ustar cdentstaff00000000000000import os import wsgi_intercept # Ensure that our test apps are sending strict headers. wsgi_intercept.STRICT_RESPONSE_HEADERS = True if os.environ.get('USER') == 'cdent': import warnings warnings.simplefilter('error') wsgi_intercept-1.4.1/wsgi_intercept/tests/install.py0000644000076500000240000000426012771214240023175 0ustar cdentstaff00000000000000import os import pytest import wsgi_intercept skipnetwork = pytest.mark.skipif(os.environ.get( 'WSGI_INTERCEPT_SKIP_NETWORK', 'False').lower() == 'true', reason="skip network requested" ) class BaseInstalledApp(object): def __init__(self, app, host, port=80, script_name='', install=None, uninstall=None, proxy=None): self.app = app self.host = host self.port = port self.script_name = script_name self._install = install or (lambda: None) self._uninstall = uninstall or (lambda: None) self._hits = 0 self._internals = {} self._proxy = proxy def __call__(self, environ, start_response): self._hits += 1 self._internals = environ return self.app(environ, start_response) def success(self): return self._hits > 0 def get_internals(self): return self._internals def install_wsgi_intercept(self): wsgi_intercept.add_wsgi_intercept( self.host, self.port, self.factory, script_name=self.script_name) def uninstall_wsgi_intercept(self): wsgi_intercept.remove_wsgi_intercept(self.host, self.port) def install(self): if self._proxy: os.environ['http_proxy'] = self._proxy self._install() self.install_wsgi_intercept() def uninstall(self): if self._proxy: del os.environ['http_proxy'] self.uninstall_wsgi_intercept() self._uninstall() def factory(self): return self def __enter__(self): self.install() return self def __exit__(self, *args, **kwargs): self.uninstall() def installer_class(module=None, install=None, uninstall=None): if module: install = install or getattr(module, 'install', None) uninstall = uninstall or getattr(module, 'uninstall', None) class InstalledApp(BaseInstalledApp): def __init__(self, app, host, port=80, script_name='', proxy=None): BaseInstalledApp.__init__( self, app=app, host=host, port=port, script_name=script_name, install=install, uninstall=uninstall, proxy=proxy) return InstalledApp wsgi_intercept-1.4.1/wsgi_intercept/tests/test_http_client.py0000644000076500000240000000537412771214240025112 0ustar cdentstaff00000000000000import py.test from wsgi_intercept import http_client_intercept, WSGIAppError from . import wsgi_app from .install import installer_class, skipnetwork try: import http.client as http_lib except ImportError: import httplib as http_lib HOST = 'some_hopefully_nonexistant_domain' InstalledApp = installer_class(http_client_intercept) def test_http(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80) as app: http_client = http_lib.HTTPConnection(HOST) http_client.request('GET', '/') content = http_client.getresponse().read() http_client.close() assert content == b'WSGI intercept successful!\n' assert app.success() def test_https(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: http_client = http_lib.HTTPSConnection(HOST) http_client.request('GET', '/') content = http_client.getresponse().read() http_client.close() assert content == b'WSGI intercept successful!\n' assert app.success() def test_other(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=8080) as app: http_client = http_lib.HTTPConnection(HOST + ':8080') http_client.request('GET', '/') content = http_client.getresponse().read() http_client.close() assert content == b'WSGI intercept successful!\n' assert app.success() def test_proxy_handling(): """Proxy variable no impact.""" with InstalledApp(wsgi_app.simple_app, host=HOST, port=80, proxy='some.host:1234') as app: http_client = http_lib.HTTPConnection(HOST) http_client.request('GET', '/') content = http_client.getresponse().read() http_client.close() assert content == b'WSGI intercept successful!\n' assert app.success() def test_app_error(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): http_client = http_lib.HTTPConnection(HOST) with py.test.raises(WSGIAppError): http_client.request('GET', '/') http_client.getresponse().read() http_client.close() @skipnetwork def test_http_not_intercepted(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): http_client = http_lib.HTTPConnection('google.com') http_client.request('GET', '/') response = http_client.getresponse() http_client.close() assert 200 <= int(response.status) < 400 @skipnetwork def test_https_not_intercepted(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=443): http_client = http_lib.HTTPSConnection('google.com') http_client.request('GET', '/') response = http_client.getresponse() http_client.close() assert 200 <= int(response.status) < 400 wsgi_intercept-1.4.1/wsgi_intercept/tests/test_httplib2.py0000644000076500000240000000537512771214240024326 0ustar cdentstaff00000000000000import py.test from wsgi_intercept import httplib2_intercept, WSGIAppError from . import wsgi_app from .install import installer_class import httplib2 from socket import gaierror HOST = 'some_hopefully_nonexistant_domain' InstalledApp = installer_class(httplib2_intercept) def test_http(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80) as app: http = httplib2.Http() resp, content = http.request( 'http://some_hopefully_nonexistant_domain:80/') assert content == b'WSGI intercept successful!\n' assert app.success() def test_http_default_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80) as app: http = httplib2.Http() resp, content = http.request( 'http://some_hopefully_nonexistant_domain/') assert content == b'WSGI intercept successful!\n' assert app.success() def test_http_other_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=8080) as app: http = httplib2.Http() resp, content = http.request( 'http://some_hopefully_nonexistant_domain:8080/') assert content == b'WSGI intercept successful!\n' assert app.success() environ = app.get_internals() assert environ['wsgi.url_scheme'] == 'http' def test_bogus_domain(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80): py.test.raises( gaierror, 'httplib2_intercept.HTTP_WSGIInterceptorWithTimeout(' '"_nonexistant_domain_").connect()') def test_proxy_handling(): """Proxy has no impact.""" with InstalledApp(wsgi_app.simple_app, host=HOST, port=80, proxy='some_proxy.com:1234') as app: http = httplib2.Http() resp, content = http.request( 'http://some_hopefully_nonexistant_domain:80/') assert content == b'WSGI intercept successful!\n' assert app.success() def test_https(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: http = httplib2.Http() resp, content = http.request( 'https://some_hopefully_nonexistant_domain:443/') assert app.success() def test_https_default_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: http = httplib2.Http() resp, content = http.request( 'https://some_hopefully_nonexistant_domain/') assert app.success() environ = app.get_internals() assert environ['wsgi.url_scheme'] == 'https' def test_app_error(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): http = httplib2.Http() with py.test.raises(WSGIAppError): http.request( 'http://some_hopefully_nonexistant_domain/') wsgi_intercept-1.4.1/wsgi_intercept/tests/test_interceptor.py0000644000076500000240000002064312771214240025127 0ustar cdentstaff00000000000000"""Tests of using the context manager style. The context manager is based on the InterceptFixture used in gabbi. """ import socket from uuid import uuid4 import py.test import requests import urllib3 from httplib2 import Http, ServerNotFoundError # don't use six as the monkey patching gets confused try: import http.client as http_client except ImportError: import httplib as http_client from six.moves.urllib.request import urlopen from six.moves.urllib.error import URLError from wsgi_intercept.interceptor import ( Interceptor, HttpClientInterceptor, Httplib2Interceptor, RequestsInterceptor, UrllibInterceptor, Urllib3Interceptor) from .wsgi_app import simple_app httppool = urllib3.PoolManager() def app(): return simple_app # Base def test_interceptor_instance(): hostname = str(uuid4()) port = 9999 interceptor = Httplib2Interceptor(app=app, host=hostname, port=port, prefix='/foobar') assert isinstance(interceptor, Interceptor) assert interceptor.app == app assert interceptor.host == hostname assert interceptor.port == port assert interceptor.script_name == '/foobar' assert interceptor.url == 'http://%s:%s/foobar' % (hostname, port) def test_intercept_by_url_no_port(): # Test for https://github.com/cdent/wsgi-intercept/issues/41 hostname = str(uuid4()) url = 'http://%s/foobar' % hostname interceptor = Httplib2Interceptor(app=app, url=url) assert isinstance(interceptor, Interceptor) assert interceptor.app == app assert interceptor.host == hostname assert interceptor.port == 80 assert interceptor.script_name == '/foobar' assert interceptor.url == url # http_lib def test_httpclient_interceptor_host(): hostname = str(uuid4()) port = 9999 with HttpClientInterceptor(app=app, host=hostname, port=port): client = http_client.HTTPConnection(hostname, port) client.request('GET', '/') response = client.getresponse() content = response.read().decode('utf-8') assert response.status == 200 assert 'WSGI intercept successful!' in content def test_httpclient_interceptor_url(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) with HttpClientInterceptor(app=app, url=url): client = http_client.HTTPConnection(hostname, port) client.request('GET', '/') response = client.getresponse() content = response.read().decode('utf-8') assert response.status == 200 assert 'WSGI intercept successful!' in content def test_httpclient_in_out(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) with HttpClientInterceptor(app=app, url=url): client = http_client.HTTPConnection(hostname, port) client.request('GET', '/') response = client.getresponse() content = response.read().decode('utf-8') assert response.status == 200 assert 'WSGI intercept successful!' in content # outside the context manager the intercept does not work with py.test.raises(socket.gaierror): client = http_client.HTTPConnection(hostname, port) client.request('GET', '/') # Httplib2 def test_httplib2_interceptor_host(): hostname = str(uuid4()) port = 9999 http = Http() with Httplib2Interceptor(app=app, host=hostname, port=port) as url: response, content = http.request(url) assert response.status == 200 assert 'WSGI intercept successful!' in content.decode('utf-8') def test_httplib2_interceptor_https_host(): hostname = str(uuid4()) port = 443 http = Http() with Httplib2Interceptor(app=app, host=hostname, port=port) as url: assert url == 'https://%s' % hostname response, content = http.request(url) assert response.status == 200 assert 'WSGI intercept successful!' in content.decode('utf-8') def test_httplib2_interceptor_no_host(): # no hostname or port, one will be generated automatically # we never actually know what it is http = Http() with Httplib2Interceptor(app=app) as url: response, content = http.request(url) assert response.status == 200 assert 'WSGI intercept successful!' in content.decode('utf-8') def test_httplib2_interceptor_url(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) http = Http() with Httplib2Interceptor(app=app, url=url) as target_url: response, content = http.request(target_url) assert response.status == 200 assert 'WSGI intercept successful!' in content.decode('utf-8') def test_httplib2_in_out(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) http = Http() with Httplib2Interceptor(app=app, url=url) as target_url: response, content = http.request(target_url) assert response.status == 200 assert 'WSGI intercept successful!' in content.decode('utf-8') # outside the context manager the intercept does not work with py.test.raises(ServerNotFoundError): http.request(url) # Requests def test_requests_interceptor_host(): hostname = str(uuid4()) port = 9999 with RequestsInterceptor(app=app, host=hostname, port=port) as url: response = requests.get(url) assert response.status_code == 200 assert 'WSGI intercept successful!' in response.text def test_requests_interceptor_url(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) with RequestsInterceptor(app=app, url=url) as target_url: response = requests.get(target_url) assert response.status_code == 200 assert 'WSGI intercept successful!' in response.text def test_requests_in_out(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) with RequestsInterceptor(app=app, url=url) as target_url: response = requests.get(target_url) assert response.status_code == 200 assert 'WSGI intercept successful!' in response.text # outside the context manager the intercept does not work with py.test.raises(requests.ConnectionError): requests.get(url) # urllib3 def test_urllib3_interceptor_host(): hostname = str(uuid4()) port = 9999 with Urllib3Interceptor(app=app, host=hostname, port=port) as url: response = httppool.request('GET', url) assert response.status == 200 assert 'WSGI intercept successful!' in str(response.data) def test_urllib3_interceptor_url(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) with Urllib3Interceptor(app=app, url=url) as target_url: response = httppool.request('GET', target_url) assert response.status == 200 assert 'WSGI intercept successful!' in str(response.data) def test_urllib3_in_out(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) with Urllib3Interceptor(app=app, url=url) as target_url: response = httppool.request('GET', target_url) assert response.status == 200 assert 'WSGI intercept successful!' in str(response.data) # outside the context manager the intercept does not work with py.test.raises(urllib3.exceptions.ProtocolError): httppool.request('GET', url, retries=False) # urllib def test_urllib_interceptor_host(): hostname = str(uuid4()) port = 9999 with UrllibInterceptor(app=app, host=hostname, port=port) as url: response = urlopen(url) assert response.code == 200 assert 'WSGI intercept successful!' in response.read().decode('utf-8') def test_urllib_interceptor_url(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) with UrllibInterceptor(app=app, url=url) as target_url: response = urlopen(target_url) assert response.code == 200 assert 'WSGI intercept successful!' in response.read().decode('utf-8') def test_urllib_in_out(): hostname = str(uuid4()) port = 9999 url = 'http://%s:%s/' % (hostname, port) with UrllibInterceptor(app=app, url=url) as target_url: response = urlopen(target_url) assert response.code == 200 assert 'WSGI intercept successful!' in response.read().decode('utf-8') # outside the context manager the intercept does not work with py.test.raises(URLError): urlopen(url) wsgi_intercept-1.4.1/wsgi_intercept/tests/test_module_interceptor.py0000644000076500000240000000163612771214240026475 0ustar cdentstaff00000000000000"""Test intercepting a full module with interceptor.""" from uuid import uuid4 from httplib2 import Http from wsgi_intercept.interceptor import Httplib2Interceptor from .wsgi_app import simple_app def app(): return simple_app def setup_module(module): module.host = str(uuid4()) module.intercept = Httplib2Interceptor(app, host=module.host) module.intercept.install_intercept() def teardown_module(module): module.intercept.uninstall_intercept() def test_simple_request(): global host http = Http() response, content = http.request('http://%s/' % host) assert response.status == 200 assert 'WSGI intercept successful!' in content.decode('utf-8') def test_another_request(): global host http = Http() response, content = http.request('http://%s/foobar' % host) assert response.status == 200 assert 'WSGI intercept successful!' in content.decode('utf-8') wsgi_intercept-1.4.1/wsgi_intercept/tests/test_requests.py0000644000076500000240000000623212771214240024442 0ustar cdentstaff00000000000000import os import py.test from wsgi_intercept import requests_intercept, WSGIAppError from . import wsgi_app from .install import installer_class, skipnetwork import requests from requests.exceptions import ConnectionError HOST = 'some_hopefully_nonexistant_domain' InstalledApp = installer_class(requests_intercept) def test_http(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80) as app: resp = requests.get('http://some_hopefully_nonexistant_domain:80/') assert resp.content == b'WSGI intercept successful!\n' assert app.success() def test_http_default_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80) as app: resp = requests.get('http://some_hopefully_nonexistant_domain/') assert resp.content == b'WSGI intercept successful!\n' assert app.success() def test_http_other_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=8080) as app: resp = requests.get('http://some_hopefully_nonexistant_domain:8080/') assert resp.content == b'WSGI intercept successful!\n' assert app.success() environ = app.get_internals() assert environ['wsgi.url_scheme'] == 'http' def test_bogus_domain(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80): py.test.raises( ConnectionError, 'requests.get("http://_nonexistant_domain_")') def test_proxy_handling(): with py.test.raises(RuntimeError) as exc: with InstalledApp(wsgi_app.simple_app, host=HOST, port=80, proxy='some_proxy.com:1234'): requests.get('http://some_hopefully_nonexistant_domain:80/') assert 'http_proxy or https_proxy set in environment' in str(exc.value) # We need to do this by hand because the exception was raised # during the entry of the context manager, so the exit handler # wasn't reached. del os.environ['http_proxy'] def test_https(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: resp = requests.get('https://some_hopefully_nonexistant_domain:443/') assert resp.content == b'WSGI intercept successful!\n' assert app.success() def test_https_default_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: resp = requests.get('https://some_hopefully_nonexistant_domain/') assert resp.content == b'WSGI intercept successful!\n' assert app.success() environ = app.get_internals() assert environ['wsgi.url_scheme'] == 'https' def test_app_error(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): with py.test.raises(WSGIAppError): requests.get('http://some_hopefully_nonexistant_domain/') @skipnetwork def test_http_not_intercepted(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): resp = requests.get("http://google.com") assert resp.status_code >= 200 and resp.status_code < 300 @skipnetwork def test_https_not_intercepted(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): resp = requests.get("https://google.com") assert resp.status_code >= 200 and resp.status_code < 300 wsgi_intercept-1.4.1/wsgi_intercept/tests/test_response_headers.py0000644000076500000240000000513512772437557026144 0ustar cdentstaff00000000000000"""Test response header validations. Response headers are supposed to be bytestrings and some servers, notably will experience an error if they are given headers with the wrong form. Since wsgi-intercept is standing in as a server, it should behave like one on this front. At the moment it does not. There are tests for how it delivers request headers, but not the other way round. Let's write some tests to fix that. """ import py.test import requests import six import wsgi_intercept from wsgi_intercept.interceptor import RequestsInterceptor class HeaderApp(object): """A simple app that returns whatever headers we give it.""" def __init__(self, headers): self.headers = headers def __call__(self, environ, start_response): headers = [] for header in self.headers: headers.append((header, self.headers[header])) start_response('200 OK', headers) return [''] def app(headers): return HeaderApp(headers) def test_header_app(): """Make sure the header apps returns headers. Many libraries normalize headers to strings so we're not going to get exact matches. """ header_value = 'alpha' header_value_str = 'alpha' def header_app(): return app({'request-id': header_value}) with RequestsInterceptor(header_app) as url: response = requests.get(url) assert response.headers['request-id'] == header_value_str def test_encoding_violation(): """If the header is unicode we expect boom.""" header_key = 'request-id' if six.PY2: header_value = u'alpha' else: header_value = b'alpha' # we expect our http library to give us a str returned_header = 'alpha' def header_app(): return app({header_key: header_value}) # save original strict_response_headers = wsgi_intercept.STRICT_RESPONSE_HEADERS # With STRICT_RESPONSE_HEADERS True, response headers must be # native str. with RequestsInterceptor(header_app) as url: wsgi_intercept.STRICT_RESPONSE_HEADERS = True with py.test.raises(TypeError) as error: response = requests.get(url) assert (str(error.value) == "Header has a key '%s' or value '%s' " "which is not a native str." % (header_key, header_value)) # When False, other types of strings are okay. wsgi_intercept.STRICT_RESPONSE_HEADERS = False response = requests.get(url) assert response.headers['request-id'] == returned_header # reset back to saved original wsgi_intercept.STRICT_RESPONSE_HEADERS = \ strict_response_headers wsgi_intercept-1.4.1/wsgi_intercept/tests/test_urllib.py0000644000076500000240000000533712771214240024065 0ustar cdentstaff00000000000000import os import py.test from wsgi_intercept import urllib_intercept, WSGIAppError from . import wsgi_app from .install import installer_class, skipnetwork try: import urllib.request as url_lib except ImportError: import urllib2 as url_lib HOST = 'some_hopefully_nonexistant_domain' InstalledApp = installer_class(install=urllib_intercept.install_opener) def test_http(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80) as app: url_lib.urlopen('http://some_hopefully_nonexistant_domain:80/') assert app.success() def test_http_default_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80) as app: url_lib.urlopen('http://some_hopefully_nonexistant_domain/') assert app.success() def test_http_other_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=8080) as app: url_lib.urlopen('http://some_hopefully_nonexistant_domain:8080/') assert app.success() environ = app.get_internals() assert environ['wsgi.url_scheme'] == 'http' def test_proxy_handling(): """Like requests, urllib gets confused about proxy early on.""" with py.test.raises(RuntimeError) as exc: with InstalledApp(wsgi_app.simple_app, host=HOST, port=80, proxy='some.host:1234'): url_lib.urlopen('http://some_hopefully_nonexistant_domain:80/') assert 'http_proxy or https_proxy set in environment' in str(exc.value) # We need to do this by hand because the exception was raised # during the entry of the context manager, so the exit handler # wasn't reached. del os.environ['http_proxy'] def test_https(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: url_lib.urlopen('https://some_hopefully_nonexistant_domain:443/') assert app.success() def test_https_default_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: url_lib.urlopen('https://some_hopefully_nonexistant_domain/') assert app.success() environ = app.get_internals() assert environ['wsgi.url_scheme'] == 'https' def test_app_error(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): with py.test.raises(WSGIAppError): url_lib.urlopen('http://some_hopefully_nonexistant_domain/') @skipnetwork def test_http_not_intercepted(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80): response = url_lib.urlopen('http://google.com/') assert 200 <= int(response.code) < 400 @skipnetwork def test_https_not_intercepted(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443): response = url_lib.urlopen('https://google.com/') assert 200 <= int(response.code) < 400 wsgi_intercept-1.4.1/wsgi_intercept/tests/test_urllib3.py0000644000076500000240000000641212771214240024143 0ustar cdentstaff00000000000000import os import py.test from wsgi_intercept import urllib3_intercept, WSGIAppError from . import wsgi_app from .install import installer_class, skipnetwork import urllib3 HOST = 'some_hopefully_nonexistant_domain' InstalledApp = installer_class(urllib3_intercept) http = urllib3.PoolManager() def test_http(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80) as app: resp = http.request( 'GET', 'http://some_hopefully_nonexistant_domain:80/') assert resp.data == b'WSGI intercept successful!\n' assert app.success() def test_http_default_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80) as app: resp = http.request('GET', 'http://some_hopefully_nonexistant_domain/') assert resp.data == b'WSGI intercept successful!\n' assert app.success() def test_http_other_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=8080) as app: resp = http.request( 'GET', 'http://some_hopefully_nonexistant_domain:8080/') assert resp.data == b'WSGI intercept successful!\n' assert app.success() environ = app.get_internals() assert environ['wsgi.url_scheme'] == 'http' def test_bogus_domain(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=80): py.test.raises( urllib3.exceptions.ProtocolError, 'http.request("GET", "http://_nonexistant_domain_", ' 'retries=False)') def test_proxy_handling(): with py.test.raises(RuntimeError) as exc: with InstalledApp(wsgi_app.simple_app, host=HOST, port=80, proxy='some_proxy.com:1234'): http.request('GET', 'http://some_hopefully_nonexistant_domain:80/') assert 'http_proxy or https_proxy set in environment' in str(exc.value) # We need to do this by hand because the exception was raised # during the entry of the context manager, so the exit handler # wasn't reached. del os.environ['http_proxy'] def test_https(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: resp = http.request( 'GET', 'https://some_hopefully_nonexistant_domain:443/') assert resp.data == b'WSGI intercept successful!\n' assert app.success() def test_https_default_port(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: resp = http.request( 'GET', 'https://some_hopefully_nonexistant_domain/') assert resp.data == b'WSGI intercept successful!\n' assert app.success() environ = app.get_internals() assert environ['wsgi.url_scheme'] == 'https' def test_app_error(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): with py.test.raises(WSGIAppError): http.request('GET', 'http://some_hopefully_nonexistant_domain/') @skipnetwork def test_http_not_intercepted(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): resp = http.request('GET', 'http://google.com') assert resp.status >= 200 and resp.status < 300 @skipnetwork def test_https_not_intercepted(): with InstalledApp(wsgi_app.raises_app, host=HOST, port=80): resp = http.request('GET', 'https://google.com') assert resp.status >= 200 and resp.status < 300 wsgi_intercept-1.4.1/wsgi_intercept/tests/test_wsgi_compliance.py0000644000076500000240000001007512771214240025732 0ustar cdentstaff00000000000000import sys import py.test try: from urllib.parse import unquote except ImportError: from urllib import unquote from wsgi_intercept import httplib2_intercept from . import wsgi_app from .install import installer_class import httplib2 HOST = 'some_hopefully_nonexistant_domain' InstalledApp = installer_class(httplib2_intercept) def test_simple_override(): with InstalledApp(wsgi_app.simple_app, host=HOST) as app: http = httplib2.Http() resp, content = http.request( 'http://some_hopefully_nonexistant_domain:80/', 'GET') assert app.success() def test_simple_override_default_port(): with InstalledApp(wsgi_app.simple_app, host=HOST) as app: http = httplib2.Http() resp, content = http.request( 'http://some_hopefully_nonexistant_domain/', 'GET') assert app.success() def test_https_in_environ(): with InstalledApp(wsgi_app.simple_app, host=HOST, port=443) as app: http = httplib2.Http() resp, content = http.request( 'https://some_hopefully_nonexistant_domain/', 'GET') assert app.success() internal_env = app.get_internals() assert internal_env['wsgi.url_scheme'] == 'https' def test_more_interesting(): expected_uri = ('/%E4%B8%96%E4%B8%8A%E5%8E%9F%E4%BE%86%E9%82%84%E6' '%9C%89%E3%80%8C%E7%BE%9A%E7%89%9B%E3%80%8D%E9%80%99' '%E7%A8%AE%E5%8B%95%E7%89%A9%EF%BC%81%2Fbarney' '?bar=baz%20zoom') with InstalledApp(wsgi_app.more_interesting_app, host=HOST) as app: http = httplib2.Http() resp, content = http.request( 'http://some_hopefully_nonexistant_domain' + expected_uri, 'GET', headers={'Accept': 'application/json', 'Cookie': 'foo=bar'}) internal_env = app.get_internals() expected_path_info = unquote(expected_uri.split('?')[0]) assert internal_env['REQUEST_URI'] == expected_uri assert internal_env['RAW_URI'] == expected_uri assert internal_env['QUERY_STRING'] == 'bar=baz%20zoom' assert internal_env['HTTP_ACCEPT'] == 'application/json' assert internal_env['HTTP_COOKIE'] == 'foo=bar' # In this test we are ensuring the value, in the environ, of # a request header has a value which is a str, as native to # that version of Python. That means always a str, despite # the fact that a str in Python 2 and 3 are different # things! PEP 3333 requires this. isinstance is not used to # avoid confusion over class hierarchies. assert type(internal_env['HTTP_COOKIE']) == type('') # noqa E721 # Do the rather painful wsgi encoding dance. if sys.version_info[0] > 2: assert internal_env['PATH_INFO'].encode('latin-1').decode( 'UTF-8') == expected_path_info else: assert internal_env['PATH_INFO'].decode( 'UTF-8') == expected_path_info.decode('UTF-8') def test_script_name(): with InstalledApp(wsgi_app.more_interesting_app, host=HOST, script_name='/funky') as app: http = httplib2.Http() response, content = http.request( 'http://some_hopefully_nonexistant_domain/funky/boom/baz') internal_env = app.get_internals() assert internal_env['SCRIPT_NAME'] == '/funky' assert internal_env['PATH_INFO'] == '/boom/baz' def test_encoding_errors(): with InstalledApp(wsgi_app.more_interesting_app, host=HOST): http = httplib2.Http() with py.test.raises(UnicodeEncodeError): response, content = http.request( 'http://some_hopefully_nonexistant_domain/boom/baz', headers={'Accept': u'application/\u2603'}) def test_post_status_headers(): with InstalledApp(wsgi_app.post_status_headers_app, host=HOST) as app: http = httplib2.Http() resp, content = http.request( 'http://some_hopefully_nonexistant_domain/', 'GET') assert app.success() assert resp.get('content-type') == 'text/plain' wsgi_intercept-1.4.1/wsgi_intercept/tests/wsgi_app.py0000644000076500000240000000146712772435511023355 0ustar cdentstaff00000000000000""" Simple WSGI applications for testing. """ from pprint import pformat try: bytes except ImportError: bytes = str def simple_app(environ, start_response): """Simplest possible application object""" status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return [b'WSGI intercept successful!\n'] def more_interesting_app(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return [pformat(environ).encode('utf-8')] def post_status_headers_app(environ, start_response): headers = [] start_response('200 OK', headers) headers.append(('Content-type', 'text/plain')) return [b'WSGI intercept successful!\n'] def raises_app(environ, start_response): raise TypeError("bah") wsgi_intercept-1.4.1/wsgi_intercept/urllib3_intercept.py0000644000076500000240000000101112673010314024002 0ustar cdentstaff00000000000000"""Intercept HTTP connections that use `urllib3 `_. """ from urllib3.connectionpool import HTTPConnectionPool, HTTPSConnectionPool from urllib3.connection import HTTPConnection, HTTPSConnection from ._urllib3 import make_urllib3_override install, uninstall = make_urllib3_override(HTTPConnectionPool, HTTPSConnectionPool, HTTPConnection, HTTPSConnection) wsgi_intercept-1.4.1/wsgi_intercept/urllib_intercept.py0000644000076500000240000000243512650437571023747 0ustar cdentstaff00000000000000"""Intercept HTTP connections that use urllib.request (Python 3) aka urllib2 (Python 2). """ import os try: import urllib.request as url_lib except ImportError: import urllib2 as url_lib from . import WSGI_HTTPConnection, WSGI_HTTPSConnection class WSGI_HTTPHandler(url_lib.HTTPHandler): """ Override the default HTTPHandler class with one that uses the WSGI_HTTPConnection class to open HTTP URLs. """ def http_open(self, req): return self.do_open(WSGI_HTTPConnection, req) class WSGI_HTTPSHandler(url_lib.HTTPSHandler): """ Override the default HTTPSHandler class with one that uses the WSGI_HTTPConnection class to open HTTPS URLs. """ def https_open(self, req): return self.do_open(WSGI_HTTPSConnection, req) def install_opener(): if 'http_proxy' in os.environ or 'https_proxy' in os.environ: raise RuntimeError( 'http_proxy or https_proxy set in environment, please unset') handlers = [WSGI_HTTPHandler()] if WSGI_HTTPSHandler is not None: handlers.append(WSGI_HTTPSHandler()) opener = url_lib.build_opener(*handlers) url_lib.install_opener(opener) return opener def uninstall_opener(): url_lib.install_opener(None) install = install_opener uninstall = uninstall_opener wsgi_intercept-1.4.1/wsgi_intercept.egg-info/0000755000076500000240000000000012772441264021514 5ustar cdentstaff00000000000000wsgi_intercept-1.4.1/wsgi_intercept.egg-info/dependency_links.txt0000644000076500000240000000000112772441263025561 0ustar cdentstaff00000000000000 wsgi_intercept-1.4.1/wsgi_intercept.egg-info/PKG-INFO0000644000076500000240000001600712772441263022614 0ustar cdentstaff00000000000000Metadata-Version: 1.1 Name: wsgi-intercept Version: 1.4.1 Summary: wsgi_intercept installs a WSGI application in place of a real URI for testing. Home-page: http://pypi.python.org/pypi/wsgi_intercept Author: Titus Brown, Kumar McMillan, Chris Dent, Sasha Hart Author-email: cdent@peermore.com License: MIT License Description: Installs a WSGI application in place of a real host for testing. Introduction ============ Testing a WSGI application sometimes involves starting a server at a local host and port, then pointing your test code to that address. Instead, this library lets you intercept calls to any specific host/port combination and redirect them into a `WSGI application`_ importable by your test program. Thus, you can avoid spawning multiple processes or threads to test your Web app. Supported Libaries ================== ``wsgi_intercept`` works with a variety of HTTP clients in Python 2.7, 3.3 and beyond, and in pypy. * urllib2 * urllib.request * httplib * http.client * httplib2 * requests * urllib3 How Does It Work? ================= ``wsgi_intercept`` works by replacing ``httplib.HTTPConnection`` with a subclass, ``wsgi_intercept.WSGI_HTTPConnection``. This class then redirects specific server/port combinations into a WSGI application by emulating a socket. If no intercept is registered for the host and port requested, those requests are passed on to the standard handler. The easiest way to use an intercept is to import an appropriate subclass of ``~wsgi_intercept.interceptor.Interceptor`` and use that as a context manager over web requests that use the library associated with the subclass. For example:: import httplib2 from wsgi_intercept.interceptor import Httplib2Interceptor from mywsgiapp import app def load_app(): return app http = httplib2.Http() with Httplib2Interceptor(load_app, host='example.com', port=80) as url: response, content = http.request('%s%s' % (url, '/path')) assert response.status == 200 The interceptor class may aslo be used directly to install intercepts. See the module documentation for more information. Older versions required that the functions ``add_wsgi_intercept(host, port, app_create_fn, script_name='')`` and ``remove_wsgi_intercept(host,port)`` be used to specify which URLs should be redirected into what applications. These methods are still available, but the ``Interceptor`` classes are likely easier to use for most use cases. .. note:: ``app_create_fn`` is a *function object* returning a WSGI application; ``script_name`` becomes ``SCRIPT_NAME`` in the WSGI app's environment, if set. .. note:: If ``http_proxy`` or ``https_proxy`` is set in the environment this can cause difficulties with some of the intercepted libraries. If requests or urllib is being used, these will raise an exception if one of those variables is set. .. note:: If ``wsgi_intercept.STRICT_RESPONSE_HEADERS`` is set to ``True`` then response headers sent by an application will be checked to make sure they are of the type ``str`` native to the version of Python, as required by pep 3333. The default is ``False`` (to preserve backwards compatibility) Install ======= :: pip install -U wsgi_intercept Packages Intercepted ==================== Unfortunately each of the HTTP client libraries use their own specific mechanism for making HTTP call-outs, so individual implementations are needed. At this time there are implementations for ``httplib2``, ``urllib3`` and ``requests`` in both Python 2 and 3, ``urllib2`` and ``httplib`` in Python 2 and ``urllib.request`` and ``http.client`` in Python 3. If you are using Python 2 and need support for a different HTTP client, require a version of ``wsgi_intercept<0.6``. Earlier versions include support for ``webtest``, ``webunit`` and ``zope.testbrowser``. The best way to figure out how to use interception is to inspect `the tests`_. More comprehensive documentation available upon request. .. _the tests: https://github.com/cdent/wsgi-intercept/tree/master/test History ======= Pursuant to Ian Bicking's `"best Web testing framework"`_ post, Titus Brown put together an `in-process HTTP-to-WSGI interception mechanism`_ for his own Web testing system, twill. Because the mechanism is pretty generic -- it works at the httplib level -- Titus decided to try adding it into all of the *other* Python Web testing frameworks. The Python 2 version of wsgi-intercept was the result. Kumar McMillan later took over maintenance. The current version is tested with Python 2.7, 3.3, 3.4, 3.5 and pypy and was assembled by `Chris Dent`_. Testing and documentation improvements from `Sasha Hart`_. .. _"best Web testing framework": http://blog.ianbicking.org/best-of-the-web-app-test-frameworks.html .. _in-process HTTP-to-WSGI interception mechanism: http://www.advogato.org/person/titus/diary.html?start=119 .. _WSGI application: http://www.python.org/peps/pep-3333.html .. _Chris Dent: https://github.com/cdent .. _Sasha Hart: https://github.com/sashahart Project Home ============ This project lives on `GitHub`_. Please submit all bugs, patches, failing tests, et cetera using the Issue Tracker. Additional documentation is available on `Read The Docs`_. .. _GitHub: http://github.com/cdent/wsgi-intercept .. _Read The Docs: http://wsgi-intercept.readthedocs.org/en/latest/ Platform: UNKNOWN Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Topic :: Internet :: WWW/HTTP :: WSGI Classifier: Topic :: Software Development :: Testing wsgi_intercept-1.4.1/wsgi_intercept.egg-info/requires.txt0000644000076500000240000000012312772441263024107 0ustar cdentstaff00000000000000six [docs] sphinx [testing] pytest>=2.4 httplib2 requests>=2.0.1 urllib3>=1.11.0 wsgi_intercept-1.4.1/wsgi_intercept.egg-info/SOURCES.txt0000644000076500000240000000226012772441264023400 0ustar cdentstaff00000000000000LICENSE MANIFEST.in Makefile README setup.cfg setup.py docs/.gitignore docs/Makefile docs/conf.py docs/http_client.rst docs/httplib2.rst docs/index.rst docs/interceptor.rst docs/requests.rst docs/urllib.rst docs/urllib3.rst docs/_static/.gitignore docs/_templates/.gitignore wsgi_intercept/__init__.py wsgi_intercept/_urllib3.py wsgi_intercept/http_client_intercept.py wsgi_intercept/httplib2_intercept.py wsgi_intercept/interceptor.py wsgi_intercept/requests_intercept.py wsgi_intercept/urllib3_intercept.py wsgi_intercept/urllib_intercept.py wsgi_intercept.egg-info/PKG-INFO wsgi_intercept.egg-info/SOURCES.txt wsgi_intercept.egg-info/dependency_links.txt wsgi_intercept.egg-info/requires.txt wsgi_intercept.egg-info/top_level.txt wsgi_intercept/tests/__init__.py wsgi_intercept/tests/install.py wsgi_intercept/tests/test_http_client.py wsgi_intercept/tests/test_httplib2.py wsgi_intercept/tests/test_interceptor.py wsgi_intercept/tests/test_module_interceptor.py wsgi_intercept/tests/test_requests.py wsgi_intercept/tests/test_response_headers.py wsgi_intercept/tests/test_urllib.py wsgi_intercept/tests/test_urllib3.py wsgi_intercept/tests/test_wsgi_compliance.py wsgi_intercept/tests/wsgi_app.pywsgi_intercept-1.4.1/wsgi_intercept.egg-info/top_level.txt0000644000076500000240000000001712772441263024243 0ustar cdentstaff00000000000000wsgi_intercept