I just want the tutorial

This commit is contained in:
Jose Palazon 2024-09-06 00:18:20 +01:00
parent 2fec0b206c
commit 127440c727
235 changed files with 46 additions and 33059 deletions

View file

@ -1,160 +1,62 @@
import os
import pkgutil
import sys
import tempfile
import pytest
from _pytest import monkeypatch
from flask import Flask
from flask.globals import request_ctx
from flaskr import create_app
from flaskr.db import get_db
from flaskr.db import init_db
@pytest.fixture(scope="session", autouse=True)
def _standard_os_environ():
"""Set up ``os.environ`` at the start of the test session to have
standard values. Returns a list of operations that is used by
:func:`._reset_os_environ` after each test.
"""
mp = monkeypatch.MonkeyPatch()
out = (
(os.environ, "FLASK_ENV_FILE", monkeypatch.notset),
(os.environ, "FLASK_APP", monkeypatch.notset),
(os.environ, "FLASK_DEBUG", monkeypatch.notset),
(os.environ, "FLASK_RUN_FROM_CLI", monkeypatch.notset),
(os.environ, "WERKZEUG_RUN_MAIN", monkeypatch.notset),
)
for _, key, value in out:
if value is monkeypatch.notset:
mp.delenv(key, False)
else:
mp.setenv(key, value)
yield out
mp.undo()
@pytest.fixture(autouse=True)
def _reset_os_environ(monkeypatch, _standard_os_environ):
"""Reset ``os.environ`` to the standard environ after each test,
in case a test changed something without cleaning up.
"""
monkeypatch._setitem.extend(_standard_os_environ)
# 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")
@pytest.fixture
def app():
app = Flask("flask_test", root_path=os.path.dirname(__file__))
app.config.update(
TESTING=True,
SECRET_KEY="test key",
)
return 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
app = create_app({"TESTING": True, "DATABASE": db_path})
# create the database and load test data
with app.app_context():
init_db()
get_db().executescript(_data_sql)
@pytest.fixture
def app_ctx(app):
with app.app_context() as ctx:
yield ctx
yield app
@pytest.fixture
def req_ctx(app):
with app.test_request_context() as ctx:
yield ctx
# 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 test_apps(monkeypatch):
monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), "test_apps"))
original_modules = set(sys.modules.keys())
yield
# Remove any imports cached during the test. Otherwise "import app"
# will work in the next test even though it's no longer on the path.
for key in sys.modules.keys() - original_modules:
sys.modules.pop(key)
def runner(app):
"""A test runner for the app's Click commands."""
return app.test_cli_runner()
@pytest.fixture(autouse=True)
def leak_detector():
yield
class AuthActions:
def __init__(self, client):
self._client = client
# make sure we're not leaking a request context since we are
# testing flask internally in debug mode in a few cases
leaks = []
while request_ctx:
leaks.append(request_ctx._get_current_object())
request_ctx.pop()
def login(self, username="test", password="test"):
return self._client.post(
"/auth/login", data={"username": username, "password": password}
)
assert leaks == []
@pytest.fixture(params=(True, False))
def limit_loader(request, monkeypatch):
"""Patch pkgutil.get_loader to give loader without get_filename or archive.
This provides for tests where a system has custom loaders, e.g. Google App
Engine's HardenedModulesHook, which have neither the `get_filename` method
nor the `archive` attribute.
This fixture will run the testcase twice, once with and once without the
limitation/mock.
"""
if not request.param:
return
class LimitedLoader:
def __init__(self, loader):
self.loader = loader
def __getattr__(self, name):
if name in {"archive", "get_filename"}:
raise AttributeError(f"Mocking a loader which does not have {name!r}.")
return getattr(self.loader, name)
old_get_loader = pkgutil.get_loader
def get_loader(*args, **kwargs):
return LimitedLoader(old_get_loader(*args, **kwargs))
monkeypatch.setattr(pkgutil, "get_loader", get_loader)
def logout(self):
return self._client.get("/auth/logout")
@pytest.fixture
def modules_tmp_path(tmp_path, monkeypatch):
"""A temporary directory added to sys.path."""
rv = tmp_path / "modules_tmp"
rv.mkdir()
monkeypatch.syspath_prepend(os.fspath(rv))
return rv
@pytest.fixture
def modules_tmp_path_prefix(modules_tmp_path, monkeypatch):
monkeypatch.setattr(sys, "prefix", os.fspath(modules_tmp_path))
return modules_tmp_path
@pytest.fixture
def site_packages(modules_tmp_path, monkeypatch):
"""Create a fake site-packages."""
py_dir = f"python{sys.version_info.major}.{sys.version_info.minor}"
rv = modules_tmp_path / "lib" / py_dir / "site-packages"
rv.mkdir(parents=True)
monkeypatch.syspath_prepend(os.fspath(rv))
return rv
@pytest.fixture
def purge_module(request):
def inner(name):
request.addfinalizer(lambda: sys.modules.pop(name, None))
return inner
def auth(client):
return AuthActions(client)