### Install pytest-flask Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/tutorial.rst Installs the pytest-flask package using pip. This is the first step to integrate pytest with Flask applications. ```bash pip install pytest-flask ``` -------------------------------- ### Run Test Suite Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/tutorial.rst Executes the test suite using the pytest command. Pytest automatically discovers and runs tests in the project. ```bash pytest ``` -------------------------------- ### GET Request Example Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Demonstrates how to perform a GET request to a Flask application using the test client provided by pytest-flask. It includes setting up a route, starting the live server, and asserting the response status 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 ``` -------------------------------- ### Install pytest-flask Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/index.rst Installs the pytest-flask plugin using pip. This is the first step to using the plugin in your project. ```bash pip install pytest-flask ``` -------------------------------- ### Configure Application Fixture Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/tutorial.rst Defines the pytest fixture for the Flask application. This fixture is responsible for creating and returning the Flask app instance, which pytest will use to run tests. ```python from myapp import create_app @pytest.fixture def app(): app = create_app() return app ``` -------------------------------- ### POST Request Example Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Demonstrates how to perform a POST request to a Flask application using the test client provided by pytest-flask. It includes setting up a route, starting the live server, and asserting the response status 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 ``` -------------------------------- ### Set Up Development Environment with Tox Source: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst Creates a virtual environment using Tox and installs pytest-flask in editable mode with development dependencies. ```bash tox -e dev source venv/bin/activate ``` -------------------------------- ### Minimal Flask Application Factory Example Source: https://github.com/pytest-dev/pytest-flask/blob/master/README.rst Demonstrates a basic Flask application factory pattern in Python, creating a minimal Flask app with a 'Hello, World!' route. This serves as a foundation for testing with pytest-flask. ```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 ``` -------------------------------- ### Installing and Using pytest-xdist for Parallel Testing Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Provides instructions on how to install the pytest-xdist plugin and run tests in parallel using the '-n' command-line option for performance improvements. ```bash pip install pytest-xdist ``` ```bash pytest -n ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst Installs pre-commit hooks to ensure code quality and consistency before committing changes. ```bash pre-commit install ``` -------------------------------- ### Blueprint Route Example Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Illustrates how to define a route using Flask's Blueprint implementation, including specifying methods and an endpoint name. This is relevant for organizing application routes. ```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 ``` -------------------------------- ### Direct Route Reference Example Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Shows an alternative way to reference a route function directly from the live_server implementation, bypassing the need for an explicit endpoint name. This simplifies testing when endpoint names are not critical. ```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 ``` -------------------------------- ### Single-sourcing package version Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Following Python Packaging User Guide recommendations, version 0.7.1 implemented single-sourcing for the package version to maintain consistency. ```python https://packaging.python.org/en/latest/single_source_version.html#single-sourcing-the-version ``` -------------------------------- ### Release random port before live server start Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.6.2 ensures that the random port is released before starting the application's live server, preventing port conflicts. ```python release the random port ``` -------------------------------- ### Accessing JSON Data in API Responses Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Shows how to easily access JSON data from API responses in tests. It also includes an example of how to handle custom JSON deserialization by overriding the response class. ```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'} ``` ```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 ``` -------------------------------- ### Live Server Configuration Options Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Details command-line options for configuring the live server fixture in pytest-flask, including host, port, and startup behavior. ```APIDOC --live-server-host Set the host name used by the live_server fixture. --live-server-port Select the port the live server will use. --start-live-server / --no-start-live-server Control whether the live server starts automatically. --live-server-wait Set the live server wait timeout for checking server availability. ``` -------------------------------- ### Live Server Command-Line Options Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Details the command-line options for managing the live server, including '--start-live-server' (default behavior), '--no-start-live-server' to disable automatic startup, '--live-server-wait' for timeout configuration, and '--live-server-port' to specify a fixed port. ```bash # Start live server automatically (default) pytest --start-live-server ``` ```bash # Do not start live server automatically pytest --no-start-live-server ``` ```bash # Set live server wait timeout to 10 seconds pytest --live-server-wait=10 ``` ```bash # Use a fixed port for the live server pytest --live-server-port=8080 ``` ```ini [pytest] addopts = --no-start-live-server ``` -------------------------------- ### Content Negotiation with Accept Headers Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Demonstrates testing content negotiation in a Flask application using predefined 'accept_*' fixtures. These fixtures provide common Accept headers for testing different media types. ```python def test_api_endpoint(accept_json, client): res = client.get(url_for('api.endpoint'), headers=accept_json) assert res.mimetype == 'application/json' ``` -------------------------------- ### Using the 'live_server' Fixture Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Explains how to use the 'live_server' fixture to run the application in a separate process, which is useful for integration tests with tools like Selenium. It shows how to retrieve the server's URL and dynamically add routes. ```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 ``` ```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() ``` -------------------------------- ### Clone pytest-flask Repository Source: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst Clones the main pytest-flask repository to your local machine. This is the first step in setting up your development environment. ```bash git clone https://github.com/pytest-dev/pytest-flask cd pytest-flask ``` -------------------------------- ### Run Full Test Suite with Tox Source: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst Runs the complete test suite across all supported Python versions using Tox. This is recommended before submitting a pull request. ```bash tox ``` -------------------------------- ### Using the 'client' Fixture for Application Testing Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Illustrates the usage of the 'client' fixture, which provides an instance of app.test_client, enabling tests to make requests to the Flask application. It highlights that a request context is automatically pushed. ```python def test_myview(client): assert client.get(url_for('myview')).status_code == 200 ``` -------------------------------- ### Pytest Fixture for Flask Application Source: https://github.com/pytest-dev/pytest-flask/blob/master/README.rst Shows how to define a pytest fixture in conftest.py to provide a Flask application instance for testing. This fixture utilizes the application factory pattern. ```python from myapp import create_app import pytest @pytest.fixture def app(): app = create_app() return app ``` -------------------------------- ### Accept Header Fixtures Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Provides descriptions for pytest-flask fixtures that generate common Accept headers for testing content negotiation. These include */*, application/json, and application/json-p. ```APIDOC ``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``. ``` -------------------------------- ### Run Tests Locally Source: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst Executes the test suite for the current environment using pytest. This is a quick way to verify your changes. ```bash pytest ``` -------------------------------- ### Define Flask App Fixture Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/index.rst Demonstrates how to define a pytest fixture for a Flask application in conftest.py. This fixture provides the Flask app instance to your tests. ```python from myapp import create_app @pytest.fixture def app(): app = create_app() return app ``` -------------------------------- ### Extend Application Configuration Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Demonstrates how to extend the Flask application's configuration using pytest markers. This allows for setting configuration options like debug mode during test execution. ```python @pytest.mark.options(debug=False) def test_app(app): assert not app.debug, 'Ensure the app is not in debug mode' ``` -------------------------------- ### Live Server Scope Configuration Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Describes how the scope of the live_server fixture can be configured via pytest.ini. ```APIDOC live_server fixture scope: By default, the live_server fixture is session-scoped. This can be changed by setting the `live-server_scope` option in your `pytest.ini` file. ``` -------------------------------- ### Add package documentation Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.7.0 focused on improving the project's documentation by adding comprehensive package documentation. -------------------------------- ### pytest.mark.options Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst A pytest marker used to pass configuration options directly to the Flask application's config during testing. It accepts keyword arguments which are then applied as configuration settings. ```APIDOC ``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: Options to be passed to the Flask application config. ``` -------------------------------- ### Push Changes to Fork Source: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst Pushes your local branch with your changes to your GitHub fork. This prepares your changes for a pull request. ```bash git push --set-upstream fork your-branch-name ``` -------------------------------- ### Add live_server fixture Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.5.0 introduced the `live_server` fixture, which enables running the application in the background for live testing. ```python live_server fixture ``` -------------------------------- ### Generate Test Coverage Report Source: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst Runs tests with coverage enabled, combines coverage data, and generates an HTML report to identify untested code sections. ```bash coverage run --concurrency=multiprocessing -m pytest coverage combine coverage html ``` -------------------------------- ### Add Fork as Remote Source: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst Adds your GitHub fork as a remote repository, allowing you to push your contributions. Replace '{username}' with your actual GitHub username. ```bash git remote add fork https://github.com/{username}/pytest-flask ``` -------------------------------- ### pytest-flask Dependencies Source: https://github.com/pytest-dev/pytest-flask/blob/master/requirements/main.txt This snippet lists the core dependencies required for pytest-flask. It ensures compatibility with pytest version 5.2 and above, and integrates with Flask and Werkzeug for application testing. ```python pytest>=5.2 Flask Werkzeug ``` -------------------------------- ### Configure Live Server Port Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Sets a fixed port for the live server. This can be configured in pytest.ini using the 'addopts' setting. ```ini [pytest] addopts = --live-server-port=5000 ``` -------------------------------- ### Introduce request_ctx fixture Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.8.0 introduced the `request_ctx` fixture, which provides access to all request-relevant information within Flask tests. ```python request_ctx ``` -------------------------------- ### Using 'client_class' Fixture for Class-Based Tests Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Demonstrates how to use the 'client_class' fixture within a test class to access the test client via 'self.client', facilitating class-based testing structures. ```python @pytest.mark.usefixtures('client_class') class TestSuite: def test_myview(self): assert self.client.get(url_for('myview')).status_code == 200 ``` -------------------------------- ### Accessing Context-Bound Objects in Tests Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Demonstrates how pytest-flask allows direct access to context-bound objects like url_for within tests without explicit context managers. ```python def test_app(client): assert client.get(url_for('myview')).status_code == 200 ``` -------------------------------- ### Create a New Branch for Contributions Source: https://github.com/pytest-dev/pytest-flask/blob/master/CONTRIBUTING.rst Fetches the latest changes from the origin and creates a new branch for your feature or bug fix. This helps in organizing contributions. ```bash git fetch origin git checkout -b your-branch-name origin/master ``` -------------------------------- ### Live Server Clean Stop Behavior Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Explains how the live_server fixture attempts to stop the server cleanly and how to disable this behavior. ```APIDOC Live Server Shutdown: The live_server fixture attempts to stop the server cleanly by emitting a SIGINT signal and waiting 5 seconds. If the server is still running after 5 seconds, it will be forcefully terminated. --no-live-server-clean-stop Disables the clean server stop behavior. ``` -------------------------------- ### Fix typo in --liveserver-port help Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.6.0 corrected a typo in the help text for the `--liveserver-port` option. ```python --liveserver-port ``` -------------------------------- ### JSONReponse Comparison with Status Codes Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Demonstrates how the JSONReponse object in pytest-flask can be directly compared with HTTP status codes for assertion. ```python assert client.get('invalid-route', headers=[('Accept', 'application/json')]) == 404 ``` -------------------------------- ### Use codecs module for file opening Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.3.2 switched to using the `codecs` module for opening files. This prevents potential errors when dealing with files containing non-ASCII characters. ```python codecs module ``` -------------------------------- ### README reST formatting Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst In version 0.6.3, the README file was updated with reStructuredText (reST) formatting to enhance readability and structure. ```python reST formatting ``` -------------------------------- ### Pin package dependencies Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.3.3 explicitly pinned the dependencies of the package along with their specific versions to ensure compatibility and reproducibility. ```python pin package dependencies ``` -------------------------------- ### Use monkeypath for teardown Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst In version 0.7.5, the pytest `monkeypath` fixture was utilized to manage the teardown of application configuration, ensuring a clean state after tests. ```python monkeypath ``` -------------------------------- ### Rename app marker to options Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst In version 0.9.0, the marker used to pass options to the application was renamed from `pytest.mark.app` to `pytest.mark.options` for better clarity. ```python pytest.mark.options ``` -------------------------------- ### Change Live Server Scope Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/features.rst Allows changing the scope of the live server fixture from the default 'session' to 'function' for better test isolation when the server has global state. ```ini [pytest] live_server_scope = function ``` -------------------------------- ### Add client_class fixture Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.4.0 introduced the `client_class` fixture, specifically designed for use in class-based tests. ```python client_class fixture ``` -------------------------------- ### Bind live server to random port Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.6.1 changed the live server binding to use a random port instead of a fixed one (like 5000). This allows for parallel test execution with pytest-xdist. ```python Bind live server to a random port ``` -------------------------------- ### Include package requirements in distribution Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.3.4 ensured that package requirements were correctly included in the distribution files. ```python package requirements ``` -------------------------------- ### Rewrite live server name with monkeypatch Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst Version 0.7.2 used the pytest `monkeypatch` fixture to rewrite the live server name, likely for testing purposes or to manage server instances. ```python monkeypatch ``` -------------------------------- ### Remove --liveserver-port option Source: https://github.com/pytest-dev/pytest-flask/blob/master/docs/changelog.rst As part of the change to random port binding, version 0.6.1 also removed the `--liveserver-port` command-line option. ```python --liveserver-port ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.