Python
May 12, 2024
Использование pytest в Flask
Краткое представление о том, как использовать pytest в фреймворке Flask.
Структура проекта
/WebApp ├── flask/ │ ├── __init__.py │ ├── app.py │ ├── templates/ │ ├── routes/ │ │ └── hello.py │ └── static/ │ └── tests/ ├── conftest.py └── test_hello.py
Tests
conftest.py
import sys import os #SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) #sys.path.append(os.path.dirname(SCRIPT_DIR)) import pytest from flask import create_app @pytest.fixture() def app(): app = create_app() app.config.update({ "TESTING": True, }) # other setup can go here yield app # clean up / reset resources here @pytest.fixture() def client(app): return app.test_client() @pytest.fixture() def runner(app): return app.test_cli_runner()
test_hello.py
def test_hello(client): response = client.get('/') assert response.status_code == 200, f'Код ответа сервера: {response.status_code}'
Flask
Использовать шаблон построения "application factory" (Blueprint).
__init__.py
from flask import Flask def create_app(): app = Flask(__name__) from WebApp.routes.hello import mainPage app.register_blueprint(mainPage) return app
app.py
from flask import Flask from route.hello import mainPage app = Flask(__name__) app.register_blueprint(mainPage) if __name__ == "__main__": app.run()
/routes/hello.py
from flask import Blueprint mainPage = Blueprint('mainPages', __name__) @mainPage.route('/') def hello(): return "Hello, World!"