pax_global_header00006660000000000000000000000064145155040750014520gustar00rootroot0000000000000052 comment=0e992d32aab1d3b439141d96e01a7370546a382d pytest-flask-1.3.0/000077500000000000000000000000001451550407500141475ustar00rootroot00000000000000pytest-flask-1.3.0/.github/000077500000000000000000000000001451550407500155075ustar00rootroot00000000000000pytest-flask-1.3.0/.github/ISSUE_TEMPLATE/000077500000000000000000000000001451550407500176725ustar00rootroot00000000000000pytest-flask-1.3.0/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000012701451550407500223640ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Environment (please complete the following information):** - OS: [e.g. macOS Catalina] - Python Version [e.g. 3.8.5] - pytest-flask version [e.g. 0.15.0] **Additional context** Add any other context about the problem here. pytest-flask-1.3.0/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000011421451550407500234150ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project title: '' labels: 'feature request' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. pytest-flask-1.3.0/.github/pull_request_template.md000066400000000000000000000016071451550407500224540ustar00rootroot00000000000000 - fixes # Checklist: - [ ] Add tests that demonstrate the correct behavior of the change. Tests should fail without the change. - [ ] Add or update relevant docs, in the docs folder and in code. - [ ] Add an entry in `docs/CHANGELOG.rst`, summarizing the change and linking to the issue. - [ ] Run `pre-commit` hooks and fix any issues. - [ ] Run `pytest` and make sure no tests failed. pytest-flask-1.3.0/.github/workflows/000077500000000000000000000000001451550407500175445ustar00rootroot00000000000000pytest-flask-1.3.0/.github/workflows/deploy.yml000066400000000000000000000025021451550407500215620ustar00rootroot00000000000000name: deploy on: workflow_dispatch: inputs: version: description: 'Release version' required: true default: '1.2.3' jobs: package: runs-on: ubuntu-latest env: SETUPTOOLS_SCM_PRETEND_VERSION: ${{ github.event.inputs.version }} steps: - uses: actions/checkout@v3 - name: Build and Check Package uses: hynek/build-and-inspect-python-package@v1.5 deploy: needs: package runs-on: ubuntu-latest environment: deploy permissions: id-token: write # For PyPI trusted publishers. contents: write # For tag and release notes. steps: - uses: actions/checkout@v3 - name: Download Package uses: actions/download-artifact@v3 with: name: Packages path: dist - name: Publish package to PyPI uses: pypa/gh-action-pypi-publish@v1.8.5 - name: Push tag run: | git config user.name "pytest bot" git config user.email "pytestbot@gmail.com" git tag --annotate --message=${{ github.event.inputs.version }} ${{ github.event.inputs.version }} ${{ github.sha }} git push origin ${{ github.event.inputs.version }} - name: GitHub Release uses: softprops/action-gh-release@v1 with: files: dist/* tag_name: ${{ github.event.inputs.version }} pytest-flask-1.3.0/.github/workflows/test.yml000066400000000000000000000020471451550407500212510ustar00rootroot00000000000000name: test on: push: branches: - main - "test-me-*" pull_request: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: package: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build and Check Package uses: hynek/build-and-inspect-python-package@v1.5 test: needs: [package] runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: python: ["3.7", "3.8", "3.9"] os: [ubuntu-latest, windows-latest] steps: - uses: actions/checkout@v3 - name: Download Package uses: actions/download-artifact@v3 with: name: Packages path: dist - name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python }} - name: Install tox run: | python -m pip install --upgrade pip pip install tox - name: Test shell: bash run: | tox run -e py --installpkg `find dist/*.tar.gz` pytest-flask-1.3.0/.gitignore000066400000000000000000000005261451550407500161420ustar00rootroot00000000000000# Python bytecode / optimized files *.py[co] *.egg-info build sdist .vscode *.swp __pycache__/ # virtualenv venv/ # Sphinx documentation docs/_build # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .pytest_cache/ .eggs/ dist/ coverage.xml tests/junit.xml src/pytest_flask/_version.py # Editors .vscode .code-workspace pytest-flask-1.3.0/.pre-commit-config.yaml000066400000000000000000000017701451550407500204350ustar00rootroot00000000000000repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-byte-order-marker - id: trailing-whitespace - id: end-of-file-fixer - id: fix-encoding-pragma args: [--remove] - id: check-yaml - repo: https://github.com/asottile/reorder_python_imports rev: v3.12.0 hooks: - id: reorder-python-imports args: ['--application-directories=.:src', --py3-plus] - repo: https://github.com/python/black rev: 23.10.0 hooks: - id: black - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 hooks: - id: flake8 additional_dependencies: [flake8-bugbear] - repo: local hooks: - id: rst name: rst entry: rst-lint --encoding utf-8 files: ^(RELEASING.rst|README.rst)$ language: python additional_dependencies: [pygments, restructuredtext_lint] - repo: https://github.com/myint/autoflake.git rev: v2.2.1 hooks: - id: autoflake pytest-flask-1.3.0/CODE_OF_CONDUCT.md000066400000000000000000000064311451550407500167520ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at pytest-dev@python.org. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq pytest-flask-1.3.0/CONTRIBUTING.rst000066400000000000000000000063421451550407500166150ustar00rootroot00000000000000How to contribute ================= All contributions are greatly appreciated! How to report issues ~~~~~~~~~~~~~~~~~~~~ Facilitating the work of potential contributors is recommended since it increases the likelihood of your issue being solved quickly. The few extra steps listed below will help clarify problems you might be facing: - Include a `minimal reproducible example`_ when possible. - Describe the expected behaviour and what actually happened including a full trace-back in case of exceptions. - Make sure to list details about your environment, such as your platform, versions of pytest, pytest-flask and python release. Also, it's important to check the current open issues for similar reports in order to avoid duplicates. .. _minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example Setting up your development environment ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Fork pytest-flask to your GitHub account by clicking the `Fork`_ button. - `Clone`_ the main repository (not your fork) to your local machine. .. code-block:: text $ git clone https://github.com/pytest-dev/pytest-flask $ cd pytest-flask - Add your fork as a remote to push your contributions.Replace ``{username}`` with your username. .. code-block:: text $ git remote add fork https://github.com/{username}/pytest-flask - Using `Tox`_, create a virtual environment and install pytest-flask in editable mode with development dependencies. .. code-block:: text $ tox -e dev $ source venv/bin/activate - Install pre-commit hooks .. code-block:: text $ pre-commit install .. _Fork: https://github.com/pytest-dev/pytest-flask/fork .. _Clone: https://docs.github.com/en/get-started/quickstart/fork-a-repo#step-2-create-a-local-clone-of-your-fork .. _Tox: https://tox.readthedocs.io/en/latest/ Start Coding ~~~~~~~~~~~~ - Create a new branch to identify what feature you are working on. .. code-block:: text $ git fetch origin $ git checkout -b your-branch-name origin/master - Make your changes - Include tests that cover any code changes you make and run them as described below. - Push your changes to your fork. `create a pull request`_ describing your changes. .. code-block:: text $ git push --set-upstream fork your-branch-name .. _create a pull request: https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request How to run tests ~~~~~~~~~~~~~~~~ You can run the test suite for the current environment with .. code-block:: text $ pytest To run the full test suite for all supported python versions .. code-block:: text $ tox Obs. CI will run tox when you submit your pull request, so this is optional. Checking Test Coverage ~~~~~~~~~~~~~~~~~~~~~~~ To get a complete report of code sections not being touched by the test suite run ``pytest`` using ``coverage``. .. code-block:: text $ coverage run --concurrency=multiprocessing -m pytest $ coverage combine $ coverage html Open ``htmlcov/index.html`` in your browser. More about coverage `here `__. pytest-flask-1.3.0/LICENSE000066400000000000000000000021311451550407500151510ustar00rootroot00000000000000The 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-1.3.0/README.rst000066400000000000000000000075051451550407500156450ustar00rootroot00000000000000pytest-flask ============ .. image:: https://img.shields.io/pypi/v/pytest-flask.svg :target: https://pypi.python.org/pypi/pytest-flask :alt: PyPi 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 .. image:: https://github.com/pytest-dev/pytest-flask/workflows/build/badge.svg :target: https://github.com/pytest-dev/pytest-flask/actions :alt: CI status .. image:: https://img.shields.io/pypi/pyversions/pytest-flask.svg :target: https://pypi.org/project/pytest-flask :alt: PyPi downloads .. image:: https://readthedocs.org/projects/pytest-flask/badge/?version=latest :target: https://pytest-flask.readthedocs.org/en/latest/ :alt: Documentation status .. image:: https://img.shields.io/maintenance/yes/2022?color=blue :target: https://github.com/pytest-dev/pytest-flask :alt: Maintenance .. image:: https://img.shields.io/github/last-commit/pytest-dev/pytest-flask?color=blue :target: https://github.com/pytest-dev/pytest-flask/commits/master :alt: GitHub last commit .. image:: https://img.shields.io/github/issues-pr-closed-raw/pytest-dev/pytest-flask?color=blue :target: https://github.com/pytest-dev/pytest-flask/pulls?q=is%3Apr+is%3Aclosed :alt: GitHub closed pull requests .. image:: https://img.shields.io/github/issues-closed/pytest-dev/pytest-flask?color=blue :target: https://github.com/pytest-dev/pytest-flask/issues?q=is%3Aissue+is%3Aclosed :alt: GitHub closed issues .. image:: https://img.shields.io/pypi/dm/pytest-flask?color=blue :target: https://pypi.org/project/pytest-flask/ :alt: PyPI - Downloads .. image:: https://img.shields.io/github/languages/code-size/pytest-dev/pytest-flask?color=blue :target: https://github.com/pytest-dev/pytest-flask :alt: Code size .. image:: https://img.shields.io/badge/license-MIT-blue.svg?color=blue :target: https://github.com/pytest-dev/pytest-flask/blob/master/LICENSE :alt: License .. image:: https://img.shields.io/github/issues-raw/pytest-dev/pytest-flask.svg?color=blue :target: https://github.com/pytest-dev/pytest-flask/issues :alt: Issues .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: style 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? ------------- Considering the minimal flask `application factory`_ below in ``myapp.py`` as an example: .. code-block:: python from flask import Flask def create_app(): # create a minimal app app = Flask(__name__) # simple hello world view @app.route('/hello') def hello(): return 'Hello, World!' return app You first need to define your application fixture in ``conftest.py``: .. code-block:: python from myapp import create_app @pytest.fixture def app(): app = create_app() return app Finally, install the extension with dependencies and run your test suite:: $ pip install pytest-flask $ pytest Contributing ------------ Don’t hesitate to create a `GitHub issue`_ for any bug or suggestion. For more information check our contribution `guidelines`_. .. _pytest: https://docs.pytest.org/en/stable/ .. _PyPI: https://pypi.python.org/pypi/pytest-flask .. _Github issue: https://github.com/vitalk/pytest-flask/issues .. _package documentation: http://pytest-flask.readthedocs.org/en/latest/ .. _guidelines: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst .. _application factory: https://flask.palletsprojects.com/patterns/appfactories/ pytest-flask-1.3.0/RELEASING.rst000066400000000000000000000004031451550407500162070ustar00rootroot00000000000000Here are the steps on how to make a new release. 1. Create a ``release-VERSION`` branch from ``upstream/main``. 2. Update ``CHANGELOG.rst``. 3. Push the branch to ``upstream``. 4. Once all tests pass, start the ``deploy`` workflow manually. 5. Merge the PR. pytest-flask-1.3.0/docs/000077500000000000000000000000001451550407500150775ustar00rootroot00000000000000pytest-flask-1.3.0/docs/Makefile000066400000000000000000000152021451550407500165370ustar00rootroot00000000000000# 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-1.3.0/docs/changelog.rst000066400000000000000000000174501451550407500175670ustar00rootroot00000000000000.. _changelog: Changelog ========= 1.3.0 (2023-10-23) ------------------ - Fix compatibility with ``Flask 3.0`` -- the consequence is that the deprecated and incompatible ``request_ctx`` has been removed. 1.2.1 ------------------ - Fix bug in ``:meth:pytest_flask.fixtures.live_server`` where ``SESSION_COOKIE_DOMAIN`` was set to false due to ``original_server_name`` defaulting to "localhost". The new default is "localhost.localdomain". - Drop support for python 3.6 and 3.5 1.2.0 (2021-02-26) ------------------ - Remove deprecated ``:meth:live_server.url`` - fixture ``request_ctx is now deprecated`` and will be removed in the future - ``JSONReponse.json`` removed in favour of ``Werkzeug.wrappers.Response.json`` 1.1.0 (2020-11-08) ------------------ - Speedup live server start time. Use `socket` instead of server pulling (`#58`_) to check server availability and add new ``--live-server-wait`` option to set the live server wait timeout. Thanks to `@jadkik`_. 1.0.0 (2020-03-03) ------------------ **Important** - ``live_server`` is now ``session``-scoped by default. This can be changed by using the ``live-server_scope`` option in your ``pytest.ini`` (`#113`_). Thanks `@havok2063`_ for the initial patch and `@TWood67`_ for finishing it up. - pytest 5.2 or later is now required. - Python 2.7 and 3.4 are no longer supported. .. _@havok2063: https://github.com/havok2063 .. _@TWood67: https://github.com/TWood67 .. _#113: https://github.com/pytest-dev/pytest-flask/pull/113 0.15.1 (2020-02-03) ------------------- - Fix ``ImportError`` with ``Werkzeug 1.0.0rc1`` (`#105`_). .. _#105: https://github.com/pytest-dev/pytest-flask/pull/105 0.15.0 (2019-05-13) ------------------- - Properly register the ``options`` marker (`#97`_). .. _#97: https://github.com/pytest-dev/pytest-flask/pull/97 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 .. _#58: steenzouthttps://github.com/pytest-dev/pytest-flask/pull/58 .. _@danstender: https://github.com/danstender .. _@jadkik: https://github.com/jadkik .. _@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-1.3.0/docs/conf.py000066400000000000000000000206501451550407500164010ustar00rootroot00000000000000# # 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 datetime 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('.')) # -- 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 = "pytest-flask" copyright = "%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", "pytest-flask Documentation", "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", "pytest-flask Documentation", ["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", "pytest-flask Documentation", "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-1.3.0/docs/contributing.rst000066400000000000000000000000641451550407500203400ustar00rootroot00000000000000.. _contributing: .. include:: ../CONTRIBUTING.rst pytest-flask-1.3.0/docs/features.rst000066400000000000000000000252001451550407500174460ustar00rootroot00000000000000.. _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 will not be overwritten. 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): return 42 @pytest.fixture(scope="session") 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:: pytest -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 test execution a request context will be automatically pushed for you, so context-bound methods can be conveniently called (e.g. ``url_for``, ``session``. 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 will start 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-wait`` - the live server wait timeout (5 seconds) ````````````````````````````````````````````````````````````````` The timeout after which test case is aborted if live server is not started. ``--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 ``live_server_scope`` - set the scope of the live server `````````````````````````````````````````````````````````````````` By default, the server will be scoped to ``session`` for performance reasons, however if your server has global state and you want better test isolation, you can use the ``live_server_scope`` ini option to change the fixture scope: .. code-block:: ini [pytest] live_server_scope = function HTTP Request ~~~~~~~~~~~~~~~~~~~ Common request methods are available through the internals of the `Flask API`_. Specifically, the API creates the default `flask.Flask.test_client`_ instance, which works like a regular `Werkzeug test client`_. Examples: .. code:: python def test_post_request(client, live_server): @live_server.app.route('/load-data') def get_endpoint(): return url_for('name.load', _external=True) live_server.start() res = client.post( get_endpoint(), headers={'Content-Type': 'application/json'}, data={} ) assert res.status_code == 200 .. code:: python def test_get_request(client, live_server): @live_server.app.route('/load-data') def get_endpoint(): return url_for('name.load', _external=True) live_server.start() res = client.get(get_endpoint()) assert res.status_code == 200 .. note:: The notation ``name.load_data``, corresponds to a ``endpoint='load'`` attribute, within a route decorator. The following is a route decorator using the `blueprint`_ implementation: .. code:: python from flask import Blueprint, request # local variables blueprint = Blueprint( 'name', __name__, template_folder='interface/templates', static_folder='interface/static' ) @blueprint.route('/load-data', methods=['POST'], endpoint='load') def load_data(): if request.method == 'POST': if request.get_json(): pass Alternatively, the route function can be referenced directly from the ``live_server`` implementation, rather than implementing an ``endpoint``: .. code:: python def test_load_data(live_server, client): @live_server.app.route('/load-data', methods=['POST']) def load_data(): pass live_server.start() res = client.post(url_for('load_data'), data={}) assert res.status_code == 200 .. note:: Remember to explicitly define which ``methods`` are supported when registering the above route function. 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 is not in debug mode' .. _pytest-xdist: https://pypi.org/project/pytest-xdist/ .. _pytest documentation: https://pytest.org/en/latest/fixture.html .. _flask.Flask.test_client: https://flask.palletsprojects.com/api/#flask.Flask.test_client .. _flask.Config: https://flask.palletsprojects.com/api/#flask.Config .. _Selenium: https://selenium-python.readthedocs.io/ .. _what markers are: https://pytest.org/en/latest/mark.html .. _using them: https://pytest.org/en/latest/example/markers.html#marking-whole-classes-or-modules .. _Flask API: https://flask.palletsprojects.com/api/ .. _Werkzeug test client: https://werkzeug.palletsprojects.com/test/#werkzeug.test.Client .. _blueprint: https://flask.palletsprojects.com/blueprints/ pytest-flask-1.3.0/docs/index.rst000066400000000000000000000015451451550407500167450ustar00rootroot00000000000000Welcome 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. 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 Now you can use the ``app`` fixture in your test suite. You can run your tests with:: pytest 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 pytest-flask-1.3.0/docs/make.bat000066400000000000000000000150711451550407500165100ustar00rootroot00000000000000@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-1.3.0/docs/tutorial.rst000066400000000000000000000027141451550407500175000ustar00rootroot00000000000000Getting 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 ``pytest`` command to run your test suite:: pytest .. 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.org/project/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-1.3.0/pyproject.toml000066400000000000000000000001601451550407500170600ustar00rootroot00000000000000[build-system] requires = [ "setuptools", "setuptools-scm[toml]", ] build-backend = "setuptools.build_meta" pytest-flask-1.3.0/requirements/000077500000000000000000000000001451550407500166725ustar00rootroot00000000000000pytest-flask-1.3.0/requirements/docs.txt000066400000000000000000000000301451550407500203540ustar00rootroot00000000000000Sphinx sphinx_rtd_theme pytest-flask-1.3.0/requirements/main.txt000066400000000000000000000000331451550407500203530ustar00rootroot00000000000000pytest>=5.2 Flask Werkzeug pytest-flask-1.3.0/requirements/test.txt000066400000000000000000000000411451550407500204050ustar00rootroot00000000000000mock pylint coverage pytest-pep8 pytest-flask-1.3.0/setup.cfg000066400000000000000000000034221451550407500157710ustar00rootroot00000000000000[metadata] license = MIT name = pytest-flask license_files = LICENSE author = Vital Kudzelka keywords = pytest, flask, testing author_email = vital.kudzelka@gmail.com url = https://github.com/pytest-dev/pytest-flask long_description = file: README.rst, docs/changelog.rst, LICENSE long_description_content_type = text/x-rst description = A set of py.test fixtures to test Flask applications. project_urls = Source = https://github.com/pytest-dev/pytest-flask Issue tracker = https://github.com/pytest-dev/pytest-flask/issues classifiers= Framework :: Pytest Environment :: Plugins Programming Language :: Python Environment :: Web Environment Intended Audience :: Developers Operating System :: OS Independent Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 License :: OSI Approved :: MIT License Topic :: Software Development :: Testing Development Status :: 5 - Production/Stable Topic :: Software Development :: Libraries :: Python Modules [options] packages = pytest_flask zip_safe = False python_requires = >= 3.7 setup_requires = setuptools_scm package_dir = =src [options.packages.find] exclude = docs, tests [options.entry_points] pytest11 = flask = pytest_flask.plugin [flake8] # B = bugbear # E = pycodestyle errors # F = flake8 pyflakes # W = pycodestyle warnings # B9 = bugbear opinions # E203 = slice notation whitespace, invalid # E501 = line length, handled by bugbear B950 # E722 = bare except, handled by bugbear B001 # W503 = bin op line break, invalid # F401 = unused imports, false positives # F811 = redefinition of variables, flase positives select = B, E, F, W, B9 ignore = E203 E501 E722 W503 F401 F811 max-line-length = 80 pytest-flask-1.3.0/setup.py000077500000000000000000000013031451550407500156610ustar00rootroot00000000000000#!/usr/bin/env python import os from setuptools import setup def read(*parts): """Reads the content of the file located at path created from *parts*.""" try: return open(os.path.join(*parts), "r", encoding="utf-8").read() except OSError: return "" tests_require = [] requirements = read("requirements", "main.txt").splitlines() extras_require = { "docs": read("requirements", "docs.txt").splitlines(), "tests": tests_require, } setup( # Dependencies are here for GitHub's dependency graph. use_scm_version={"write_to": "src/pytest_flask/_version.py"}, install_requires=requirements, tests_require=tests_require, extras_require=extras_require, ) pytest-flask-1.3.0/src/000077500000000000000000000000001451550407500147365ustar00rootroot00000000000000pytest-flask-1.3.0/src/pytest_flask/000077500000000000000000000000001451550407500174465ustar00rootroot00000000000000pytest-flask-1.3.0/src/pytest_flask/__init__.py000066400000000000000000000001031451550407500215510ustar00rootroot00000000000000#!/usr/bin/env python from ._version import version as __version__ pytest-flask-1.3.0/src/pytest_flask/_internal.py000066400000000000000000000020121451550407500217660ustar00rootroot00000000000000import functools import warnings def deprecated(reason): """Decorator which can be used to mark function or method as deprecated. It will result a warning being emitted when the function is called.""" def decorator(func): @functools.wraps(func) def deprecated_call(*args, **kwargs): warnings.simplefilter("always", DeprecationWarning) warnings.warn(reason, DeprecationWarning, stacklevel=2) warnings.simplefilter("default", DeprecationWarning) return func(*args, **kwargs) return deprecated_call return decorator 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, _ = server_name.split(sep, 1) return sep.join((server_name, new_port)) def _determine_scope(*, fixture_name, config): return config.getini("live_server_scope") def _make_accept_header(mimetype): return [("Accept", mimetype)] pytest-flask-1.3.0/src/pytest_flask/fixtures.py000066400000000000000000000061121451550407500216710ustar00rootroot00000000000000#!/usr/bin/env python import socket import pytest from ._internal import _determine_scope from ._internal import _make_accept_header from ._internal import _rewrite_server_name from .live_server import LiveServer @pytest.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 @pytest.fixture(scope=_determine_scope) def live_server(request, app, pytestconfig): # pragma: no cover """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 """ # Set or get a port port = app.config.get("LIVESERVER_PORT", None) if not port: 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 original_server_name = app.config["SERVER_NAME"] or "localhost.localdomain" final_server_name = _rewrite_server_name(original_server_name, str(port)) app.config["SERVER_NAME"] = final_server_name wait = request.config.getvalue("live_server_wait") clean_stop = request.config.getvalue("live_server_clean_stop") server = LiveServer(app, host, port, wait, clean_stop) if request.config.getvalue("start_live_server"): server.start() request.addfinalizer(server.stop) yield server if original_server_name is not None: app.config["SERVER_NAME"] = original_server_name @pytest.fixture def config(app): """An application config.""" return app.config @pytest.fixture(params=["application/json", "text/html"]) def mimetype(request): return request.param @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-1.3.0/src/pytest_flask/live_server.py000066400000000000000000000060271451550407500223520ustar00rootroot00000000000000import logging import multiprocessing import os import platform import signal import socket import time import pytest # force 'fork' on macOS if platform.system() == "Darwin": multiprocessing = multiprocessing.get_context("fork") class LiveServer: # pragma: no cover """The helper class used to manage a 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. :param wait: The timeout after which test case is aborted if application is not started. """ def __init__(self, app, host, port, wait, clean_stop=False): self.app = app self.port = port self.host = host self.wait = wait 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.daemon = True self._process.start() keep_trying = True start_time = time.time() while keep_trying: elapsed_time = time.time() - start_time if elapsed_time > self.wait: pytest.fail( "Failed to start the server after {!s} " "seconds.".format(self.wait) ) if self._is_ready(): keep_trying = False def _is_ready(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((self.host, self.port)) except socket.error: ret = False else: ret = True finally: sock.close() return ret def url(self, url=""): """Returns the complete url based on server options.""" return "http://{host!s}:{port!s}{url!s}".format( host=self.host, port=self.port, url=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() pytest-flask-1.3.0/src/pytest_flask/plugin.py000066400000000000000000000130221451550407500213140ustar00rootroot00000000000000#!/usr/bin/env python """ A py.test plugin which helps testing Flask applications. :copyright: (c) by Vital Kudzelka :license: MIT """ import pytest from .fixtures import accept_any from .fixtures import accept_json from .fixtures import accept_jsonp from .fixtures import accept_mimetype from .fixtures import client from .fixtures import client_class from .fixtures import config from .fixtures import live_server from .pytest_compat import getfixturevalue class JSONResponse: """Mixin with testing helper methods for JSON responses.""" def __eq__(self, other): if isinstance(other, int): return self.status_code == other return super().__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-wait", action="store", dest="live_server_wait", default=5, type=float, help="the timeout after which test case is aborted if live server is " " not started.", ) 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.", ) parser.addini( "live_server_scope", "modify the scope of the live_server fixture.", default="session", ) def pytest_configure(config): config.addinivalue_line( "markers", "app(options): pass options to your application factory" ) config.addinivalue_line("markers", "options: app config manipulation") pytest-flask-1.3.0/src/pytest_flask/pytest_compat.py000066400000000000000000000002761451550407500227200ustar00rootroot00000000000000def getfixturevalue(request, value): if hasattr(request, "getfixturevalue"): return request.getfixturevalue(value) return request.getfuncargvalue(value) # pragma: no cover pytest-flask-1.3.0/tests/000077500000000000000000000000001451550407500153115ustar00rootroot00000000000000pytest-flask-1.3.0/tests/conftest.py000077500000000000000000000020551451550407500175150ustar00rootroot00000000000000#!/usr/bin/env python from textwrap import dedent import pytest from flask import Flask from flask import jsonify from pytest_flask.fixtures import mimetype pytest_plugins = "pytester" @pytest.fixture(scope="session") 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(scope='session') def app(): app = Flask(__name__) return app """, filename="conftest.py", ) return testdir pytest-flask-1.3.0/tests/test_fixtures.py000077500000000000000000000020221451550407500205720ustar00rootroot00000000000000import pytest from flask import request from flask import 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_accept_mimetype(self, accept_mimetype): mimestrings = [[("Accept", "application/json")], [("Accept", "text/html")]] assert accept_mimetype in mimestrings def test_accept_any(self, accept_any): mimestrings = [[("Accept", "*")], [("Accept", "*/*")]] assert accept_any in mimestrings @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-1.3.0/tests/test_internal.py000066400000000000000000000006331451550407500205400ustar00rootroot00000000000000import pytest from pytest_flask._internal import deprecated class TestInternal: def test_deprecation_decorator(self, appdir): @deprecated(reason="testing decorator") def deprecated_fun(): pass with pytest.warns(DeprecationWarning) as record: deprecated_fun() assert len(record) == 1 assert record[0].message.args[0] == "testing decorator" pytest-flask-1.3.0/tests/test_json_response.py000066400000000000000000000017051451550407500216140ustar00rootroot00000000000000import pytest from flask import url_for 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" pytest-flask-1.3.0/tests/test_live_server.py000077500000000000000000000162641451550407500212630ustar00rootroot00000000000000import os import pytest from flask import url_for pytestmark = pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") class TestLiveServer: def test_init(self, live_server): assert live_server.port assert live_server.host == "localhost" assert live_server.url() == "http://localhost:{0}".format(live_server.port) def test_server_is_alive(self, live_server): assert live_server._process assert live_server._process.is_alive() def test_server_listening(self, client, live_server): res = client.get(url_for("ping", _external=True)) assert res.status_code == 200 assert b"pong" in res.data def test_url_for(self, live_server): assert ( url_for("ping", _external=True) == "http://localhost.localdomain:%s/ping" % live_server.port ) def test_set_application_server_name(self, live_server): assert ( live_server.app.config["SERVER_NAME"] == "localhost.localdomain:%d" % live_server.port ) def test_rewrite_application_server_name(self, appdir): appdir.create_test_module( """ import pytest @pytest.mark.options(server_name='example.com:5000') def test_a(live_server): assert live_server.app.config['SERVER_NAME'] == \\ 'example.com:%d' % live_server.port """ ) result = appdir.runpytest("-v", "-o", "live_server_scope=function") result.stdout.fnmatch_lines(["*PASSED*"]) assert result.ret == 0 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 def test_stop_cleanly_join_exception(self, appdir, live_server, caplog): # timeout = 'a' here to force an exception when # attempting to self._process.join() assert not live_server._stop_cleanly(timeout="a") assert "Failed to join" in caplog.text @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 from flask import url_for def test_a(live_server, client): @live_server.app.route('/') def index(): return 'got it', 200 live_server.start() res = client.get(url_for('index', _external=True)) assert res.status_code == 200 assert b'got it' in res.data """ ) 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 from flask import url_for def test_a(live_server, client): @live_server.app.route('/new-endpoint') def new_endpoint(): return 'got it', 200 live_server.start() res = client.get(url_for('new_endpoint', _external=True)) assert res.status_code == 200 assert b'got it' in res.data """ ) result = appdir.runpytest("-v", "--no-start-live-server") result.stdout.fnmatch_lines(["*passed*"]) assert result.ret == 0 @pytest.mark.skip("this test hangs in the original code") def test_concurrent_requests_to_live_server(self, appdir): appdir.create_test_module( """ import pytest from flask import url_for def test_concurrent_requests(live_server, client): @live_server.app.route('/one') def one(): res = client.get(url_for('two', _external=True)) return res.data @live_server.app.route('/two') def two(): return '42' live_server.start() res = client.get(url_for('one', _external=True)) assert res.status_code == 200 assert b'42' in res.data """ ) 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 def test_respect_wait_timeout(self, appdir): appdir.create_test_module( """ import pytest def test_should_fail(live_server): assert live_server._process.is_alive() """ ) result = appdir.runpytest("-v", "--live-server-wait=0.00000001") result.stdout.fnmatch_lines(["**ERROR**"]) assert result.ret == 1 pytest-flask-1.3.0/tests/test_markers.py000077500000000000000000000010561451550407500203730ustar00rootroot00000000000000import 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-1.3.0/tests/test_response_overwriting.py000066400000000000000000000016141451550407500232210ustar00rootroot00000000000000import pytest from flask import Flask from flask import jsonify from flask import url_for class TestResponseOverwriting: """ we overwrite the app fixture here so we can test _monkeypatch_response_class (an autouse fixture) will return the original response_class since a json @property is already present in response_class """ @pytest.fixture def app(self): app = Flask(__name__) app.config["SECRET_KEY"] = "42" class MyResponse(app.response_class): @property def json(self): return 49 @app.route("/ping") def ping(): return jsonify(ping="pong") app.response_class = MyResponse return app def test_dont_rewrite_existing_implementation(self, accept_json, client): res = client.get(url_for("ping"), headers=accept_json) assert res.json == 49 pytest-flask-1.3.0/tox.ini000066400000000000000000000021721451550407500154640ustar00rootroot00000000000000[tox] envlist = py{37,38,39,linting} [pytest] norecursedirs = .git .tox env coverage docs pep8ignore = docs/conf.py ALL pep8maxlinelength = 79 [testenv:dev] commands = envdir = venv deps= -rrequirements/main.txt -rrequirements/test.txt -rrequirements/docs.txt pre-commit>=1.11.0 tox basepython = python3.8 usedevelop = True [testenv] usedevelop = True deps = -rrequirements/main.txt -rrequirements/test.txt commands = coverage run -m pytest {posargs:tests} coverage combine coverage report [coverage:report] fail_under=90 [coverage:run] source=pytest_flask concurrency=multiprocessing [tool:pytest] addopts = -v --basetemp={envtmpdir} --confcutdir=tests [testenv:pre] pip_pre=true usedevelop = {[testenv]usedevelop} deps = {[testenv]deps} commands = {[testenv]commands} [testenv:linting] skip_install = True basepython = python3.8 deps = pre-commit>=1.11.0 commands = pre-commit run --all-files --show-diff-on-failure {posargs:} [testenv:docs] changedir = docs skipsdist = True usedevelop = True deps = -r requirements/docs.txt commands = sphinx-build -W -b html . _build