EcoSpecies-Atlas/apps/api/tests/test_auth.py

59 lines
2.2 KiB
Python

from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from ecospecies_api import auth, repository
class ContributorAuthTests(unittest.TestCase):
def setUp(self) -> None:
self.tempdir = tempfile.TemporaryDirectory()
db_path = Path(self.tempdir.name) / "test.db"
self.engine = create_engine(f"sqlite:///{db_path}", future=True)
self.session_local = sessionmaker(
bind=self.engine,
autoflush=False,
autocommit=False,
future=True,
)
self.repository_engine_patch = patch.object(repository, "create_db_engine", return_value=self.engine)
self.repository_session_patch = patch.object(repository, "SessionLocal", self.session_local)
self.auth_engine_patch = patch.object(auth, "create_db_engine", return_value=self.engine)
self.auth_session_patch = patch.object(auth, "SessionLocal", self.session_local)
self.repository_engine_patch.start()
self.repository_session_patch.start()
self.auth_engine_patch.start()
self.auth_session_patch.start()
def tearDown(self) -> None:
self.auth_session_patch.stop()
self.auth_engine_patch.stop()
self.repository_session_patch.stop()
self.repository_engine_patch.stop()
self.engine.dispose()
self.tempdir.cleanup()
def test_contributor_token_resolves_to_contributor_session(self) -> None:
registration = repository.register_contributor("author@example.org", True)
session = auth.resolve_auth_session({"Authorization": f"Bearer {registration['token']}"})
self.assertIsNotNone(session)
assert session is not None
self.assertEqual(session.username, "author@example.org")
self.assertEqual(session.role, "contributor")
def test_contributor_role_does_not_satisfy_editor(self) -> None:
self.assertTrue(auth.role_satisfies("editor", "contributor"))
self.assertFalse(auth.role_satisfies("contributor", "editor"))
if __name__ == "__main__":
unittest.main()