pytest-flask-0.14.0/0000775000175100017510000000000013363327364015364 5ustar jenkinsjenkins00000000000000pytest-flask-0.14.0/PKG-INFO0000664000175100017510000001105113363327364016457 0ustar jenkinsjenkins00000000000000Metadata-Version: 2.1 Name: pytest-flask Version: 0.14.0 Summary: A set of py.test fixtures to test Flask applications. Home-page: https://github.com/vitalk/pytest-flask Author: Vital Kudzelka Author-email: vital.kudzelka@gmail.com License: MIT Project-URL: Tracker, https://github.com/pytest-dev/pytest-flask/issues Project-URL: Source, https://github.com/pytest-dev/pytest-flask Description: pytest-flask ============ A set of `pytest `_ fixtures to test Flask extensions and applications. Features -------- Plugin provides some fixtures to simplify app testing: - ``client`` - an instance of ``app.test_client``, - ``client_class`` - ``client`` fixture for class-based tests, - ``config`` - the application config, - ``live_server`` - runs an application in the background (useful for tests with `Selenium `_ and other headless browsers), - ``request_ctx`` - the request context, - ``accept_json``, ``accept_jsonp``, ``accept_any`` - accept headers suitable to use as parameters in ``client``. To pass options to your application use the ``pytest.mark.options`` marker: .. code:: python @pytest.mark.options(debug=False) def test_app(app): assert not app.debug, 'Ensure the app not in debug mode' During tests execution the request context has been pushed, e.g. ``url_for``, ``session`` and other context bound objects are available without context managers: .. code:: python def test_app(client): assert client.get(url_for('myview')).status_code == 200 Response object has a ``json`` property to test a view that returns a JSON response: .. code:: python @api.route('/ping') def ping(): return jsonify(ping='pong') def test_api_ping(client): res = client.get(url_for('api.ping')) assert res.json == {'ping': 'pong'} If you want your tests done via Selenium or other headless browser use the ``live_server`` fixture. The server’s URL can be retrieved using the ``url_for`` function: .. code:: python from flask import url_for @pytest.mark.usefixtures('live_server') class TestLiveServer: def test_server_is_up_and_running(self): res = urllib2.urlopen(url_for('index', _external=True)) assert b'OK' in res.read() assert res.code == 200 Quick Start ----------- To start using a plugin define your application fixture in ``conftest.py``: .. code:: python from myapp import create_app @pytest.fixture def app(): app = create_app() return app Install the extension with dependencies and run your test suite: .. code:: bash $ pip install pytest-flask $ py.test Documentation ------------- The latest documentation is available at http://pytest-flask.readthedocs.org/en/latest/. Contributing ------------ Don’t hesitate to create a `GitHub issue `_ for any **bug** or **suggestion**. Keywords: pytest flask testing Platform: any Classifier: Development Status :: 4 - Beta Classifier: Environment :: Plugins Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Software Development :: Testing Classifier: Topic :: Software Development :: Libraries :: Python Modules Provides-Extra: tests Provides-Extra: docs pytest-flask-0.14.0/.gitignore0000664000175100017510000000043413363327112017344 0ustar jenkinsjenkins00000000000000# Python bytecode / optimized files *.py[co] *.egg-info build sdist __pycache__/ # virtualenv venv/ # Sphinx documentation docs/_build # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .pytest_cache/ .eggs/ coverage.xml tests/junit.xml pytest_flask/_version.py pytest-flask-0.14.0/tests/0000775000175100017510000000000013363327364016526 5ustar jenkinsjenkins00000000000000pytest-flask-0.14.0/tests/test_fixtures.py0000775000175100017510000000452113363327112022004 0ustar jenkinsjenkins00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from flask import request, url_for class TestFixtures: def test_config_access(self, config): assert config['SECRET_KEY'] == '42' def test_client(self, client): assert client.get(url_for('ping')).status == '200 OK' def test_accept_json(self, accept_json): assert accept_json == [('Accept', 'application/json')] def test_accept_jsonp(self, accept_jsonp): assert accept_jsonp == [('Accept', 'application/json-p')] def test_request_ctx(self, app, request_ctx): assert request_ctx.app is app def test_request_ctx_is_kept_around(self, client): client.get(url_for('index'), headers=[('X-Something', '42')]) assert request.headers['X-Something'] == '42' class TestJSONResponse: def test_json_response(self, client, accept_json): res = client.get(url_for('ping'), headers=accept_json) assert res.json == {'ping': 'pong'} def test_json_response_compare_to_status_code(self, client, accept_json): assert client.get(url_for('ping'), headers=accept_json) == 200 assert client.get('fake-route', headers=accept_json) == 404 assert client.get('fake-route', headers=accept_json) != '404' res = client.get(url_for('ping'), headers=accept_json) assert res == res def test_mismatching_eq_comparison(self, client, accept_json): with pytest.raises(AssertionError, match=r'Mismatch in status code'): assert client.get('fake-route', headers=accept_json) == 200 with pytest.raises(AssertionError, match=r'404 NOT FOUND'): assert client.get('fake-route', headers=accept_json) == '200' def test_dont_rewrite_existing_implementation(self, app, accept_json): class MyResponse(app.response_class): @property def json(self): """What is the meaning of life, the universe and everything?""" return 42 app.response_class = MyResponse client = app.test_client() res = client.get(url_for('ping'), headers=accept_json) assert res.json == 42 @pytest.mark.usefixtures('client_class') class TestClientClass: def test_client_attribute(self): assert hasattr(self, 'client') assert self.client.get(url_for('ping')).json == {'ping': 'pong'} pytest-flask-0.14.0/tests/conftest.py0000775000175100017510000000172013363327061020722 0ustar jenkinsjenkins00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from textwrap import dedent from flask import Flask, jsonify pytest_plugins = 'pytester' @pytest.fixture def app(): app = Flask(__name__) app.config['SECRET_KEY'] = '42' @app.route('/') def index(): return app.response_class('OK') @app.route('/ping') def ping(): return jsonify(ping='pong') return app @pytest.fixture def appdir(testdir): app_root = testdir.tmpdir test_root = app_root.mkdir('tests') def create_test_module(code, filename='test_app.py'): f = test_root.join(filename) f.write(dedent(code), ensure=True) return f testdir.create_test_module = create_test_module testdir.create_test_module(''' import pytest from flask import Flask @pytest.fixture def app(): app = Flask(__name__) return app ''', filename='conftest.py') return testdir pytest-flask-0.14.0/tests/test_markers.py0000775000175100017510000000113613363327061021601 0ustar jenkinsjenkins00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from flask import Flask @pytest.fixture(scope='session') def app(): app = Flask(__name__) app.config['SECRET_KEY'] = '42' return app class TestOptionMarker: @pytest.mark.options(debug=False) def test_not_debug_app(self, app): assert not app.debug, 'Ensure the app not in debug mode' @pytest.mark.options(foo=42) def test_update_application_config(self, request, app, config): assert config['FOO'] == 42 def test_application_config_teardown(self, config): assert 'FOO' not in config pytest-flask-0.14.0/tests/test_live_server.py0000775000175100017510000001471613363327112022467 0ustar jenkinsjenkins00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import os import pytest try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen from flask import url_for pytestmark = pytest.mark.skipif(not hasattr(os, 'fork'), reason='needs fork') class TestLiveServer: def test_server_is_alive(self, live_server): assert live_server._process assert live_server._process.is_alive() def test_server_url(self, live_server): assert live_server.url() == 'http://localhost:%d' % live_server.port assert live_server.url('/ping') == \ 'http://localhost:%d/ping' % live_server.port def test_server_listening(self, live_server): res = urlopen(live_server.url('/ping')) assert res.code == 200 assert b'pong' in res.read() def test_url_for(self, live_server): assert url_for('ping', _external=True) == \ 'http://localhost:%s/ping' % live_server.port def test_set_application_server_name(self, live_server): assert live_server.app.config['SERVER_NAME'] == \ 'localhost:%d' % live_server.port @pytest.mark.options(server_name='example.com:5000') def test_rewrite_application_server_name(self, live_server): assert live_server.app.config['SERVER_NAME'] == \ 'example.com:%d' % live_server.port def test_prevent_starting_live_server(self, appdir): appdir.create_test_module(''' import pytest def test_a(live_server): assert live_server._process is None ''') result = appdir.runpytest('-v', '--no-start-live-server') result.stdout.fnmatch_lines(['*PASSED*']) assert result.ret == 0 def test_start_live_server(self, appdir): appdir.create_test_module(''' import pytest def test_a(live_server): assert live_server._process assert live_server._process.is_alive() ''') result = appdir.runpytest('-v', '--start-live-server') result.stdout.fnmatch_lines(['*PASSED*']) assert result.ret == 0 @pytest.mark.parametrize('clean_stop', [True, False]) def test_clean_stop_live_server(self, appdir, monkeypatch, clean_stop): """Ensure the fixture is trying to cleanly stop the server. Because this is tricky to test, we are checking that the _stop_cleanly() internal function was called and reported success. """ from pytest_flask.fixtures import LiveServer original_stop_cleanly_func = LiveServer._stop_cleanly stop_cleanly_result = [] def mocked_stop_cleanly(*args, **kwargs): result = original_stop_cleanly_func(*args, **kwargs) stop_cleanly_result.append(result) return result monkeypatch.setattr(LiveServer, '_stop_cleanly', mocked_stop_cleanly) appdir.create_test_module(''' import pytest try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen from flask import url_for def test_a(live_server): @live_server.app.route('/') def index(): return 'got it', 200 live_server.start() res = urlopen(url_for('index', _external=True)) assert res.code == 200 assert b'got it' in res.read() ''') args = [] if clean_stop else ['--no-live-server-clean-stop'] result = appdir.runpytest_inprocess('-v', '--no-start-live-server', *args) result.stdout.fnmatch_lines('*1 passed*') if clean_stop: assert stop_cleanly_result == [True] else: assert stop_cleanly_result == [] def test_add_endpoint_to_live_server(self, appdir): appdir.create_test_module(''' import pytest try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen from flask import url_for def test_a(live_server): @live_server.app.route('/new-endpoint') def new_endpoint(): return 'got it', 200 live_server.start() res = urlopen(url_for('new_endpoint', _external=True)) assert res.code == 200 assert b'got it' in res.read() ''') result = appdir.runpytest('-v', '--no-start-live-server') result.stdout.fnmatch_lines(['*PASSED*']) assert result.ret == 0 def test_concurrent_requests_to_live_server(self, appdir): appdir.create_test_module(''' import pytest try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen from flask import url_for def test_concurrent_requests(live_server): @live_server.app.route('/one') def one(): res = urlopen(url_for('two', _external=True)) return res.read() @live_server.app.route('/two') def two(): return '42' live_server.start() res = urlopen(url_for('one', _external=True)) assert res.code == 200 assert b'42' in res.read() ''') result = appdir.runpytest('-v', '--no-start-live-server') result.stdout.fnmatch_lines(['*PASSED*']) assert result.ret == 0 @pytest.mark.parametrize('port', [5000, 5001]) def test_live_server_fixed_port(self, port, appdir): appdir.create_test_module(''' import pytest def test_port(live_server): assert live_server.port == %d ''' % port) result = appdir.runpytest('-v', '--live-server-port', str(port)) result.stdout.fnmatch_lines(['*PASSED*']) assert result.ret == 0 @pytest.mark.parametrize('host', ['127.0.0.1', '0.0.0.0']) def test_live_server_fixed_host(self, host, appdir): appdir.create_test_module(''' import pytest def test_port(live_server): assert live_server.host == '%s' ''' % host) result = appdir.runpytest('-v', '--live-server-host', str(host)) result.stdout.fnmatch_lines(['*PASSED*']) assert result.ret == 0 pytest-flask-0.14.0/docs/0000775000175100017510000000000013363327364016314 5ustar jenkinsjenkins00000000000000pytest-flask-0.14.0/docs/conf.py0000664000175100017510000002043713363327112017610 0ustar jenkinsjenkins00000000000000# -*- coding: utf-8 -*- # # pytest-flask documentation build configuration file, created by # sphinx-quickstart on Thu Feb 19 17:57:27 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os, datetime # 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('.')) # -- 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 = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pytest-flask' copyright = u'%d, Vital Kudzelka and contributors' % datetime.date.today().year # 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 = __import__('pytest_flask').__version__ # The full version, including alpha/beta/rc tags. release = __import__('pytest_flask').__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # Only import and set the theme if we're building docs locally on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: 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 = 'pytest-flaskdoc' # -- 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', 'pytest-flask.tex', u'pytest-flask Documentation', u'Vital Kudzelka', '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', 'pytest-flask', u'pytest-flask Documentation', [u'Vital Kudzelka'], 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', 'pytest-flask', u'pytest-flask Documentation', u'Vital Kudzelka', 'pytest-flask', '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 pytest-flask-0.14.0/docs/changelog.rst0000664000175100017510000001366213363327112020774 0ustar jenkinsjenkins00000000000000.. _changelog: Changelog ========= 0.14.0 (2018-10-15) ------------------- - New ``--live-server-host`` command-line option to set the host name used by the ``live_server`` fixture. Thanks `@o1da`_ for the PR (`#90`_). .. _@o1da: https://github.com/o1da .. _#90: https://github.com/pytest-dev/pytest-flask/pull/90 0.13.0 (2018-09-29) ------------------- - ``JSONReponse`` now supports comparison directly with status codes: .. code-block:: python assert client.get('invalid-route', headers=[('Accept', 'application/json')]) == 404 Thanks `@dusktreader`_ for the PR (`#86`_). .. _@dusktreader: https://github.com/dusktreader .. _#86: https://github.com/pytest-dev/pytest-flask/pull/86 0.12.0 (2018-09-06) ------------------- - ``pytest-flask`` now requires ``pytest>=3.6`` (`#84`_). - Add new ``--live-server-port`` option to select the port the live server will use (`#82`_). Thanks `@RazerM`_ for the PR. - Now ``live_server`` will try to stop the server cleanly by emitting a ``SIGINT`` signal and waiting 5 seconds for the server to shutdown. If the server is still running after 5 seconds, it will be forcefully terminated. This behavior can be changed by passing ``--no-live-server-clean-stop`` in the command-line (`#49`_). Thanks `@jadkik`_ for the PR. - Internal fixes silence pytest warnings, more visible now with ``pytest-3.8.0`` (`#84`_). .. _@jadkik: https://github.com/jadkik .. _@RazerM: https://github.com/RazerM .. _#49: https://github.com/pytest-dev/pytest-flask/issues/49 .. _#82: https://github.com/pytest-dev/pytest-flask/pull/82 .. _#84: https://github.com/pytest-dev/pytest-flask/pull/84 0.11.0 (compared to 0.10.0) --------------------------- - Implement deployment using Travis, following in line with many other pytest plugins. - Allow live server to handle concurrent requests (`#56`_), thanks to `@mattwbarry`_ for the PR. - Fix broken link to pytest documentation (`#50`_), thanks to `@jineshpaloor`_ for the PR. - Tox support (`#48`_), thanks to `@steenzout`_ for the PR. - Add ``LICENSE`` into distribution (`#43`_), thanks to `@danstender`_. - Minor typography improvements in documentation. - Add changelog to documentation. .. _#43: https://github.com/vitalk/pytest-flask/issues/43 .. _#48: https://github.com/pytest-dev/pytest-flask/pull/48 .. _#50: https://github.com/pytest-dev/pytest-flask/pull/50 .. _#56: https://github.com/pytest-dev/pytest-flask/pull/56 .. _@danstender: https://github.com/danstender .. _@jineshpaloor: https://github.com/jineshpaloor .. _@mattwbarry: https://github.com/mattwbarry .. _@steenzout: https://github.com/steenzout 0.10.0 (compared to 0.9.0) -------------------------- - Add ``--start-live-server``/``--no-start-live-server`` options to prevent live server from starting automatically (`#36`_), thanks to `@EliRibble`_. - Fix title formatting in documentation. .. _#36: https://github.com/vitalk/pytest-flask/issues/36 .. _@EliRibble: https://github.com/EliRibble 0.9.0 (compared to 0.8.1) ------------------------- - Rename marker used to pass options to application, e.g. ``pytest.mark.app`` is now ``pytest.mark.options`` (`#35`_). - Documentation badge points to the package documentation. - Add Travis CI configuration to ensure the tests are passed in supported environments (`#32`_). .. _#32: https://github.com/vitalk/pytest-flask/issues/32 .. _#35: https://github.com/vitalk/pytest-flask/issues/35 0.8.1 ----- - Minor changes in documentation. 0.8.0 ----- - New ``request_ctx`` fixture which contains all request relevant information (`#29`_). .. _#29: https://github.com/vitalk/pytest-flask/issues/29 0.7.5 ----- - Use pytest ``monkeypath`` fixture to teardown application config (`#27`_). .. _#27: https://github.com/vitalk/pytest-flask/issues/27 0.7.4 ----- - Better test coverage, e.g. tests for available fixtures and markers. 0.7.3 ----- - Use retina-ready badges in documentation (`#21`_). .. _#21: https://github.com/vitalk/pytest-flask/issues/21 0.7.2 ----- - Use pytest ``monkeypatch`` fixture to rewrite live server name. 0.7.1 ----- - Single-sourcing package version (`#24`_), as per `"Python Packaging User Guide" `_. .. _#24: https://github.com/vitalk/pytest-flask/issues/24 0.7.0 ----- - Add package documentation (`#20`_). .. _#20: https://github.com/vitalk/pytest-flask/issues/20 0.6.3 ----- - Better documentation in README with reST formatting (`#18`_), thanks to `@greedo`_. .. _#18: https://github.com/vitalk/pytest-flask/issues/18 .. _@greedo: https://github.com/greedo 0.6.2 ----- - Release the random port before starting the application live server (`#17`_), thanks to `@davehunt`_. .. _#17: https://github.com/vitalk/pytest-flask/issues/17 .. _@davehunt: https://github.com/davehunt 0.6.1 ----- - Bind live server to a random port instead of 5000 or whatever is passed on the command line, so it’s possible to execute tests in parallel via pytest-dev/pytest-xdist (`#15`_). Thanks to `@davehunt`_. - Remove ``--liveserver-port`` option. .. _#15: https://github.com/vitalk/pytest-flask/issues/15 .. _@davehunt: https://github.com/davehunt 0.6.0 ----- - Fix typo in option help for ``--liveserver-port``, thanks to `@svenstaro`_. .. _@svenstaro: https://github.com/svenstaro 0.5.0 ----- - Add ``live_server`` fixture uses to run application in the background (`#11`_), thanks to `@svenstaro`_. .. _#11: https://github.com/vitalk/pytest-flask/issues/11 .. _@svenstaro: https://github.com/svenstaro 0.4.0 ----- - Add ``client_class`` fixture for class-based tests. 0.3.4 ----- - Include package requirements into distribution (`#8`_). .. _#8: https://github.com/vitalk/pytest-flask/issues/8 0.3.3 ----- - Explicitly pin package dependencies and their versions. 0.3.2 ----- - Use ``codecs`` module to open files to prevent possible errors on open files which contains non-ascii characters. 0.3.1 ----- First release on PyPI. pytest-flask-0.14.0/docs/make.bat0000664000175100017510000001507113363327061017717 0ustar jenkinsjenkins00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :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. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over 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 goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\pytest-flask.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\pytest-flask.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end pytest-flask-0.14.0/docs/index.rst0000664000175100017510000000165713363327061020160 0ustar jenkinsjenkins00000000000000Welcome to pytest-flask’s documentation! ======================================== Pytest-flask is a plugin for `pytest `_ that provides a set of useful tools to test `Flask `_ applications and extensions. User’s Guide ------------ This part of the documentation will show you how to get started in using pytest-flask with your application. .. toctree:: :maxdepth: 4 tutorial features contributing changelog Quickstart ---------- Install plugin via ``pip``:: pip install pytest-flask Define your application fixture in ``conftest.py``: .. code:: python from myapp import create_app @pytest.fixture def app(): app = create_app() return app And run your test suite:: py.test Contributing ------------ Don’t hesitate to create a `GitHub issue `_ for any **bug** or **suggestion**. pytest-flask-0.14.0/docs/features.rst0000664000175100017510000002023213363327112020652 0ustar jenkinsjenkins00000000000000.. _features: Feature reference ================= Extension provides some sugar for your tests, such as: * Access to context bound objects (``url_for``, ``request``, ``session``) without context managers: .. code:: python def test_app(client): assert client.get(url_for('myview')).status_code == 200 * Easy access to ``JSON`` data in response: .. code:: python @api.route('/ping') def ping(): return jsonify(ping='pong') def test_api_ping(client): res = client.get(url_for('api.ping')) assert res.json == {'ping': 'pong'} .. note:: User-defined ``json`` attribute/method in application response class does not overrides. So you can define your own response deserialization method: .. code:: python from flask import Response from myapp import create_app class MyResponse(Response): '''Implements custom deserialization method for response objects.''' @property def json(self): '''What is the meaning of life, the universe and everything?''' return 42 @pytest.fixture def app(): app = create_app() app.response_class = MyResponse return app def test_my_json_response(client): res = client.get(url_for('api.ping')) assert res.json == 42 * Running tests in parallel with `pytest-xdist`_. This can lead to significant speed improvements on multi core/multi CPU machines. This requires the ``pytest-xdist`` plugin to be available, it can usually be installed with:: pip install pytest-xdist You can then run the tests by running:: py.test -n **Not enough pros?** See the full list of available fixtures and markers below. Fixtures -------- ``pytest-flask`` provides a list of useful fixtures to simplify application testing. More information on fixtures and their usage is available in the `pytest documentation`_. ``client`` - application test client ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An instance of ``app.test_client``. Typically refers to `flask.Flask.test_client`_. .. hint:: During tests execution the request context has been pushed, e.g. ``url_for``, ``session`` and other context bound objects are available without context managers. Example: .. code:: python def test_myview(client): assert client.get(url_for('myview')).status_code == 200 ``client_class`` - application test client for class-based tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Example: .. code:: python @pytest.mark.usefixtures('client_class') class TestSuite: def test_myview(self): assert self.client.get(url_for('myview')).status_code == 200 ``config`` - application config ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An instance of ``app.config``. Typically refers to `flask.Config`_. ``live_server`` - application live server ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Run application in a separate process (useful for tests with Selenium_ and other headless browsers). .. hint:: The server’s URL can be retrieved using the ``url_for`` function. .. code:: python from flask import url_for @pytest.mark.usefixtures('live_server') class TestLiveServer: def test_server_is_up_and_running(self): res = urllib2.urlopen(url_for('index', _external=True)) assert b'OK' in res.read() assert res.code == 200 ``--start-live-server`` - start live server automatically (default) ``````````````````````````````````````````````````````````````````` ``--no-start-live-server`` - don’t start live server automatically `````````````````````````````````````````````````````````````````` By default the server is starting automatically whenever you reference ``live_server`` fixture in your tests. But starting live server imposes some high costs on tests that need it when they may not be ready yet. To prevent that behaviour pass ``--no-start-live-server`` into your default options (for example, in your project’s ``pytest.ini`` file):: [pytest] addopts = --no-start-live-server .. note:: You **should manually start** live server after you finish your application configuration and define all required routes: .. code:: python def test_add_endpoint_to_live_server(live_server): @live_server.app.route('/test-endpoint') def test_endpoint(): return 'got it', 200 live_server.start() res = urlopen(url_for('test_endpoint', _external=True)) assert res.code == 200 assert b'got it' in res.read() ``--live-server-port`` - use a fixed port ````````````````````````````````````````` By default the server uses a random port. In some cases it is desirable to run the server with a fixed port. You can use ``--live-server-port`` (for example, in your project's ``pytest.ini`` file):: [pytest] addopts = --live-server-port=5000 ``request_ctx`` - request context ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The request context which contains all request relevant information. .. hint:: The request context has been pushed implicitly any time the ``app`` fixture is applied and is kept around during test execution, so it’s easy to introspect the data: .. code:: python from flask import request, url_for def test_request_headers(client): res = client.get(url_for('ping'), headers=[('X-Something', '42')]) assert request.headers['X-Something'] == '42' Content negotiation ~~~~~~~~~~~~~~~~~~~ An important part of any :abbr:`REST (REpresentational State Transfer)` service is content negotiation. It allows you to implement behaviour such as selecting a different serialization schemes for different media types. HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available. -- :rfc:`2616#section-12`. Fielding, et al. The most common way to select one of the multiple possible representation is via ``Accept`` request header. The following series of ``accept_*`` fixtures provides an easy way to test content negotiation in your application: .. code:: python def test_api_endpoint(accept_json, client): res = client.get(url_for('api.endpoint'), headers=accept_json) assert res.mimetype == 'application/json' ``accept_any`` - :mimetype:`*/*` accept header `````````````````````````````````````````````` :mimetype:`*/*` accept header suitable to use as parameter in ``client``. ``accept_json`` - :mimetype:`application/json` accept header ```````````````````````````````````````````````````````````` :mimetype:`application/json` accept header suitable to use as parameter in ``client``. ``accept_jsonp`` - :mimetype:`application/json-p` accept header ``````````````````````````````````````````````````````````````` :mimetype:`application/json-p` accept header suitable to use as parameter in ``client``. Markers ------- ``pytest-flask`` registers the following markers. See the pytest documentation on `what markers are`_ and for notes on `using them`_. ``pytest.mark.options`` - pass options to your application config ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: pytest.mark.options(**kwargs) The mark used to pass options to your application config. :type kwargs: dict :param kwargs: The dictionary used to extend application config. Example usage: .. code:: python @pytest.mark.options(debug=False) def test_app(app): assert not app.debug, 'Ensure the app not in debug mode' .. _pytest-xdist: https://pypi.python.org/pypi/pytest-xdist .. _pytest documentation: http://pytest.org/latest/fixture.html .. _flask.Flask.test_client: http://flask.pocoo.org/docs/latest/api/#flask.Flask.test_client .. _flask.Config: http://flask.pocoo.org/docs/latest/api/#flask.Config .. _Selenium: http://www.seleniumhq.org .. _what markers are: http://pytest.org/latest/mark.html .. _using them: http://pytest.org/latest/example/markers.html#marking-whole-classes-or-modules pytest-flask-0.14.0/docs/contributing.rst0000664000175100017510000000132613363327061021551 0ustar jenkinsjenkins00000000000000.. _contributing: Contributing ============ Found a bug? Have an issue? --------------------------- The fastest way to get feedback on contributions/bugs is create a `GitHub issue`_ or catch me on `Twitter`_. Code syntax and conventions --------------------------- We try to conform to :pep:`8` as much as possible. Make sure that your code as well. Where are the tests? -------------------- Good that you’re asking. The repository test suite is located in ``tests`` directory. Makefile defines a target to run them:: make test Ensure the all tests are passed before submitting a pull request. .. _GitHub issue: https://github.com/vitalk/pytest-flask/issues .. _Twitter: https://twitter.com/elephantscanfly pytest-flask-0.14.0/docs/tutorial.rst0000664000175100017510000000271513363327061020710 0ustar jenkinsjenkins00000000000000Getting started =============== Pytest is capable to pick up and run existing tests without any or little configuration. This section describes how to get started quickly. Step 1. Install --------------- ``pytest-flask`` is available on `PyPi`_, and can be easily installed via ``pip``:: pip install pytest-flask Step 2. Configure ----------------- Define your application fixture in ``conftest.py``: .. code:: python from myapp import create_app @pytest.fixture def app(): app = create_app() return app Step 3. Run your test suite --------------------------- Use the ``py.test`` command to run your test suite:: py.test .. note:: Test discovery. Pytest `discovers your tests`_ and has a built-in integration with other testing tools (such as ``nose``, ``unittest`` and ``doctest``). More comprehensive examples and use cases can be found in the `official documentation`_. What’s next? ------------ The :ref:`features` section gives a more detailed view of available features, as well as test fixtures and markers. Consult the `pytest documentation `_ for more information about pytest itself. If you want to contribute to the project, see the :ref:`contributing` section. .. _PyPi: https://pypi.python.org/pypi/pytest-flask .. _discovers your tests: http://docs.pytest.org/en/latest/goodpractices.html#test-discovery .. _official documentation: http://pytest.org/latest/usage.html pytest-flask-0.14.0/docs/Makefile0000664000175100017510000001520213363327061017746 0ustar jenkinsjenkins00000000000000# 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/pytest-flask.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pytest-flask.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/pytest-flask" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pytest-flask" @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." pytest-flask-0.14.0/requirements/0000775000175100017510000000000013363327364020107 5ustar jenkinsjenkins00000000000000pytest-flask-0.14.0/requirements/main.txt0000664000175100017510000000004013363327112021555 0ustar jenkinsjenkins00000000000000pytest>=3.6 Flask Werkzeug>=0.7 pytest-flask-0.14.0/requirements/test.txt0000664000175100017510000000004313363327061021616 0ustar jenkinsjenkins00000000000000mock pylint pytest-cov pytest-pep8 pytest-flask-0.14.0/requirements/docs.txt0000664000175100017510000000003013363327061021563 0ustar jenkinsjenkins00000000000000Sphinx sphinx_rtd_theme pytest-flask-0.14.0/pytest_flask.egg-info/0000775000175100017510000000000013363327364021566 5ustar jenkinsjenkins00000000000000pytest-flask-0.14.0/pytest_flask.egg-info/dependency_links.txt0000664000175100017510000000000113363327364025634 0ustar jenkinsjenkins00000000000000 pytest-flask-0.14.0/pytest_flask.egg-info/PKG-INFO0000664000175100017510000001105113363327364022661 0ustar jenkinsjenkins00000000000000Metadata-Version: 2.1 Name: pytest-flask Version: 0.14.0 Summary: A set of py.test fixtures to test Flask applications. Home-page: https://github.com/vitalk/pytest-flask Author: Vital Kudzelka Author-email: vital.kudzelka@gmail.com License: MIT Project-URL: Tracker, https://github.com/pytest-dev/pytest-flask/issues Project-URL: Source, https://github.com/pytest-dev/pytest-flask Description: pytest-flask ============ A set of `pytest `_ fixtures to test Flask extensions and applications. Features -------- Plugin provides some fixtures to simplify app testing: - ``client`` - an instance of ``app.test_client``, - ``client_class`` - ``client`` fixture for class-based tests, - ``config`` - the application config, - ``live_server`` - runs an application in the background (useful for tests with `Selenium `_ and other headless browsers), - ``request_ctx`` - the request context, - ``accept_json``, ``accept_jsonp``, ``accept_any`` - accept headers suitable to use as parameters in ``client``. To pass options to your application use the ``pytest.mark.options`` marker: .. code:: python @pytest.mark.options(debug=False) def test_app(app): assert not app.debug, 'Ensure the app not in debug mode' During tests execution the request context has been pushed, e.g. ``url_for``, ``session`` and other context bound objects are available without context managers: .. code:: python def test_app(client): assert client.get(url_for('myview')).status_code == 200 Response object has a ``json`` property to test a view that returns a JSON response: .. code:: python @api.route('/ping') def ping(): return jsonify(ping='pong') def test_api_ping(client): res = client.get(url_for('api.ping')) assert res.json == {'ping': 'pong'} If you want your tests done via Selenium or other headless browser use the ``live_server`` fixture. The server’s URL can be retrieved using the ``url_for`` function: .. code:: python from flask import url_for @pytest.mark.usefixtures('live_server') class TestLiveServer: def test_server_is_up_and_running(self): res = urllib2.urlopen(url_for('index', _external=True)) assert b'OK' in res.read() assert res.code == 200 Quick Start ----------- To start using a plugin define your application fixture in ``conftest.py``: .. code:: python from myapp import create_app @pytest.fixture def app(): app = create_app() return app Install the extension with dependencies and run your test suite: .. code:: bash $ pip install pytest-flask $ py.test Documentation ------------- The latest documentation is available at http://pytest-flask.readthedocs.org/en/latest/. Contributing ------------ Don’t hesitate to create a `GitHub issue `_ for any **bug** or **suggestion**. Keywords: pytest flask testing Platform: any Classifier: Development Status :: 4 - Beta Classifier: Environment :: Plugins Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Software Development :: Testing Classifier: Topic :: Software Development :: Libraries :: Python Modules Provides-Extra: tests Provides-Extra: docs pytest-flask-0.14.0/pytest_flask.egg-info/not-zip-safe0000664000175100017510000000000113363327262024011 0ustar jenkinsjenkins00000000000000 pytest-flask-0.14.0/pytest_flask.egg-info/SOURCES.txt0000664000175100017510000000136213363327364023454 0ustar jenkinsjenkins00000000000000.gitignore .travis.yml HOWTORELEASE.rst LICENSE README.rst setup.cfg setup.py tox.ini docs/Makefile docs/changelog.rst docs/conf.py docs/contributing.rst docs/features.rst docs/index.rst docs/make.bat docs/tutorial.rst pytest_flask/__init__.py pytest_flask/_version.py pytest_flask/fixtures.py pytest_flask/plugin.py pytest_flask/pytest_compat.py pytest_flask.egg-info/PKG-INFO pytest_flask.egg-info/SOURCES.txt pytest_flask.egg-info/dependency_links.txt pytest_flask.egg-info/entry_points.txt pytest_flask.egg-info/not-zip-safe pytest_flask.egg-info/requires.txt pytest_flask.egg-info/top_level.txt requirements/docs.txt requirements/main.txt requirements/test.txt tests/conftest.py tests/test_fixtures.py tests/test_live_server.py tests/test_markers.pypytest-flask-0.14.0/pytest_flask.egg-info/top_level.txt0000664000175100017510000000001513363327364024314 0ustar jenkinsjenkins00000000000000pytest_flask pytest-flask-0.14.0/pytest_flask.egg-info/entry_points.txt0000664000175100017510000000005013363327364025057 0ustar jenkinsjenkins00000000000000[pytest11] flask = pytest_flask.plugin pytest-flask-0.14.0/pytest_flask.egg-info/requires.txt0000664000175100017510000000012013363327364024157 0ustar jenkinsjenkins00000000000000pytest>=3.6 Flask Werkzeug>=0.7 pytest [docs] Sphinx sphinx_rtd_theme [tests] pytest-flask-0.14.0/tox.ini0000664000175100017510000000126413363327112016671 0ustar jenkinsjenkins00000000000000[tox] envlist = py{27,34,35,36,37} [pytest] norecursedirs = .git .tox env coverage docs pep8ignore = docs/conf.py ALL pep8maxlinelength = 119 [testenv] usedevelop = True deps = -rrequirements/main.txt -rrequirements/test.txt passenv = HOME LANG LC_ALL commands = pytest --basetemp={envtmpdir} --confcutdir=tests \ --junitxml=tests/junit.xml \ --cov-report xml --cov pytest_flask \ --cov-report=html \ --cov-report term-missing \ --pep8 \ -ra \ {posargs:tests} [testenv:docs] changedir = docs skipsdist = True usedevelop = True deps = -r requirements/docs.txt commands = sphinx-build -W -b html . _build pytest-flask-0.14.0/.travis.yml0000664000175100017510000000305513363327112017467 0ustar jenkinsjenkins00000000000000language: python python: - "3.6" stages: - test - name: deploy if: repo = pytest-dev/pytest-flask AND tag IS present jobs: include: - env: TOXENV=py27 python: '2.7' - env: TOXENV=py34 python: '3.4' - env: TOXENV=py35 python: '3.5' - env: TOXENV=py36 python: '3.6' - env: TOXENV=docs python: '3.6' - env: TOXENV=py37 python: '3.7' sudo: required dist: xenial - stage: deploy python: '3.6' env: install: pip install -U setuptools setuptools_scm script: skip deploy: provider: pypi user: nicoddemus distributions: sdist bdist_wheel skip_upload_docs: true password: secure: lSaCqdifJoDS7qjpAnGgfrvuACEEBBQYDsjtkNlkktIhrZNJi0OjNWNuHN8uDpQSULiOdiQv/bOCAk288Pao341nHznMP3Cu9o+Zgi96dESAwTHx7w+01uzj+nzuRieeYL+Ye9VK0W3A7yu8tTG2GAhuqKCv0bDV7fUKAfySSI+SKTudLt4DHAYLd02tpbmPoHcHRqUSKTtkJKYUaYGM9QGk8p4+2ap006nqiykhiplnAWNLu+xzby7TaFYpA3Yy4x6XWMcdOoTaaBzQHZaGVayT1zR1BfmcOovlIb8sOUQVr6PV/dxC29VTRuyY85S2Rdyw/2Y4viTO5c1omEU/pVzy4RNi4RWboh58WA0kjrwOmb/nLW8AcXNJG9H828dqy8KKdbblTU5guz1oO1Tb2ICLT2z4hQOcZoDkCg3jf54Ee4BYvLOvMH/kNOjNqLA7wjBUzvyWk5OPOIPZ0rozmRwU89VS2kxIhbvtAq0BtmLnIYY3nT5BIrt18FomiINxlgZj6jz2uWGaOPAhcghdjydbGdYs5g2JcUc1B3jvXSyjB+o1l/EJ9OUwCQWIc32XWvOtx/a7pcyrejbKBqQqi5nKF1bvYDM+8VSLEeLTIX1Ie8hModxWp8WPIk+dHBdy8Kb91c4ssOvEkfwHK7cYBdbcn6O0yhiLOxuOO/3Cb3c= on: tags: true repo: pytest-dev/pytest-flask install: - pip install -U pip - pip install -U tox setuptools script: - tox pytest-flask-0.14.0/setup.cfg0000664000175100017510000000007513363327364017207 0ustar jenkinsjenkins00000000000000[wheel] universal = 1 [egg_info] tag_build = tag_date = 0 pytest-flask-0.14.0/LICENSE0000664000175100017510000000213113363327061016360 0ustar jenkinsjenkins00000000000000The MIT License (MIT) Copyright © 2014–2016 Vital Kudzelka and 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. pytest-flask-0.14.0/setup.py0000775000175100017510000001170213363327112017071 0ustar jenkinsjenkins00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ pytest-flask ============ A set of `pytest `_ fixtures to test Flask extensions and applications. Features -------- Plugin provides some fixtures to simplify app testing: - ``client`` - an instance of ``app.test_client``, - ``client_class`` - ``client`` fixture for class-based tests, - ``config`` - the application config, - ``live_server`` - runs an application in the background (useful for tests with `Selenium `_ and other headless browsers), - ``request_ctx`` - the request context, - ``accept_json``, ``accept_jsonp``, ``accept_any`` - accept headers suitable to use as parameters in ``client``. To pass options to your application use the ``pytest.mark.options`` marker: .. code:: python @pytest.mark.options(debug=False) def test_app(app): assert not app.debug, 'Ensure the app not in debug mode' During tests execution the request context has been pushed, e.g. ``url_for``, ``session`` and other context bound objects are available without context managers: .. code:: python def test_app(client): assert client.get(url_for('myview')).status_code == 200 Response object has a ``json`` property to test a view that returns a JSON response: .. code:: python @api.route('/ping') def ping(): return jsonify(ping='pong') def test_api_ping(client): res = client.get(url_for('api.ping')) assert res.json == {'ping': 'pong'} If you want your tests done via Selenium or other headless browser use the ``live_server`` fixture. The server’s URL can be retrieved using the ``url_for`` function: .. code:: python from flask import url_for @pytest.mark.usefixtures('live_server') class TestLiveServer: def test_server_is_up_and_running(self): res = urllib2.urlopen(url_for('index', _external=True)) assert b'OK' in res.read() assert res.code == 200 Quick Start ----------- To start using a plugin define your application fixture in ``conftest.py``: .. code:: python from myapp import create_app @pytest.fixture def app(): app = create_app() return app Install the extension with dependencies and run your test suite: .. code:: bash $ pip install pytest-flask $ py.test Documentation ------------- The latest documentation is available at http://pytest-flask.readthedocs.org/en/latest/. Contributing ------------ Don’t hesitate to create a `GitHub issue `_ for any **bug** or **suggestion**. """ import io import os import re from setuptools import setup from setuptools import find_packages def read(*parts): """Reads the content of the file located at path created from *parts*.""" try: return io.open(os.path.join(*parts), 'r', encoding='utf-8').read() except IOError: return '' requirements = read('requirements', 'main.txt').splitlines() + ['pytest'] tests_require = [] extras_require = { 'docs': read('requirements', 'docs.txt').splitlines(), 'tests': tests_require } setup( name='pytest-flask', # Versions should comply with PEP440, and automatically obtained from tags # thanks to setuptools_scm use_scm_version={"write_to": "pytest_flask/_version.py"}, setup_requires=["setuptools-scm"], author='Vital Kudzelka', author_email='vital.kudzelka@gmail.com', url='https://github.com/vitalk/pytest-flask', project_urls={ "Source": "https://github.com/pytest-dev/pytest-flask", "Tracker": "https://github.com/pytest-dev/pytest-flask/issues", }, description='A set of py.test fixtures to test Flask applications.', long_description=__doc__, license='MIT', packages=find_packages(exclude=['docs', 'tests']), zip_safe=False, platforms='any', install_requires=requirements, tests_require=tests_require, extras_require=extras_require, keywords='pytest flask testing', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Plugins', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Libraries :: Python Modules', ], # The following makes a plugin available to pytest entry_points={ 'pytest11': [ 'flask = pytest_flask.plugin', ] }, ) pytest-flask-0.14.0/HOWTORELEASE.rst0000664000175100017510000000037613363327112020014 0ustar jenkinsjenkins00000000000000Here are the steps on how to make a new release. 1. Create a ``release-VERSION`` branch from ``upstream/master``. 2. Update ``docs/changelog.rst``. 3. Push a branch with the changes. 4. Once all builds pass, push a tag to ``upstream``. 5. Merge the PR. pytest-flask-0.14.0/README.rst0000664000175100017510000000316413363327112017046 0ustar jenkinsjenkins00000000000000pytest-flask ============ |PyPI version| |conda-forge version| |Python versions| |Documentation status| An extension of `pytest `__ test runner which provides a set of useful tools to simplify testing and development of the Flask extensions and applications. To view a more detailed list of extension features and examples go to the `PyPI `__ overview page or `package documentation `_. How to start? ------------- Define your application fixture in ``conftest.py``: .. code-block:: python from myapp import create_app @pytest.fixture def app(): app = create_app() return app Install the extension with dependencies and go:: $ pip install pytest-flask $ pytest Contributing ------------ Don’t hesitate to create a `GitHub issue `__ for any bug or suggestion. .. |PyPI version| image:: https://img.shields.io/pypi/v/pytest-flask.svg :target: https://pypi.python.org/pypi/pytest-flask :alt: PyPi version .. |conda-forge version| image:: https://img.shields.io/conda/vn/conda-forge/pytest-flask.svg :target: https://anaconda.org/conda-forge/pytest-flask :alt: conda-forge version .. |Python versions| image:: https://img.shields.io/pypi/pyversions/pytest-flask.svg :target: https://pypi.org/project/pytest-flask :alt: PyPi downloads .. |Documentation status| image:: https://readthedocs.org/projects/pytest-flask/badge/?version=latest :target: https://pytest-flask.readthedocs.org/en/latest/ :alt: Documentation status pytest-flask-0.14.0/pytest_flask/0000775000175100017510000000000013363327364020074 5ustar jenkinsjenkins00000000000000pytest-flask-0.14.0/pytest_flask/_version.py0000664000175100017510000000016513363327364022274 0ustar jenkinsjenkins00000000000000# coding: utf-8 # file generated by setuptools_scm # don't change, don't track in version control version = '0.14.0' pytest-flask-0.14.0/pytest_flask/fixtures.py0000775000175100017510000001326413363327112022317 0ustar jenkinsjenkins00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import time import multiprocessing import pytest import socket import signal import os import logging try: from urllib2 import URLError, urlopen except ImportError: from urllib.error import URLError from urllib.request import urlopen from flask import _request_ctx_stack @pytest.yield_fixture def client(app): """A Flask test client. An instance of :class:`flask.testing.TestClient` by default. """ with app.test_client() as client: yield client @pytest.fixture def client_class(request, client): """Uses to set a ``client`` class attribute to current Flask test client:: @pytest.mark.usefixtures('client_class') class TestView: def login(self, email, password): credentials = {'email': email, 'password': password} return self.client.post(url_for('login'), data=credentials) def test_login(self): assert self.login('foo@example.com', 'pass').status_code == 200 """ if request.cls is not None: request.cls.client = client class LiveServer(object): """The helper class uses to manage live server. Handles creation and stopping application in a separate process. :param app: The application to run. :param host: The host where to listen (default localhost). :param port: The port to run application. """ def __init__(self, app, host, port, clean_stop=False): self.app = app self.port = port self.host = host self.clean_stop = clean_stop self._process = None def start(self): """Start application in a separate process.""" def worker(app, host, port): app.run(host=host, port=port, use_reloader=False, threaded=True) self._process = multiprocessing.Process( target=worker, args=(self.app, self.host, self.port) ) self._process.start() # We must wait for the server to start listening with a maximum # timeout of 5 seconds. timeout = 5 while timeout > 0: time.sleep(1) try: urlopen(self.url()) timeout = 0 except URLError: timeout -= 1 def url(self, url=''): """Returns the complete url based on server options.""" return 'http://%s:%d%s' % (self.host, self.port, url) def stop(self): """Stop application process.""" if self._process: if self.clean_stop and self._stop_cleanly(): return if self._process.is_alive(): # If it's still alive, kill it self._process.terminate() def _stop_cleanly(self, timeout=5): """Attempts to stop the server cleanly by sending a SIGINT signal and waiting for ``timeout`` seconds. :return: True if the server was cleanly stopped, False otherwise. """ try: os.kill(self._process.pid, signal.SIGINT) self._process.join(timeout) return True except Exception as ex: logging.error('Failed to join the live server process: %r', ex) return False def __repr__(self): return '' % self.url() def _rewrite_server_name(server_name, new_port): """Rewrite server port in ``server_name`` with ``new_port`` value.""" sep = ':' if sep in server_name: server_name, port = server_name.split(sep, 1) return sep.join((server_name, new_port)) @pytest.fixture(scope='function') def live_server(request, app, monkeypatch, pytestconfig): """Run application in a separate process. When the ``live_server`` fixture is applied, the ``url_for`` function works as expected:: def test_server_is_up_and_running(live_server): index_url = url_for('index', _external=True) assert index_url == 'http://localhost:5000/' res = urllib2.urlopen(index_url) assert res.code == 200 """ port = pytestconfig.getvalue('live_server_port') if port == 0: # Bind to an open port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 0)) port = s.getsockname()[1] s.close() host = pytestconfig.getvalue('live_server_host') # Explicitly set application ``SERVER_NAME`` for test suite # and restore original value on test teardown. server_name = app.config['SERVER_NAME'] or 'localhost' monkeypatch.setitem(app.config, 'SERVER_NAME', _rewrite_server_name(server_name, str(port))) clean_stop = request.config.getvalue('live_server_clean_stop') server = LiveServer(app, host, port, clean_stop) if request.config.getvalue('start_live_server'): server.start() request.addfinalizer(server.stop) return server @pytest.fixture def config(app): """An application config.""" return app.config @pytest.fixture def request_ctx(app): """The request context which contains all request relevant information, e.g. `session`, `g`, `flashes`, etc. """ return _request_ctx_stack.top @pytest.fixture(params=['application/json', 'text/html']) def mimetype(request): return request.param def _make_accept_header(mimetype): return [('Accept', mimetype)] @pytest.fixture def accept_mimetype(mimetype): return _make_accept_header(mimetype) @pytest.fixture def accept_json(request): return _make_accept_header('application/json') @pytest.fixture def accept_jsonp(): return _make_accept_header('application/json-p') @pytest.fixture(params=['*', '*/*']) def accept_any(request): return _make_accept_header(request.param) pytest-flask-0.14.0/pytest_flask/__init__.py0000775000175100017510000000013413363327112022175 0ustar jenkinsjenkins00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from ._version import version as __version__ pytest-flask-0.14.0/pytest_flask/plugin.py0000775000175100017510000001336213363327112021743 0ustar jenkinsjenkins00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ A py.test plugin which helps testing Flask applications. :copyright: (c) by Vital Kudzelka :license: MIT """ import sys import pytest from flask import json from werkzeug import cached_property from .fixtures import ( client, config, accept_json, accept_jsonp, accept_any, accept_mimetype, client_class, live_server, request_ctx ) from .pytest_compat import getfixturevalue class JSONResponse(object): """Mixin with testing helper methods for JSON responses.""" @cached_property def json(self): """Try to deserialize response data (a string containing a valid JSON document) to a Python object by passing it to the underlying :mod:`flask.json` module. """ return json.loads(self.data) def __eq__(self, other): if isinstance(other, int): return self.status_code == other # even though the Python 2-specific code works on Python 3, keep the two versions # separate so we can simplify the code once Python 2 support is dropped if sys.version_info[0] == 2: try: super_eq = super(JSONResponse, self).__eq__ except AttributeError: return NotImplemented else: return super_eq(other) else: return super(JSONResponse, self).__eq__(other) def __ne__(self, other): return not self == other def pytest_assertrepr_compare(op, left, right): if isinstance(left, JSONResponse) and op == '==' and isinstance(right, int): return [ 'Mismatch in status code for response: {} != {}'.format( left.status_code, right, ), 'Response status: {}'.format(left.status), ] return None def _make_test_response_class(response_class): """Extends the response class with special attribute to test JSON responses. Don't override user-defined `json` attribute if any. :param response_class: An original response class. """ if 'json' in response_class.__dict__: return response_class return type(str(JSONResponse), (response_class, JSONResponse), {}) @pytest.fixture(autouse=True) def _monkeypatch_response_class(request, monkeypatch): """Set custom response class before test suite and restore the original after. Custom response has `json` property to easily test JSON responses:: @app.route('/ping') def ping(): return jsonify(ping='pong') def test_json(client): res = client.get(url_for('ping')) assert res.json == {'ping': 'pong'} """ if 'app' not in request.fixturenames: return app = getfixturevalue(request, 'app') monkeypatch.setattr(app, 'response_class', _make_test_response_class(app.response_class)) @pytest.fixture(autouse=True) def _push_request_context(request): """During tests execution request context has been pushed, e.g. `url_for`, `session`, etc. can be used in tests as is:: def test_app(app, client): assert client.get(url_for('myview')).status_code == 200 """ if 'app' not in request.fixturenames: return app = getfixturevalue(request, 'app') # Get application bound to the live server if ``live_server`` fixture # is applied. Live server application has an explicit ``SERVER_NAME``, # so ``url_for`` function generates a complete URL for endpoint which # includes application port as well. if 'live_server' in request.fixturenames: app = getfixturevalue(request, 'live_server').app ctx = app.test_request_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) @pytest.fixture(autouse=True) def _configure_application(request, monkeypatch): """Use `pytest.mark.options` decorator to pass options to your application factory:: @pytest.mark.options(debug=False) def test_something(app): assert not app.debug, 'the application works not in debug mode!' """ if 'app' not in request.fixturenames: return app = getfixturevalue(request, 'app') for options in request.node.iter_markers('options'): for key, value in options.kwargs.items(): monkeypatch.setitem(app.config, key.upper(), value) def pytest_addoption(parser): group = parser.getgroup('flask') group.addoption('--start-live-server', action="store_true", dest="start_live_server", default=True, help="start server automatically when live_server " "fixture is applied (enabled by default).") group.addoption('--no-start-live-server', action="store_false", dest="start_live_server", help="don't start server automatically when live_server " "fixture is applied.") group.addoption('--live-server-clean-stop', action="store_true", dest="live_server_clean_stop", default=True, help="attempt to kill the live server cleanly.") group.addoption('--no-live-server-clean-stop', action="store_false", dest="live_server_clean_stop", help="terminate the server forcefully after stop.") group.addoption('--live-server-host', action='store', default='localhost', type=str, help='use a host where to listen (default localhost).') group.addoption('--live-server-port', action='store', default=0, type=int, help='use a fixed port for the live_server fixture.') def pytest_configure(config): config.addinivalue_line( 'markers', 'app(options): pass options to your application factory') pytest-flask-0.14.0/pytest_flask/pytest_compat.py0000664000175100017510000000025213363327061023332 0ustar jenkinsjenkins00000000000000def getfixturevalue(request, value): if hasattr(request, 'getfixturevalue'): return request.getfixturevalue(value) return request.getfuncargvalue(value)