Skip to content
Merged
17 changes: 17 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,20 @@

# Rate limiting uses Redis + FastAPILimiter.init(); tests skip that unless you opt in.
os.environ["USE_REDIS"] = "false"


def pytest_configure(config):
"""
Ensure the SQLite schema exists before any test runs.

Tests that go through ``TestClient(app)`` get the schema for free because
``ubiblio.main`` calls ``Base.metadata.create_all`` at import time, but tests
that exercise lower-level helpers (e.g. ``tests/dependencies/test_auth.py``)
don't import ``ubiblio.main``. On a clean CI checkout there's no ``sql_app.db``,
so they fail with "no such table: users". Importing the schema here is enough
to make either path work.
"""
from ubiblio import models
from ubiblio.database import engine

models.Base.metadata.create_all(bind=engine)
Empty file added tests/dependencies/__init__.py
Empty file.
21 changes: 21 additions & 0 deletions tests/dependencies/test_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import pytest
from fastapi import HTTPException

from ubiblio.dependencies.auth import get_admin_user, get_user
from tests.helpers.create_test_user import create_test_user


class TestGetAdminUser:
def test_admin_user_is_returned(self):
with create_test_user(is_admin=True) as test_user:
user = get_user(test_user.username)
result = get_admin_user(user)
assert result is user

def test_non_admin_raises_403(self):
with create_test_user(is_admin=False) as test_user:
user = get_user(test_user.username)
with pytest.raises(HTTPException) as exc_info:
get_admin_user(user)
assert exc_info.value.status_code == 403
assert exc_info.value.detail == "You are not authorized to add books. Only an admin can do this."
17 changes: 14 additions & 3 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ def test_head_on_public_endpoints_returns_200(self, path):

@pytest.mark.parametrize("path", [
"/searchbooks",
"/add_book",
"/scan_isbn",
"/addisbn",
"/genre/",
])
def test_head_on_authenticated_endpoints(self, path):
Expand All @@ -39,3 +36,17 @@ def test_head_on_authenticated_endpoints(self, path):
f"HEAD {path} returned {response.status_code} instead of 200"
)
assert response.content == b""

@pytest.mark.parametrize("path", [
"/add_book",
"/addisbn",
"/scan_isbn",
])
def test_head_on_admin_endpoints(self, path):
with create_test_user(is_admin=True) as user:
with access_token_cookie(self.client, user):
response = self.client.head(path, follow_redirects=False)
assert response.status_code == 200, (
f"HEAD {path} returned {response.status_code} instead of 200"
)
assert response.content == b""
319 changes: 0 additions & 319 deletions ubiblio/dependencies.py

This file was deleted.

Loading
Loading