Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
How to always provide a context for Flask app tested with PyTest?

I try to implement unit tests with Pytest on a Flask app and I have a hard time to do it.

My Flask application uses configuration files on most of the functions (here some_method) to illustrate. So it seems that I should provide a context for each call to any method that I would like to test. It seems that I can achieve it with "with app.app_context():" on each call.

I read the official testing documentation but they talk about creating a client. As I would like to do unit tests, I need to call sub functions which are not top level.

Is there a way to always provide a context without pushing the context manually on each call?

Please find below my current implementation:

main.py

from flask import current_app


def main(request):
    current_app.config.from_envvar('APPLICATION_SETTINGS')
    print(some_method())
    return 'OK'


def some_method():
    # doing some stuff using the context
    world = current_app.config['SECRET_KEY']
    return world

test_main.py

import pytest
from flask import current_app, Flask

from main import main, some_method

@pytest.fixture
def app():
    app = Flask(__name__)
    # load here any potential configuration configuration
    return app


def test_some_method(app):
    with app.app_context():
        # calling and doing some assertion
        some_method()

PS: I do not have app = Flask(name) in my main file because I am running on the Functions Framework

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

pytest-flask seems to configure the context on any call.

conftest.py

import pytest
from flask import Flask


@pytest.fixture
def app():
    app = Flask(__name__)
    return app

test_main.py

import pytest
from flask import current_app, Flask

from main import main, some_method

def test_some_method(app):
    #with app.app_context():
        # calling and doing some assertion
    some_method()

works.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda