flask/examples/tutorial/tests/conftest.py

63 lines
1.4 KiB
Python
Raw Normal View History

2018-02-09 14:39:05 -08:00
import os
import tempfile
import pytest
2018-02-09 14:39:05 -08:00
from flaskr import create_app
from flaskr.db import get_db
from flaskr.db import init_db
2018-02-09 14:39:05 -08:00
# read in SQL for populating test data
with open(os.path.join(os.path.dirname(__file__), "data.sql"), "rb") as f:
_data_sql = f.read().decode("utf8")
2018-02-09 14:39:05 -08:00
@pytest.fixture
def app():
"""Create and configure a new app instance for each test."""
# create a temporary file to isolate the database for each test
db_fd, db_path = tempfile.mkstemp()
# create the app with common test config
2024-06-19 16:42:19 +02:00
test_app = create_app({"TESTING": True, "DATABASE": db_path})
2018-02-09 14:39:05 -08:00
# create the database and load test data
2024-06-19 16:42:19 +02:00
with test_app.app_context():
2018-02-09 14:39:05 -08:00
init_db()
get_db().executescript(_data_sql)
2024-06-19 16:42:19 +02:00
yield test_app
2018-02-09 14:39:05 -08:00
# close and remove the temporary database
os.close(db_fd)
os.unlink(db_path)
@pytest.fixture
2024-06-19 16:42:19 +02:00
def client(app_):
2018-02-09 14:39:05 -08:00
"""A test client for the app."""
2024-06-19 16:42:19 +02:00
return app_.test_client()
2018-02-09 14:39:05 -08:00
@pytest.fixture
2024-06-19 16:42:19 +02:00
def runner(app_):
2018-02-09 14:39:05 -08:00
"""A test runner for the app's Click commands."""
2024-06-19 16:42:19 +02:00
return app_.test_cli_runner()
2018-02-09 14:39:05 -08:00
2020-04-04 09:43:06 -07:00
class AuthActions:
2024-06-19 16:42:19 +02:00
def __init__(self, client_obj):
self._client = client_obj
2018-02-09 14:39:05 -08:00
def login(self, username="test", password="test"):
2018-02-09 14:39:05 -08:00
return self._client.post(
"/auth/login", data={"username": username, "password": password}
2018-02-09 14:39:05 -08:00
)
def logout(self):
return self._client.get("/auth/logout")
2018-02-09 14:39:05 -08:00
@pytest.fixture
def auth(client):
return AuthActions(client)