2018-02-10 06:39:05 +08:00
|
|
|
import os
|
|
|
|
import tempfile
|
|
|
|
|
|
|
|
import pytest
|
2019-06-01 23:35:03 +08:00
|
|
|
|
2018-02-10 06:39:05 +08:00
|
|
|
from flaskr import create_app
|
2019-06-01 23:35:03 +08:00
|
|
|
from flaskr.db import get_db
|
|
|
|
from flaskr.db import init_db
|
2018-02-10 06:39:05 +08:00
|
|
|
|
|
|
|
# read in SQL for populating test data
|
2019-05-07 03:39:41 +08:00
|
|
|
with open(os.path.join(os.path.dirname(__file__), "data.sql"), "rb") as f:
|
|
|
|
_data_sql = f.read().decode("utf8")
|
2018-02-10 06: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
|
2019-05-07 03:39:41 +08:00
|
|
|
app = create_app({"TESTING": True, "DATABASE": db_path})
|
2018-02-10 06:39:05 +08:00
|
|
|
|
|
|
|
# create the database and load test data
|
|
|
|
with app.app_context():
|
|
|
|
init_db()
|
|
|
|
get_db().executescript(_data_sql)
|
|
|
|
|
|
|
|
yield app
|
|
|
|
|
|
|
|
# close and remove the temporary database
|
|
|
|
os.close(db_fd)
|
|
|
|
os.unlink(db_path)
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def client(app):
|
|
|
|
"""A test client for the app."""
|
|
|
|
return app.test_client()
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def runner(app):
|
|
|
|
"""A test runner for the app's Click commands."""
|
|
|
|
return app.test_cli_runner()
|
|
|
|
|
|
|
|
|
2020-04-05 00:43:06 +08:00
|
|
|
class AuthActions:
|
2018-02-10 06:39:05 +08:00
|
|
|
def __init__(self, client):
|
|
|
|
self._client = client
|
|
|
|
|
2019-05-07 03:39:41 +08:00
|
|
|
def login(self, username="test", password="test"):
|
2018-02-10 06:39:05 +08:00
|
|
|
return self._client.post(
|
2019-05-07 03:39:41 +08:00
|
|
|
"/auth/login", data={"username": username, "password": password}
|
2018-02-10 06:39:05 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
def logout(self):
|
2019-05-07 03:39:41 +08:00
|
|
|
return self._client.get("/auth/logout")
|
2018-02-10 06:39:05 +08:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def auth(client):
|
|
|
|
return AuthActions(client)
|