2020-12-05 21:08:42 +00:00
|
|
|
"""authentik e2e testing utilities"""
|
2020-11-23 13:24:42 +00:00
|
|
|
import json
|
2021-09-08 18:04:56 +00:00
|
|
|
import os
|
2021-02-27 21:32:48 +00:00
|
|
|
from functools import lru_cache, wraps
|
2020-07-12 14:17:04 +00:00
|
|
|
from os import environ, makedirs
|
2020-09-11 21:21:11 +00:00
|
|
|
from time import sleep, time
|
2021-02-18 12:41:03 +00:00
|
|
|
from typing import Any, Callable, Optional
|
2020-06-19 17:34:27 +00:00
|
|
|
|
2021-11-23 17:46:51 +00:00
|
|
|
from channels.testing import ChannelsLiveServerTestCase
|
2020-06-07 17:30:56 +00:00
|
|
|
from django.apps import apps
|
2021-02-27 21:57:15 +00:00
|
|
|
from django.db import connection
|
2021-02-26 15:46:01 +00:00
|
|
|
from django.db.migrations.loader import MigrationLoader
|
|
|
|
from django.db.migrations.operations.special import RunPython
|
2020-10-22 12:05:29 +00:00
|
|
|
from django.test.testcases import TransactionTestCase
|
2021-02-20 17:58:50 +00:00
|
|
|
from django.urls import reverse
|
2020-09-11 21:21:11 +00:00
|
|
|
from docker import DockerClient, from_env
|
2021-10-03 21:04:59 +00:00
|
|
|
from docker.errors import DockerException
|
2020-09-11 21:21:11 +00:00
|
|
|
from docker.models.containers import Container
|
2020-06-20 15:06:00 +00:00
|
|
|
from selenium import webdriver
|
2021-08-03 15:45:16 +00:00
|
|
|
from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException
|
2020-11-23 13:24:42 +00:00
|
|
|
from selenium.webdriver.common.by import By
|
2021-02-26 15:46:01 +00:00
|
|
|
from selenium.webdriver.common.keys import Keys
|
2020-06-20 15:06:00 +00:00
|
|
|
from selenium.webdriver.remote.webdriver import WebDriver
|
2021-02-21 22:30:31 +00:00
|
|
|
from selenium.webdriver.remote.webelement import WebElement
|
2020-06-20 15:06:00 +00:00
|
|
|
from selenium.webdriver.support.ui import WebDriverWait
|
2021-01-01 14:39:43 +00:00
|
|
|
from structlog.stdlib import get_logger
|
2020-06-19 17:34:27 +00:00
|
|
|
|
2020-12-05 21:08:42 +00:00
|
|
|
from authentik.core.api.users import UserSerializer
|
|
|
|
from authentik.core.models import User
|
2021-11-23 20:30:02 +00:00
|
|
|
from authentik.core.tests.utils import create_test_admin_user
|
2021-02-27 22:33:15 +00:00
|
|
|
from authentik.managed.manager import ObjectManager
|
2020-06-20 21:52:06 +00:00
|
|
|
|
2021-11-23 18:15:37 +00:00
|
|
|
RETRIES = int(environ.get("RETRIES", "3"))
|
2020-06-20 21:52:06 +00:00
|
|
|
|
2020-06-19 17:34:27 +00:00
|
|
|
|
2021-09-08 18:04:56 +00:00
|
|
|
def get_docker_tag() -> str:
|
|
|
|
"""Get docker-tag based off of CI variables"""
|
|
|
|
env_pr_branch = "GITHUB_HEAD_REF"
|
|
|
|
default_branch = "GITHUB_REF"
|
|
|
|
branch_name = os.environ.get(default_branch, "master")
|
|
|
|
if os.environ.get(env_pr_branch, "") != "":
|
|
|
|
branch_name = os.environ[env_pr_branch]
|
|
|
|
branch_name = branch_name.replace("refs/heads/", "").replace("/", "-")
|
|
|
|
return f"gh-{branch_name}"
|
|
|
|
|
|
|
|
|
2021-11-23 17:46:51 +00:00
|
|
|
class SeleniumTestCase(ChannelsLiveServerTestCase):
|
2020-06-20 21:52:06 +00:00
|
|
|
"""StaticLiveServerTestCase which automatically creates a Webdriver instance"""
|
|
|
|
|
2020-09-11 21:21:11 +00:00
|
|
|
container: Optional[Container] = None
|
2021-02-21 22:30:31 +00:00
|
|
|
wait_timeout: int
|
2021-11-23 20:30:02 +00:00
|
|
|
user: User
|
2020-09-11 21:21:11 +00:00
|
|
|
|
2020-06-20 15:06:00 +00:00
|
|
|
def setUp(self):
|
|
|
|
super().setUp()
|
2021-11-23 21:05:19 +00:00
|
|
|
# pylint: disable=invalid-name
|
2021-07-29 09:30:30 +00:00
|
|
|
self.maxDiff = None
|
2021-02-21 22:30:31 +00:00
|
|
|
self.wait_timeout = 60
|
2020-06-20 15:06:00 +00:00
|
|
|
self.driver = self._get_driver()
|
2020-06-20 22:26:29 +00:00
|
|
|
self.driver.maximize_window()
|
2020-09-29 13:01:01 +00:00
|
|
|
self.driver.implicitly_wait(30)
|
2021-02-21 22:30:31 +00:00
|
|
|
self.wait = WebDriverWait(self.driver, self.wait_timeout)
|
2020-06-26 13:06:46 +00:00
|
|
|
self.logger = get_logger()
|
2021-11-23 20:30:02 +00:00
|
|
|
self.user = create_test_admin_user(set_password=True)
|
2020-09-11 21:21:11 +00:00
|
|
|
if specs := self.get_container_specs():
|
|
|
|
self.container = self._start_container(specs)
|
|
|
|
|
2021-10-03 21:04:59 +00:00
|
|
|
def get_container_image(self, base: str) -> str:
|
|
|
|
"""Try to pull docker image based on git branch, fallback to master if not found."""
|
|
|
|
client: DockerClient = from_env()
|
|
|
|
image = f"{base}:gh-master"
|
|
|
|
try:
|
|
|
|
branch_image = f"{base}:{get_docker_tag()}"
|
|
|
|
client.images.pull(branch_image)
|
|
|
|
return branch_image
|
|
|
|
except DockerException:
|
|
|
|
client.images.pull(image)
|
|
|
|
return image
|
|
|
|
|
2021-02-18 12:41:03 +00:00
|
|
|
def _start_container(self, specs: dict[str, Any]) -> Container:
|
2020-09-11 21:21:11 +00:00
|
|
|
client: DockerClient = from_env()
|
|
|
|
container = client.containers.run(**specs)
|
2020-09-16 19:54:35 +00:00
|
|
|
if "healthcheck" not in specs:
|
|
|
|
return container
|
2020-09-11 21:21:11 +00:00
|
|
|
while True:
|
|
|
|
container.reload()
|
|
|
|
status = container.attrs.get("State", {}).get("Health", {}).get("Status")
|
|
|
|
if status == "healthy":
|
|
|
|
return container
|
|
|
|
self.logger.info("Container failed healthcheck")
|
|
|
|
sleep(1)
|
|
|
|
|
2021-06-03 20:17:18 +00:00
|
|
|
def output_container_logs(self, container: Optional[Container] = None):
|
|
|
|
"""Output the container logs to our STDOUT"""
|
2021-11-23 21:05:19 +00:00
|
|
|
_container = container or self.container
|
|
|
|
self.logger.debug("--------container logs", container=_container.image.tags[0])
|
|
|
|
for log in _container.logs().decode().split("\n"):
|
|
|
|
self.logger.debug(log, container=_container.image.tags[0])
|
|
|
|
self.logger.debug("--------end container logs", container=_container.image.tags[0])
|
2021-06-03 20:17:18 +00:00
|
|
|
|
2021-02-18 12:41:03 +00:00
|
|
|
def get_container_specs(self) -> Optional[dict[str, Any]]:
|
2020-09-11 21:21:11 +00:00
|
|
|
"""Optionally get container specs which will launched on setup, wait for the container to
|
|
|
|
be healthy, and deleted again on tearDown"""
|
|
|
|
return None
|
2020-06-20 15:06:00 +00:00
|
|
|
|
|
|
|
def _get_driver(self) -> WebDriver:
|
2021-11-12 08:37:05 +00:00
|
|
|
count = 0
|
|
|
|
while count < RETRIES:
|
|
|
|
try:
|
|
|
|
return webdriver.Remote(
|
|
|
|
command_executor="http://localhost:4444/wd/hub",
|
2021-11-22 10:28:26 +00:00
|
|
|
options=webdriver.ChromeOptions(),
|
2021-11-12 08:37:05 +00:00
|
|
|
)
|
|
|
|
except WebDriverException:
|
|
|
|
count += 1
|
|
|
|
raise ValueError(f"Webdriver failed after {RETRIES}.")
|
2020-06-20 15:06:00 +00:00
|
|
|
|
|
|
|
def tearDown(self):
|
2020-07-23 18:03:35 +00:00
|
|
|
if "TF_BUILD" in environ:
|
2021-04-02 21:23:09 +00:00
|
|
|
makedirs("selenium_screenshots/", exist_ok=True)
|
2021-08-03 15:45:16 +00:00
|
|
|
screenshot_file = f"selenium_screenshots/{self.__class__.__name__}_{time()}.png"
|
2020-07-12 14:17:04 +00:00
|
|
|
self.driver.save_screenshot(screenshot_file)
|
|
|
|
self.logger.warning("Saved screenshot", file=screenshot_file)
|
2021-03-24 10:57:56 +00:00
|
|
|
self.logger.debug("--------browser logs")
|
2020-06-26 13:06:46 +00:00
|
|
|
for line in self.driver.get_log("browser"):
|
2021-08-03 15:45:16 +00:00
|
|
|
self.logger.debug(line["message"], source=line["source"], level=line["level"])
|
2021-03-24 10:57:56 +00:00
|
|
|
self.logger.debug("--------end browser logs")
|
2020-09-11 21:21:11 +00:00
|
|
|
if self.container:
|
2021-06-03 20:17:18 +00:00
|
|
|
self.output_container_logs()
|
2020-09-11 21:21:11 +00:00
|
|
|
self.container.kill()
|
2020-06-20 15:06:00 +00:00
|
|
|
self.driver.quit()
|
2020-06-20 15:06:15 +00:00
|
|
|
super().tearDown()
|
2020-06-20 15:06:00 +00:00
|
|
|
|
2020-06-26 14:21:59 +00:00
|
|
|
def wait_for_url(self, desired_url):
|
|
|
|
"""Wait until URL is `desired_url`."""
|
2020-06-30 14:36:30 +00:00
|
|
|
self.wait.until(
|
2020-09-16 21:31:16 +00:00
|
|
|
lambda driver: driver.current_url == desired_url,
|
2020-06-30 14:36:30 +00:00
|
|
|
f"URL {self.driver.current_url} doesn't match expected URL {desired_url}",
|
|
|
|
)
|
2020-06-26 14:21:59 +00:00
|
|
|
|
2020-06-20 21:56:35 +00:00
|
|
|
def url(self, view, **kwargs) -> str:
|
|
|
|
"""reverse `view` with `**kwargs` into full URL using live_server_url"""
|
|
|
|
return self.live_server_url + reverse(view, kwargs=kwargs)
|
|
|
|
|
2021-09-16 15:30:16 +00:00
|
|
|
def if_user_url(self, view) -> str:
|
2020-11-23 13:24:42 +00:00
|
|
|
"""same as self.url() but show URL in shell"""
|
2021-09-16 15:30:16 +00:00
|
|
|
return f"{self.live_server_url}/if/user/#{view}"
|
2020-11-23 13:24:42 +00:00
|
|
|
|
2021-08-03 15:45:16 +00:00
|
|
|
def get_shadow_root(self, selector: str, container: Optional[WebElement] = None) -> WebElement:
|
2021-02-21 22:30:31 +00:00
|
|
|
"""Get shadow root element's inner shadowRoot"""
|
|
|
|
if not container:
|
|
|
|
container = self.driver
|
|
|
|
shadow_root = container.find_element(By.CSS_SELECTOR, selector)
|
2021-08-03 15:45:16 +00:00
|
|
|
element = self.driver.execute_script("return arguments[0].shadowRoot", shadow_root)
|
2021-02-21 22:30:31 +00:00
|
|
|
return element
|
|
|
|
|
2021-02-26 15:46:01 +00:00
|
|
|
def login(self):
|
|
|
|
"""Do entire login flow and check user afterwards"""
|
|
|
|
flow_executor = self.get_shadow_root("ak-flow-executor")
|
2021-08-03 15:45:16 +00:00
|
|
|
identification_stage = self.get_shadow_root("ak-stage-identification", flow_executor)
|
2021-02-26 15:46:01 +00:00
|
|
|
|
2021-08-03 15:45:16 +00:00
|
|
|
identification_stage.find_element(By.CSS_SELECTOR, "input[name=uidField]").click()
|
|
|
|
identification_stage.find_element(By.CSS_SELECTOR, "input[name=uidField]").send_keys(
|
2021-11-23 20:30:02 +00:00
|
|
|
self.user.username
|
2021-08-03 15:45:16 +00:00
|
|
|
)
|
|
|
|
identification_stage.find_element(By.CSS_SELECTOR, "input[name=uidField]").send_keys(
|
|
|
|
Keys.ENTER
|
|
|
|
)
|
2021-02-26 15:46:01 +00:00
|
|
|
|
|
|
|
flow_executor = self.get_shadow_root("ak-flow-executor")
|
|
|
|
password_stage = self.get_shadow_root("ak-stage-password", flow_executor)
|
|
|
|
password_stage.find_element(By.CSS_SELECTOR, "input[name=password]").send_keys(
|
2021-11-23 20:30:02 +00:00
|
|
|
self.user.username
|
2021-02-26 15:46:01 +00:00
|
|
|
)
|
2021-08-03 15:45:16 +00:00
|
|
|
password_stage.find_element(By.CSS_SELECTOR, "input[name=password]").send_keys(Keys.ENTER)
|
2021-02-27 22:33:15 +00:00
|
|
|
sleep(1)
|
2021-02-26 15:46:01 +00:00
|
|
|
|
2020-11-23 13:24:42 +00:00
|
|
|
def assert_user(self, expected_user: User):
|
|
|
|
"""Check users/me API and assert it matches expected_user"""
|
2020-12-05 21:08:42 +00:00
|
|
|
self.driver.get(self.url("authentik_api:user-me") + "?format=json")
|
2020-11-23 13:24:42 +00:00
|
|
|
user_json = self.driver.find_element(By.CSS_SELECTOR, "pre").text
|
2021-03-22 12:44:17 +00:00
|
|
|
user = UserSerializer(data=json.loads(user_json)["user"])
|
2020-11-23 13:24:42 +00:00
|
|
|
user.is_valid()
|
|
|
|
self.assertEqual(user["username"].value, expected_user.username)
|
|
|
|
self.assertEqual(user["name"].value, expected_user.name)
|
|
|
|
self.assertEqual(user["email"].value, expected_user.email)
|
|
|
|
|
2021-02-27 21:32:48 +00:00
|
|
|
|
|
|
|
@lru_cache
|
|
|
|
def get_loader():
|
|
|
|
"""Thin wrapper to lazily get a Migration Loader, only when it's needed
|
|
|
|
and only once"""
|
|
|
|
return MigrationLoader(connection)
|
2020-10-20 16:42:26 +00:00
|
|
|
|
|
|
|
|
2021-02-26 15:46:01 +00:00
|
|
|
def apply_migration(app_name: str, migration_name: str):
|
|
|
|
"""Re-apply migrations that create objects using RunPython before test cases"""
|
|
|
|
|
|
|
|
def wrapper_outter(func: Callable):
|
|
|
|
"""Retry test multiple times"""
|
|
|
|
|
|
|
|
@wraps(func)
|
|
|
|
def wrapper(self: TransactionTestCase, *args, **kwargs):
|
2021-02-27 21:32:48 +00:00
|
|
|
migration = get_loader().get_migration(app_name, migration_name)
|
2021-02-26 15:46:01 +00:00
|
|
|
with connection.schema_editor() as schema_editor:
|
|
|
|
for operation in migration.operations:
|
|
|
|
if not isinstance(operation, RunPython):
|
|
|
|
continue
|
|
|
|
operation.code(apps, schema_editor)
|
|
|
|
return func(self, *args, **kwargs)
|
|
|
|
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
return wrapper_outter
|
|
|
|
|
|
|
|
|
2021-02-27 22:33:15 +00:00
|
|
|
def object_manager(func: Callable):
|
|
|
|
"""Run objectmanager before a test function"""
|
|
|
|
|
|
|
|
@wraps(func)
|
|
|
|
def wrapper(*args, **kwargs):
|
|
|
|
"""Run objectmanager before a test function"""
|
|
|
|
ObjectManager().run()
|
|
|
|
return func(*args, **kwargs)
|
|
|
|
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
|
2021-03-24 13:43:46 +00:00
|
|
|
def retry(max_retires=RETRIES, exceptions=None):
|
2020-10-20 16:42:26 +00:00
|
|
|
"""Retry test multiple times. Default to catching Selenium Timeout Exception"""
|
|
|
|
|
|
|
|
if not exceptions:
|
2020-12-06 15:17:51 +00:00
|
|
|
exceptions = [WebDriverException, TimeoutException, NoSuchElementException]
|
2020-10-20 16:42:26 +00:00
|
|
|
|
2020-10-22 12:05:29 +00:00
|
|
|
logger = get_logger()
|
|
|
|
|
2020-10-20 16:42:26 +00:00
|
|
|
def retry_actual(func: Callable):
|
|
|
|
"""Retry test multiple times"""
|
|
|
|
count = 1
|
|
|
|
|
|
|
|
@wraps(func)
|
2020-10-22 12:05:29 +00:00
|
|
|
def wrapper(self: TransactionTestCase, *args, **kwargs):
|
2020-10-20 16:42:26 +00:00
|
|
|
"""Run test again if we're below max_retries, including tearDown and
|
|
|
|
setUp. Otherwise raise the error"""
|
|
|
|
nonlocal count
|
|
|
|
try:
|
|
|
|
return func(self, *args, **kwargs)
|
|
|
|
# pylint: disable=catching-non-exception
|
|
|
|
except tuple(exceptions) as exc:
|
|
|
|
count += 1
|
|
|
|
if count > max_retires:
|
2020-10-22 12:05:29 +00:00
|
|
|
logger.debug("Exceeded retry count", exc=exc, test=self)
|
2020-10-20 16:42:26 +00:00
|
|
|
# pylint: disable=raising-non-exception
|
|
|
|
raise exc
|
2020-10-22 12:05:29 +00:00
|
|
|
logger.debug("Retrying on error", exc=exc, test=self)
|
2020-10-20 16:42:26 +00:00
|
|
|
self.tearDown()
|
2020-11-15 19:46:53 +00:00
|
|
|
self._post_teardown() # noqa
|
2020-10-20 16:42:26 +00:00
|
|
|
self.setUp()
|
|
|
|
return wrapper(self, *args, **kwargs)
|
|
|
|
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
return retry_actual
|