From abc8e5463467c4257cf856f96ea17ac30572447b Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Mon, 9 Oct 2023 15:59:00 -0400 Subject: [PATCH] Test refactoring to manage route testing with flask-login --- NOTES.md | 6 ++++++ tests/conftest.py | 15 ++++++++++++++- tests/test_routes.py | 8 ++++++-- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/NOTES.md b/NOTES.md index 48905c7..140d5ab 100644 --- a/NOTES.md +++ b/NOTES.md @@ -1,5 +1,11 @@ # Notes + +## Flask Login + +- [This basic usage article](https://realpython.com/using-flask-login-for-user-management-with-flask/) was a good refresher. I forgot that you need a couple of methods on the User class to use it. +- It was tougher to write tests until...I RTFM'd. https://flask-login.readthedocs.io/en/latest/#automated-testing + ## Toasts using Toastify.js [In depth example of a Toast](https://www.cssscript.com/simple-vanilla-javascript-toast-notification-library-toastify/) diff --git a/tests/conftest.py b/tests/conftest.py index 8844909..4b4e0a2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,7 +1,9 @@ import pytest +from flask_login.test_client import FlaskLoginClient from htmx_contact import create_app from htmx_contact.config import ContactSettings +from htmx_contact.models import User @pytest.fixture() @@ -9,9 +11,15 @@ def test_config(): return ContactSettings(SECRET_KEY=b"secrettestingvalue") +@pytest.fixture() +def test_user(): + return User(id=1, primary_email="test", password="password", username="test") + + @pytest.fixture() def app(test_config): app = create_app(config=test_config) + app.test_client_class = FlaskLoginClient app.config.update( { "TESTING": True, @@ -26,10 +34,15 @@ def app(test_config): @pytest.fixture() -def client(app): +def anynomous_client(app): return app.test_client() +@pytest.fixture() +def client(app, test_user): + return app.test_client(user=test_user) + + @pytest.fixture() def runner(app): return app.test_cli_runner() diff --git a/tests/test_routes.py b/tests/test_routes.py index 42446b2..9624211 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -4,7 +4,11 @@ def test_index_redirect_to_contacts(client): assert response.headers.get("Location") == "/contacts" +def test_login_get_contacts(anynomous_client): + response = anynomous_client.get("/contacts", follow_redirects=False) + assert response.status_code == 302 + + def test_get_contacts(client): - response = client.get("/contacts") + response = client.get("/contacts", follow_redirects=True) assert response.status_code == 200 - assert "htmx" in response.text.lower()