authentik.flows.tests
Test helpers
1"""Test helpers""" 2 3from collections.abc import Callable, Generator 4from contextlib import contextmanager 5from json import loads 6from typing import Any 7from unittest.mock import MagicMock, patch 8 9from django.http.response import HttpResponse 10from django.test import TestCase 11from django.urls.base import reverse 12from rest_framework.test import APITestCase 13 14from authentik.core.models import User 15from authentik.flows.models import Flow 16from authentik.flows.planner import FlowPlan 17from authentik.flows.views.executor import SESSION_KEY_PLAN 18 19 20class _FlowTestCase: 21 """Helpers for testing flows and stages.""" 22 23 def assertStageResponse( 24 self, 25 response: HttpResponse, 26 flow: Flow | None = None, 27 user: User | None = None, 28 **kwargs, 29 ) -> dict[str, Any]: 30 """Assert various attributes of a stage response""" 31 self.assertEqual(response.status_code, 200) 32 raw_response = loads(response.content.decode()) 33 self.assertIsNotNone(raw_response["component"]) 34 if flow: 35 self.assertIn("flow_info", raw_response) 36 self.assertTrue( 37 raw_response["flow_info"]["cancel_url"].startswith( 38 reverse("authentik_flows:cancel") 39 ) 40 ) 41 # We don't check the flow title since it will most likely go 42 # through ChallengeStageView.format_title() so might not match 1:1 43 # self.assertEqual(raw_response["flow_info"]["title"], flow.title) 44 self.assertIsNotNone(raw_response["flow_info"]["title"]) 45 if user: 46 self.assertEqual(raw_response["pending_user"], user.username) 47 self.assertEqual(raw_response["pending_user_avatar"], user.avatar) 48 for key, expected in kwargs.items(): 49 self.assertEqual(raw_response[key], expected) 50 return raw_response 51 52 def get_flow_plan(self) -> FlowPlan | None: 53 return self.client.session.get(SESSION_KEY_PLAN) 54 55 def set_flow_plan(self, plan: FlowPlan): 56 session = self.client.session 57 session[SESSION_KEY_PLAN] = plan 58 session.save() 59 60 def assertStageRedirects(self, response: HttpResponse, to: str) -> dict[str, Any]: 61 """Wrapper around assertStageResponse that checks for a redirect""" 62 return self.assertStageResponse(response, component="xak-flow-redirect", to=to) 63 64 @contextmanager 65 def assertFlowFinishes(self) -> Generator[Callable[[], FlowPlan]]: 66 """Capture the flow plan before the flow finishes and return it""" 67 try: 68 with patch("authentik.flows.views.executor.FlowExecutorView.cancel", MagicMock()): 69 yield lambda: self.client.session.get(SESSION_KEY_PLAN) 70 finally: 71 pass 72 73 74class FlowTestCase(_FlowTestCase, TestCase): 75 """Flow test case with a standard Django client""" 76 77 78class APIFlowTestCase(_FlowTestCase, APITestCase): 79 """Flow test case with a DRF client"""
75class FlowTestCase(_FlowTestCase, TestCase): 76 """Flow test case with a standard Django client"""
Flow test case with a standard Django client
Flow test case with a DRF client