How to pytest a Flask Endpoint

Viewed 9451

I'm getting started with Flask and Pytest in order to implemente a rest service with unit test, but i'm having some troouble.

I'll 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

2 Answers

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.

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.

Related