Xhark
Xhark

Reputation: 841

How to pytest a Flask Endpoint

I'm getting started with Flask and Pytest in order to implement a REST service with unit test, but i'm having some trouble.

I'd like to make a simple test for my simple endpoint but I keep getting a Working outside of application context. error when running the test.

This is the end point:

from flask import jsonify, request, Blueprint
STATUS_API = Blueprint('status_api', __name__)

def get_blueprint():
    """Return the blueprint for the main app module"""
    return STATUS_API


@STATUS_API.route('/status', methods=['GET'])
def get_status():
    return jsonify({
        'status' : 'alive'
    })

And this is how I'm trying to test it (I know it should fail the test):

import pytest

from routes import status_api

def test_get_status():
    assert status_api.get_status() == ''

I'm guessing I just cant try the method with out building the whole app. But if that's the case I dont really know how to aproach this problem

Upvotes: 6

Views: 17847

Answers (2)

Jürgen Gmach
Jürgen Gmach

Reputation: 6093

The Flask documentation on testing is pretty good.

Instead of importing the view functions, you should create a so called test client, e.g. as a pytest fixture.

For my last Flask app this looked like:

@pytest.fixture
def client():
    app = create_app()
    app.config['TESTING'] = True

    with app.app_context():
        with app.test_client() as client:
            yield client

(create_app is my app factory)

Then you can easily create tests as follows:

def test_status(client):
    rv = client.get('/stats')
    assert ...

As mentioned at the beginning, the official documentation is really good.

Upvotes: 8

Paul
Paul

Reputation: 135

Have you considered trying an API client/development tool? Insomnia and Postman are popular ones. Using one may be able to resolve this for you.

Upvotes: -1

Related Questions