diff --git a/Makefile b/Makefile index 3d9ceeca..2a224b0c 100644 --- a/Makefile +++ b/Makefile @@ -23,11 +23,14 @@ ifdef html PYTEST += --html=$(resultsdir)/report-$(@F).html endif -commit-acceptance: pylint mypy all-is-package +commit-acceptance: black pylint mypy all-is-package pylint mypy: pipenv-dev pipenv run $@ $(flags) testsuite +black: pipenv-dev + pipenv run black --line-length 120 --check testsuite --diff + all-is-package: @echo @echo "Searching for dirs missing __init__.py" diff --git a/Pipfile b/Pipfile index e5f531bf..6eee28e0 100644 --- a/Pipfile +++ b/Pipfile @@ -2,6 +2,7 @@ mypy = "*" pylint = "*" types-PyYAML = "*" +black = {version = "*", extras = ["d"]} # Have commented out python-language-server to make it available quickly # for the development #python-language-server = "*" diff --git a/testsuite/certificates/__init__.py b/testsuite/certificates/__init__.py index c7f4ce2b..bcdbcaf1 100644 --- a/testsuite/certificates/__init__.py +++ b/testsuite/certificates/__init__.py @@ -15,6 +15,7 @@ class CFSSLException(Exception): @dataclasses.dataclass class CertInfo: """Certificate configuration details""" + hosts: Optional[Union[Collection[str], str]] = None ca: bool = False children: Optional[Dict[str, Optional["CertInfo"]]] = None @@ -24,6 +25,7 @@ class CertInfo: @dataclasses.dataclass class Certificate: """Object representing Signed certificate""" + key: str certificate: str chain: str @@ -32,13 +34,14 @@ class Certificate: @dataclasses.dataclass class UnsignedKey: """Object representing generated key waiting to be signed""" + key: str csr: str -def build_cert_request_json(common_name: str, - names: Optional[List[Dict[str, str]]] = None, - hosts: Optional[Collection[str]] = None) -> dict: +def build_cert_request_json( + common_name: str, names: Optional[List[Dict[str, str]]] = None, hosts: Optional[Collection[str]] = None +) -> dict: """ Build certificate request for the CFSSL client :param common_name: certificate identifier @@ -50,15 +53,13 @@ def build_cert_request_json(common_name: str, "CN": common_name, "names": names, "hosts": hosts, - "key": { - "algo": "rsa", - "size": 4096 - }, + "key": {"algo": "rsa", "size": 4096}, } class CFSSLClient: """Client for working with CFSSL library""" + DEFAULT_NAMES = [ { "O": "Red Hat Inc.", @@ -73,20 +74,20 @@ def __init__(self, binary) -> None: super().__init__() self.binary = binary - def _execute_command(self, - command: str, - *args: str, - stdin: Optional[str] = None, - env: Optional[Dict[str, str]] = None): + def _execute_command( + self, command: str, *args: str, stdin: Optional[str] = None, env: Optional[Dict[str, str]] = None + ): args = (self.binary, command, *args) try: - response = subprocess.run(args, - stderr=subprocess.PIPE, - stdout=subprocess.PIPE, - input=stdin, - universal_newlines=bool(stdin), - check=False, - env=env) + response = subprocess.run( + args, + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, + input=stdin, + universal_newlines=bool(stdin), + check=False, + env=env, + ) if response.returncode != 0: raise CFSSLException(f"CFSSL command {args} returned non-zero response code, error {response.stderr}") return json.loads(response.stdout) @@ -101,8 +102,9 @@ def exists(self): """Returns true if the binary exists and is correctly set up""" return shutil.which(self.binary) - def generate_key(self, common_name: str, names: Optional[List[Dict[str, str]]] = None, - hosts: Optional[Collection[str]] = None) -> UnsignedKey: + def generate_key( + self, common_name: str, names: Optional[List[Dict[str, str]]] = None, hosts: Optional[Collection[str]] = None + ) -> UnsignedKey: """Generates unsigned key""" data = build_cert_request_json(common_name, names, hosts) @@ -114,35 +116,46 @@ def sign_intermediate_authority(self, key: UnsignedKey, certificate_authority: C args = [ "-ca=env:CA", "-ca-key=env:KEY", - f"-config={resources.files('testsuite.resources.tls').joinpath('intermediate_config.json')}" + f"-config={resources.files('testsuite.resources.tls').joinpath('intermediate_config.json')}", ] - result = self._execute_command("sign", *args, "-", stdin=key.csr, env={ - "CA": certificate_authority.certificate, - "KEY": certificate_authority.key}) + result = self._execute_command( + "sign", + *args, + "-", + stdin=key.csr, + env={"CA": certificate_authority.certificate, "KEY": certificate_authority.key}, + ) return Certificate(key=key.key, certificate=result["cert"], chain=result["cert"]) def sign(self, key: UnsignedKey, certificate_authority: Certificate) -> Certificate: """Signs unsigned key""" - result = self._execute_command("sign", "-ca=env:CA", "-ca-key=env:KEY", "-", stdin=key.csr, env={ - "CA": certificate_authority.certificate, - "KEY": certificate_authority.key}) + result = self._execute_command( + "sign", + "-ca=env:CA", + "-ca-key=env:KEY", + "-", + stdin=key.csr, + env={"CA": certificate_authority.certificate, "KEY": certificate_authority.key}, + ) chain = result["cert"] + certificate_authority.chain return Certificate(key=key.key, certificate=result["cert"], chain=chain) - def self_sign(self, common_name: str, - names: Optional[List[Dict[str, str]]] = None, - hosts: Optional[Collection[str]] = None) -> Certificate: + def self_sign( + self, common_name: str, names: Optional[List[Dict[str, str]]] = None, hosts: Optional[Collection[str]] = None + ) -> Certificate: """Creates self-signed certificate""" data = build_cert_request_json(common_name, names, hosts) result = self._execute_command("selfsign", common_name, "-", stdin=json.dumps(data)) return Certificate(key=result["key"], certificate=result["cert"], chain=result["cert"]) - def create_authority(self, - common_name: str, - hosts: Collection[str], - names: Optional[List[Dict[str, str]]] = None, - certificate_authority: Optional[Certificate] = None) -> Certificate: + def create_authority( + self, + common_name: str, + hosts: Collection[str], + names: Optional[List[Dict[str, str]]] = None, + certificate_authority: Optional[Certificate] = None, + ) -> Certificate: """Generates self-signed root or intermediate CA certificate and private key Args: :param common_name: identifier to the certificate and key. @@ -160,11 +173,13 @@ def create_authority(self, certificate = self.sign_intermediate_authority(key, certificate_authority) return certificate - def create(self, - common_name: str, - hosts: Collection[str], - certificate_authority: Optional[Certificate] = None, - names: Optional[List[Dict[str, str]]] = None) -> Certificate: + def create( + self, + common_name: str, + hosts: Collection[str], + certificate_authority: Optional[Certificate] = None, + names: Optional[List[Dict[str, str]]] = None, + ) -> Certificate: """Create a new certificate. Args: :param common_name: Exact DNS match for which this certificate is valid diff --git a/testsuite/config/__init__.py b/testsuite/config/__init__.py index cc11de9b..c4269947 100644 --- a/testsuite/config/__init__.py +++ b/testsuite/config/__init__.py @@ -10,14 +10,19 @@ class DefaultValueValidator(Validator): """Validator which will run default function only when the original value is missing""" def __init__(self, name, default, **kwargs) -> None: - super().__init__(name, ne=None, - messages={ - "operations": ("{name} must {operation} {op_value} but it is {value} in env {env}. " - "You might be missing tools on the cluster.") - }, - default=default, - when=Validator(name, must_exist=False), - **kwargs) + super().__init__( + name, + ne=None, + messages={ + "operations": ( + "{name} must {operation} {op_value} but it is {value} in env {env}. " + "You might be missing tools on the cluster." + ) + }, + default=default, + when=Validator(name, must_exist=False), + **kwargs + ) settings = Dynaconf( @@ -35,5 +40,5 @@ def __init__(self, name, default, **kwargs) -> None: Validator("kuadrant.enable", must_exist=False, eq=False) | Validator("kuadrant.gateway.name", must_exist=True), ], validate_only=["authorino", "kuadrant"], - loaders=["dynaconf.loaders.env_loader", "testsuite.config.openshift_loader"] + loaders=["dynaconf.loaders.env_loader", "testsuite.config.openshift_loader"], ) diff --git a/testsuite/config/openshift_loader.py b/testsuite/config/openshift_loader.py index 1215f4c4..990733da 100644 --- a/testsuite/config/openshift_loader.py +++ b/testsuite/config/openshift_loader.py @@ -10,10 +10,7 @@ def load(obj, env=None, silent=True, key=None, filename=None): config = weakget(obj) section = config["openshift"] client = OpenShiftClient( - section["project"] % None, - section["api_url"] % None, - section["token"] % None, - section["kubeconfig_path"] % None + section["project"] % None, section["api_url"] % None, section["token"] % None, section["kubeconfig_path"] % None ) obj["openshift"] = client diff --git a/testsuite/config/tools.py b/testsuite/config/tools.py index d77f5ca8..d970348c 100644 --- a/testsuite/config/tools.py +++ b/testsuite/config/tools.py @@ -6,6 +6,7 @@ def fetch_route(name, force_http=False): """Fetches the URL of a route with specific name""" + def _fetcher(settings, _): try: openshift = settings["tools"] @@ -17,11 +18,13 @@ def _fetcher(settings, _): except Exception: logger.warning("Unable to fetch route %s from tools", name) return None + return _fetcher def fetch_secret(name, key): """Fetches the key out of a secret with specific name""" + def _fetcher(settings, _): try: openshift = settings["tools"] @@ -30,4 +33,5 @@ def _fetcher(settings, _): except Exception: logger.warning("Unable to fetch secret %s[%s] from tools", name, key) return None + return _fetcher diff --git a/testsuite/httpx/__init__.py b/testsuite/httpx/__init__.py index 775e875c..025223c8 100644 --- a/testsuite/httpx/__init__.py +++ b/testsuite/httpx/__init__.py @@ -20,6 +20,7 @@ def create_tmp_file(content: str): class UnexpectedResponse(Exception): """Slightly different response attributes were expected""" + def __init__(self, msg, response): super().__init__(msg) self.response = response @@ -58,12 +59,38 @@ def add_retry_code(self, code): self.retry_codes.add(code) @backoff.on_exception(backoff.fibo, UnexpectedResponse, max_tries=8, jitter=None) - def request(self, method: str, url, *, content=None, data=None, files=None, - json=None, params=None, headers=None, cookies=None, auth=None, follow_redirects=None, - timeout=None, extensions=None) -> Response: - response = super().request(method, url, content=content, data=data, files=files, json=json, params=params, - headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, - timeout=timeout, extensions=extensions) + def request( + self, + method: str, + url, + *, + content=None, + data=None, + files=None, + json=None, + params=None, + headers=None, + cookies=None, + auth=None, + follow_redirects=None, + timeout=None, + extensions=None, + ) -> Response: + response = super().request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) if response.status_code in self.retry_codes: raise UnexpectedResponse(f"Didn't expect '{response.status_code}' status code", response) return response diff --git a/testsuite/httpx/auth.py b/testsuite/httpx/auth.py index 6c82e102..4ee87e85 100644 --- a/testsuite/httpx/auth.py +++ b/testsuite/httpx/auth.py @@ -14,8 +14,7 @@ class HttpxOidcClientAuth(Auth): """Auth class for Httpx client for product secured by oidc""" - def __init__(self, token: TokenType, location="authorization", - username: str = None, password: str = None) -> None: + def __init__(self, token: TokenType, location="authorization", username: str = None, password: str = None) -> None: self.location = location self._token = token self.username = username @@ -34,12 +33,12 @@ def token(self): return self._token def _add_credentials(self, request: Request, token): - if self.location == 'authorization': - request.headers['Authorization'] = f"Bearer {token}" - elif self.location == 'headers': - request.headers['access_token'] = token - elif self.location == 'query': - request.url = URL(request.url, params={'access_token': token}) + if self.location == "authorization": + request.headers["Authorization"] = f"Bearer {token}" + elif self.location == "headers": + request.headers["access_token"] = token + elif self.location == "query": + request.url = URL(request.url, params={"access_token": token}) else: raise ValueError(f"Unknown credentials location '{self.location}'") diff --git a/testsuite/mockserver.py b/testsuite/mockserver.py index 9fcb607e..8cbd8ff6 100644 --- a/testsuite/mockserver.py +++ b/testsuite/mockserver.py @@ -22,35 +22,22 @@ def _expectation(self, expectation_id, response_data): Creates an Expectation with given response_data. Expectation is accessible on the `mockserver.url/expectation_id` url. """ - json_data = { - "id": expectation_id, - "httpRequest": { - "path": f"/{expectation_id}" - } - } + json_data = {"id": expectation_id, "httpRequest": {"path": f"/{expectation_id}"}} json_data.update(response_data) - response = httpx.put( - urljoin(self.url, "/mockserver/expectation"), verify=False, timeout=5, json=json_data) + response = httpx.put(urljoin(self.url, "/mockserver/expectation"), verify=False, timeout=5, json=json_data) response.raise_for_status() self.expectations[expectation_id] = f"{self.url}/{expectation_id}" return self.expectations[expectation_id] def create_expectation( - self, - expectation_id, - body, - content_type: Union[ContentType, str] = ContentType.PLAIN_TEXT, + self, + expectation_id, + body, + content_type: Union[ContentType, str] = ContentType.PLAIN_TEXT, ): """Creates an Expectation - response with given body""" - json_data = { - "httpResponse": { - "headers": { - "Content-Type": [str(content_type)] - }, - "body": body - } - } + json_data = {"httpResponse": {"headers": {"Content-Type": [str(content_type)]}, "body": body}} return self._expectation(expectation_id, json_data) def create_template_expectation(self, expectation_id, template): @@ -58,30 +45,25 @@ def create_template_expectation(self, expectation_id, template): Creates template expectation in Mustache format. https://www.mock-server.com/mock_server/response_templates.html """ - json_data = { - "httpResponseTemplate": { - "templateType": "MUSTACHE", - "template": template - } - } + json_data = {"httpResponseTemplate": {"templateType": "MUSTACHE", "template": template}} return self._expectation(expectation_id, json_data) def clear_expectation(self, expectation_id): """Clears Expectation with specific ID""" httpx.put( - urljoin(self.url, "/mockserver/clear"), verify=False, timeout=5, json={ - "id": expectation_id - } - ).raise_for_status() + urljoin(self.url, "/mockserver/clear"), verify=False, timeout=5, json={"id": expectation_id} + ).raise_for_status() del self.expectations[expectation_id] def verify_expectation(self, path): """Verify a request has been received a specific number of times for specific expectation""" return httpx.put( - urljoin(self.url, "/mockserver/retrieve"), params="type=REQUESTS&format=JSON", - verify=False, timeout=5, json={ - "path": path - }) + urljoin(self.url, "/mockserver/retrieve"), + params="type=REQUESTS&format=JSON", + verify=False, + timeout=5, + json={"path": path}, + ) def get_expectation_endpoint(self, expectation_id): """Returns endpoint for expectation""" diff --git a/testsuite/objects/__init__.py b/testsuite/objects/__init__.py index d5dd8d9c..ea3b9e69 100644 --- a/testsuite/objects/__init__.py +++ b/testsuite/objects/__init__.py @@ -54,6 +54,7 @@ def to_dict(self): @dataclass class Cache: """Dataclass for specifying Cache in Authorization""" + ttl: int key: Value @@ -65,6 +66,7 @@ def to_dict(self): @dataclass class PatternRef: """Dataclass for specifying Pattern reference in Authorization""" + # pylint: disable=invalid-name patternRef: str diff --git a/testsuite/objects/sections.py b/testsuite/objects/sections.py index dcca3d68..e3597db4 100644 --- a/testsuite/objects/sections.py +++ b/testsuite/objects/sections.py @@ -72,7 +72,7 @@ def user_info_metadata(self, name, identity_source, **common_features): @abc.abstractmethod def uma_metadata(self, name, endpoint, credentials, **common_features): - """Set metadata User-Managed Access (UMA) resource registry """ + """Set metadata User-Managed Access (UMA) resource registry""" class Responses(abc.ABC): diff --git a/testsuite/oidc/__init__.py b/testsuite/oidc/__init__.py index 86169710..d5a4b751 100644 --- a/testsuite/oidc/__init__.py +++ b/testsuite/oidc/__init__.py @@ -7,6 +7,7 @@ @dataclass class Token: """Token class""" + access_token: str refresh_function: Callable[[str], "Token"] refresh_token: str diff --git a/testsuite/oidc/auth0.py b/testsuite/oidc/auth0.py index 1bb51c74..7cfeab81 100644 --- a/testsuite/oidc/auth0.py +++ b/testsuite/oidc/auth0.py @@ -31,12 +31,15 @@ def refresh_token(self, refresh_token): return self.get_token() def get_token(self, username=None, password=None) -> Token: - response = httpx.post(self.token_endpoint, json={ - "client_id": self.client_id, - "client_secret": self.client_secret, - "grant_type": "client_credentials", - "audience": self.domain + "/api/v2/" - }) + response = httpx.post( + self.token_endpoint, + json={ + "client_id": self.client_id, + "client_secret": self.client_secret, + "grant_type": "client_credentials", + "audience": self.domain + "/api/v2/", + }, + ) data = response.json() assert response.status_code == 200, f"Unable to acquire token from Auth0, reason: {data}" return Token(data["access_token"], self.refresh_token, "None") diff --git a/testsuite/oidc/rhsso/__init__.py b/testsuite/oidc/rhsso/__init__.py index c1c710f0..c460a931 100644 --- a/testsuite/oidc/rhsso/__init__.py +++ b/testsuite/oidc/rhsso/__init__.py @@ -15,8 +15,16 @@ class RHSSO(OIDCProvider, LifecycleObject): OIDCProvider implementation for RHSSO. It creates Realm, client and user. """ - def __init__(self, server_url, username, password, realm_name, client_name, - test_username="testUser", test_password="testPassword") -> None: + def __init__( + self, + server_url, + username, + password, + realm_name, + client_name, + test_username="testUser", + test_password="testPassword", + ) -> None: self.test_username = test_username self.test_password = test_password self.username = username @@ -28,32 +36,31 @@ def __init__(self, server_url, username, password, realm_name, client_name, self.client = None try: - self.master = KeycloakAdmin(server_url=server_url, - username=username, - password=password, - realm_name="master", - verify=False, - auto_refresh_token=['get', 'put', 'post', 'delete']) + self.master = KeycloakAdmin( + server_url=server_url, + username=username, + password=password, + realm_name="master", + verify=False, + auto_refresh_token=["get", "put", "post", "delete"], + ) self.server_url = server_url except KeycloakPostError: # Older Keycloaks versions (and RHSSO) needs requires url to be pointed at auth/ endpoint # pylint: disable=protected-access self.server_url = urlparse(server_url)._replace(path="auth/").geturl() - self.master = KeycloakAdmin(server_url=self.server_url, - username=username, - password=password, - realm_name="master", - verify=False, - auto_refresh_token=['get', 'put', 'post', 'delete']) + self.master = KeycloakAdmin( + server_url=self.server_url, + username=username, + password=password, + realm_name="master", + verify=False, + auto_refresh_token=["get", "put", "post", "delete"], + ) def create_realm(self, name: str, **kwargs) -> Realm: """Creates new realm""" - self.master.create_realm(payload={ - "realm": name, - "enabled": True, - "sslRequired": "None", - **kwargs - }) + self.master.create_realm(payload={"realm": name, "enabled": True, "sslRequired": "None", **kwargs}) return Realm(self.master, name) def commit(self): @@ -66,7 +73,8 @@ def commit(self): protocol="openid-connect", standardFlowEnabled=False, serviceAccountsEnabled=True, - authorizationServicesEnabled=True) + authorizationServicesEnabled=True, + ) self.user = self.realm.create_user(self.test_username, self.test_password) def delete(self): @@ -94,6 +102,8 @@ def token_params(self) -> str: """ Returns token parameters that can be added to request url """ - return f"grant_type=password&client_id={self.oidc_client.client_id}&" \ - f"client_secret={self.oidc_client.client_secret_key}&username={self.test_username}&" \ - f"password={self.test_password}" + return ( + f"grant_type=password&client_id={self.oidc_client.client_id}&" + f"client_secret={self.oidc_client.client_secret_key}&username={self.test_username}&" + f"password={self.test_password}" + ) diff --git a/testsuite/oidc/rhsso/objects.py b/testsuite/oidc/rhsso/objects.py index c6145ab6..97349253 100644 --- a/testsuite/oidc/rhsso/objects.py +++ b/testsuite/oidc/rhsso/objects.py @@ -7,14 +7,17 @@ class Realm: """Helper class for RHSSO realm manipulation""" + def __init__(self, master: KeycloakAdmin, name) -> None: - self.admin = KeycloakAdmin(server_url=master.server_url, - username=master.username, - password=master.password, - realm_name=name, - user_realm_name="master", - verify=False, - auto_refresh_token=['get', 'put', 'post', 'delete']) + self.admin = KeycloakAdmin( + server_url=master.server_url, + username=master.username, + password=master.password, + realm_name=name, + user_realm_name="master", + verify=False, + auto_refresh_token=["get", "put", "post", "delete"], + ) self.name = name def delete(self): @@ -23,10 +26,7 @@ def delete(self): def create_client(self, name, **kwargs): """Creates new client""" - self.admin.create_client(payload={ - **kwargs, - "clientId": name} - ) + self.admin.create_client(payload={**kwargs, "clientId": name}) client_id = self.admin.get_client_id(name) return Client(self, client_id) @@ -52,14 +52,14 @@ def create_realm_role(self, role_name: str): def oidc_client(self, client_id, client_secret): """Create OIDC client for this realm""" - return KeycloakOpenID(server_url=self.admin.server_url, - client_id=client_id, - realm_name=self.name, - client_secret_key=client_secret) + return KeycloakOpenID( + server_url=self.admin.server_url, client_id=client_id, realm_name=self.name, client_secret_key=client_secret + ) class Client: """Helper class for RHSSO client manipulation""" + def __init__(self, realm: Realm, client_id) -> None: self.admin = realm.admin self.realm = realm @@ -119,8 +119,7 @@ def assign_realm_role(self, role): :param role: Dictionary with two keys "name" and "id" of role to assign :returns: Keycloak server response """ - return self.admin.assign_realm_roles(user_id=self.user_id, - roles=role) + return self.admin.assign_realm_roles(user_id=self.user_id, roles=role) def assign_attribute(self, attribute): """Assigns attribute to user""" diff --git a/testsuite/openshift/client.py b/testsuite/openshift/client.py index 6a146945..db0176f1 100644 --- a/testsuite/openshift/client.py +++ b/testsuite/openshift/client.py @@ -88,8 +88,7 @@ def secrets(self): """Return dict-like interface for Secrets""" return Secrets(self) - def do_action(self, verb: str, *args, - auto_raise: bool = True, parse_output: bool = False): + def do_action(self, verb: str, *args, auto_raise: bool = True, parse_output: bool = False): """Run an oc command.""" with self.context: result = oc.invoke(verb, args, auto_raise=auto_raise) @@ -136,16 +135,13 @@ def is_ready(self, selector: Selector): def create_tls_secret(self, name: str, certificate: Certificate, labels: Optional[Dict[str, str]] = None): """Creates a TLS secret""" model: Dict = { - 'kind': 'Secret', - 'apiVersion': 'v1', - 'metadata': { - 'name': name, + "kind": "Secret", + "apiVersion": "v1", + "metadata": { + "name": name, }, - 'stringData': { - "tls.crt": certificate.chain, - "tls.key": certificate.key - }, - "type": "kubernetes.io/tls" + "stringData": {"tls.crt": certificate.chain, "tls.key": certificate.key}, + "type": "kubernetes.io/tls", } if labels is not None: model["metadata"]["labels"] = labels diff --git a/testsuite/openshift/envoy.py b/testsuite/openshift/envoy.py index 8dd8be5e..0724e059 100644 --- a/testsuite/openshift/envoy.py +++ b/testsuite/openshift/envoy.py @@ -13,6 +13,7 @@ class Envoy(Proxy): """Envoy deployed from template""" + def __init__(self, openshift: OpenShiftClient, authorino, name, label, httpbin: Httpbin, image) -> None: self.openshift = openshift self.authorino = authorino @@ -27,10 +28,11 @@ def __init__(self, openshift: OpenShiftClient, authorino, name, label, httpbin: def route(self) -> Route: """Returns route for object""" with self.openshift.context: - return self.envoy_objects\ - .narrow("route")\ - .narrow(lambda route: route.model.metadata.name == self.name)\ + return ( + self.envoy_objects.narrow("route") + .narrow(lambda route: route.model.metadata.name == self.name) .object(cls=OpenshiftRoute) + ) def add_hostname(self, name) -> str: """Add another hostname that points to this Envoy""" @@ -51,13 +53,16 @@ def client(self, **kwargs): def commit(self): """Deploy all required objects into OpenShift""" with resources.path("testsuite.resources", "envoy.yaml") as path: - self.envoy_objects = self.openshift.new_app(path, { - "NAME": self.name, - "LABEL": self.label, - "AUTHORINO_URL": self.authorino.authorization_url, - "UPSTREAM_URL": self.httpbin_hostname, - "ENVOY_IMAGE": self.image - }) + self.envoy_objects = self.openshift.new_app( + path, + { + "NAME": self.name, + "LABEL": self.label, + "AUTHORINO_URL": self.authorino.authorization_url, + "UPSTREAM_URL": self.httpbin_hostname, + "ENVOY_IMAGE": self.image, + }, + ) with self.openshift.context: assert self.openshift.is_ready(self.envoy_objects.narrow("deployment")), "Envoy wasn't ready in time" @@ -71,8 +76,19 @@ def delete(self): class TLSEnvoy(Envoy): """Envoy with TLS enabled and all required certificates set up, requires using a client certificate""" - def __init__(self, openshift, authorino, name, label, httpbin_hostname, image, - authorino_ca_secret, envoy_ca_secret, envoy_cert_secret) -> None: + + def __init__( + self, + openshift, + authorino, + name, + label, + httpbin_hostname, + image, + authorino_ca_secret, + envoy_ca_secret, + envoy_cert_secret, + ) -> None: super().__init__(openshift, authorino, name, label, httpbin_hostname, image) self.authorino_ca_secret = authorino_ca_secret self.backend_ca_secret = envoy_ca_secret @@ -84,16 +100,19 @@ def client(self, **kwargs): def commit(self): with resources.path("testsuite.resources.tls", "envoy.yaml") as path: - self.envoy_objects = self.openshift.new_app(path, { - "NAME": self.name, - "LABEL": self.label, - "AUTHORINO_URL": self.authorino.authorization_url, - "UPSTREAM_URL": self.httpbin_hostname, - "AUTHORINO_CA_SECRET": self.authorino_ca_secret, - "ENVOY_CA_SECRET": self.backend_ca_secret, - "ENVOY_CERT_SECRET": self.envoy_cert_secret, - "ENVOY_IMAGE": self.image - }) + self.envoy_objects = self.openshift.new_app( + path, + { + "NAME": self.name, + "LABEL": self.label, + "AUTHORINO_URL": self.authorino.authorization_url, + "UPSTREAM_URL": self.httpbin_hostname, + "AUTHORINO_CA_SECRET": self.authorino_ca_secret, + "ENVOY_CA_SECRET": self.backend_ca_secret, + "ENVOY_CERT_SECRET": self.envoy_cert_secret, + "ENVOY_IMAGE": self.image, + }, + ) with self.openshift.context: assert self.openshift.is_ready(self.envoy_objects.narrow("deployment")), "Envoy wasn't ready in time" diff --git a/testsuite/openshift/httpbin.py b/testsuite/openshift/httpbin.py index 4b179cbe..fc63b932 100644 --- a/testsuite/openshift/httpbin.py +++ b/testsuite/openshift/httpbin.py @@ -9,6 +9,7 @@ class Httpbin(LifecycleObject, Referencable): """Httpbin deployed in OpenShift through template""" + def __init__(self, openshift: OpenShiftClient, name, label) -> None: super().__init__() self.openshift = openshift @@ -19,13 +20,7 @@ def __init__(self, openshift: OpenShiftClient, name, label) -> None: @property def reference(self): - return { - "group": "", - "kind": "Service", - "port": 8080, - "name": self.name, - "namespace": self.openshift.project - } + return {"group": "", "kind": "Service", "port": 8080, "name": self.name, "namespace": self.openshift.project} @property def url(self): diff --git a/testsuite/openshift/objects/__init__.py b/testsuite/openshift/objects/__init__.py index f741a748..e2165a42 100644 --- a/testsuite/openshift/objects/__init__.py +++ b/testsuite/openshift/objects/__init__.py @@ -6,8 +6,9 @@ def modify(func): """Wraps method of a subclass of OpenShiftObject to use modify_and_apply when the object - is already committed to the server, or run it normally if it isn't. - All methods modifying the target object in any way should be decorated by this""" + is already committed to the server, or run it normally if it isn't. + All methods modifying the target object in any way should be decorated by this""" + def _custom_partial(func, *args, **kwargs): """Custom partial function which makes sure that self is always assigned correctly""" @@ -29,6 +30,7 @@ def _wrap(self, *args, **kwargs): class OpenShiftObject(APIObject): """Custom APIObjects which tracks if the object was already committed to the server or not""" + def __init__(self, dict_to_model=None, string_to_model=None, context=None): super().__init__(dict_to_model, string_to_model, context) self.committed = False diff --git a/testsuite/openshift/objects/api_key.py b/testsuite/openshift/objects/api_key.py index 7655d14c..45e7dd56 100644 --- a/testsuite/openshift/objects/api_key.py +++ b/testsuite/openshift/objects/api_key.py @@ -20,15 +20,10 @@ def create_instance(cls, openshift: OpenShiftClient, name, label, api_key): "metadata": { "name": name, "namespace": openshift.project, - "labels": { - "authorino.kuadrant.io/managed-by": "authorino", - "group": label - } + "labels": {"authorino.kuadrant.io/managed-by": "authorino", "group": label}, }, - "stringData": { - "api_key": api_key - }, - "type": "Opaque" + "stringData": {"api_key": api_key}, + "type": "Opaque", } return cls(model, context=openshift.context) @@ -36,4 +31,4 @@ def create_instance(cls, openshift: OpenShiftClient, name, label, api_key): @modify def update_api_key(self, api_key): """Updates API key Secret with new API key""" - self.model.data["api_key"] = base64.b64encode(api_key.encode("utf-8")).decode('ascii') + self.model.data["api_key"] = base64.b64encode(api_key.encode("utf-8")).decode("ascii") diff --git a/testsuite/openshift/objects/auth_config/__init__.py b/testsuite/openshift/objects/auth_config/__init__.py index ab7aee05..245e872e 100644 --- a/testsuite/openshift/objects/auth_config/__init__.py +++ b/testsuite/openshift/objects/auth_config/__init__.py @@ -5,8 +5,7 @@ from testsuite.objects import Authorization, Responses, Metadata, Identities, Authorizations from testsuite.openshift.client import OpenShiftClient from testsuite.openshift.objects import OpenShiftObject, modify -from .sections import AuthorizationsSection, IdentitySection, MetadataSection, \ - ResponsesSection +from .sections import AuthorizationsSection, IdentitySection, MetadataSection, ResponsesSection from ..route import Route @@ -39,19 +38,15 @@ def responses(self) -> Responses: return ResponsesSection(self, "response") @classmethod - def create_instance(cls, openshift: OpenShiftClient, name, route: Route, - labels: Dict[str, str] = None, hostnames: List[str] = None): + def create_instance( + cls, openshift: OpenShiftClient, name, route: Route, labels: Dict[str, str] = None, hostnames: List[str] = None + ): """Creates base instance""" model: Dict = { "apiVersion": "authorino.kuadrant.io/v1beta1", "kind": "AuthConfig", - "metadata": { - "name": name, - "namespace": openshift.project - }, - "spec": { - "hosts": hostnames or route.hostnames - } + "metadata": {"name": name, "namespace": openshift.project}, + "spec": {"hosts": hostnames or route.hostnames}, } if labels is not None: @@ -78,4 +73,5 @@ def remove_all_hosts(self): def set_deny_with(self, code, value): """Set denyWith""" self.auth_section["denyWith"] = { - "unauthenticated": {"code": code, "headers": [{"name": "Location", "valueFrom": {"authJSON": value}}]}} + "unauthenticated": {"code": code, "headers": [{"name": "Location", "valueFrom": {"authJSON": value}}]} + } diff --git a/testsuite/openshift/objects/auth_config/sections.py b/testsuite/openshift/objects/auth_config/sections.py index e7a8ae3d..2d7c7e30 100644 --- a/testsuite/openshift/objects/auth_config/sections.py +++ b/testsuite/openshift/objects/auth_config/sections.py @@ -11,6 +11,7 @@ class Section: """Common class for all Sections""" + def __init__(self, obj: "AuthConfig", section_name) -> None: super().__init__() self.obj = obj @@ -18,8 +19,10 @@ def __init__(self, obj: "AuthConfig", section_name) -> None: def modify_and_apply(self, modifier_func, retries=2, cmd_args=None): """Reimplementation of modify_and_apply from OpenshiftObject""" + def _new_modifier(obj): modifier_func(self.__class__(obj, self.section_name)) + return self.obj.modify_and_apply(_new_modifier, retries, cmd_args) @property @@ -32,8 +35,9 @@ def section(self): """The actual dict section which will be edited""" return self.obj.auth_section.setdefault(self.section_name, []) - def add_item(self, name, value, priority: int = None, when: Iterable[Rule] = None, - metrics: bool = None, cache: Cache = None): + def add_item( + self, name, value, priority: int = None, when: Iterable[Rule] = None, metrics: bool = None, cache: Cache = None + ): """Adds item to the section""" item = {"name": name, **value} if when: @@ -58,33 +62,28 @@ def mtls(self, name: str, selector_key: str, selector_value: str, **common_featu :param selector_key: selector key to match :param selector_value: selector value to match """ - self.add_item(name, { - "mtls": { - "selector": { - "matchLabels": { - selector_key: selector_value - } - } - } - }, **common_features) + self.add_item(name, {"mtls": {"selector": {"matchLabels": {selector_key: selector_value}}}}, **common_features) @modify def oidc(self, name, endpoint, credentials="authorization_header", selector="Bearer", **common_features): """Adds OIDC identity""" - self.add_item(name, { - "oidc": { - "endpoint": endpoint - }, - "credentials": { - "in": credentials, - "keySelector": selector - } - }, **common_features) + self.add_item( + name, + {"oidc": {"endpoint": endpoint}, "credentials": {"in": credentials, "keySelector": selector}}, + **common_features + ) @modify - def api_key(self, name, all_namespaces: bool = False, - match_label=None, match_expression: MatchExpression = None, - credentials="authorization_header", selector="APIKEY", **common_features): + def api_key( + self, + name, + all_namespaces: bool = False, + match_label=None, + match_expression: MatchExpression = None, + credentials="authorization_header", + selector="APIKEY", + **common_features + ): """ Adds API Key identity Args: @@ -100,27 +99,19 @@ def api_key(self, name, all_namespaces: bool = False, matcher: Dict = {} if match_label: - matcher.update({ - "matchLabels": { - "group": match_label - } - }) + matcher.update({"matchLabels": {"group": match_label}}) if match_expression: - matcher.update({ - "matchExpressions": [asdict(match_expression)] - }) - - self.add_item(name, { - "apiKey": { - "selector": matcher, - "allNamespaces": all_namespaces + matcher.update({"matchExpressions": [asdict(match_expression)]}) + + self.add_item( + name, + { + "apiKey": {"selector": matcher, "allNamespaces": all_namespaces}, + "credentials": {"in": credentials, "keySelector": selector}, }, - "credentials": { - "in": credentials, - "keySelector": selector - } - }, **common_features) + **common_features + ) @modify def anonymous(self, name, **common_features): @@ -140,37 +131,31 @@ def remove_all(self): class MetadataSection(Section, Metadata): """Section which contains metadata configuration""" + @modify def http_metadata(self, name, endpoint, method: Literal["GET", "POST"], **common_features): """Set metadata http external auth feature""" - self.add_item(name, { - "http": { - "endpoint": endpoint, - "method": method, - "headers": [{"name": "Accept", "value": "application/json"}] - } - }, **common_features) + self.add_item( + name, + { + "http": { + "endpoint": endpoint, + "method": method, + "headers": [{"name": "Accept", "value": "application/json"}], + } + }, + **common_features + ) @modify def user_info_metadata(self, name, identity_source, **common_features): """Set metadata OIDC user info""" - self.add_item(name, { - "userInfo": { - "identitySource": identity_source - } - }, **common_features) + self.add_item(name, {"userInfo": {"identitySource": identity_source}}, **common_features) @modify def uma_metadata(self, name, endpoint, credentials, **common_features): """Set metadata feature for resource-level authorization with User-Managed Access (UMA) resource registry""" - self.add_item(name, { - "uma": { - "endpoint": endpoint, - "credentialsRef": { - "name": credentials - } - } - }, **common_features) + self.add_item(name, {"uma": {"endpoint": endpoint, "credentialsRef": {"name": credentials}}}, **common_features) class ResponsesSection(Section, Responses): @@ -188,11 +173,7 @@ class AuthorizationsSection(Section, Authorizations): @modify def auth_rule(self, name, rule: Rule, **common_features): """Adds JSON pattern-matching authorization rule (authorization.json)""" - section = { - "json": { - "rules": [asdict(rule)] - } - } + section = {"json": {"rules": [asdict(rule)]}} self.add_item(name, section, **common_features) def role_rule(self, name: str, role: str, path: str, **common_features): @@ -212,25 +193,14 @@ def role_rule(self, name: str, role: str, path: str, **common_features): @modify def opa_policy(self, name, rego_policy, **common_features): """Adds Opa (https://www.openpolicyagent.org/docs/latest/) policy to the AuthConfig""" - self.add_item(name, { - "opa": { - "inlineRego": rego_policy - } - }, **common_features) + self.add_item(name, {"opa": {"inlineRego": rego_policy}}, **common_features) @modify def external_opa_policy(self, name, endpoint, ttl=0, **common_features): """ Adds OPA policy that is declared as an HTTP endpoint """ - self.add_item(name, { - "opa": { - "externalRegistry": { - "endpoint": endpoint, - "ttl": ttl - } - } - }, **common_features) + self.add_item(name, {"opa": {"externalRegistry": {"endpoint": endpoint, "ttl": ttl}}}, **common_features) @modify def kubernetes(self, name: str, user: Value, kube_attrs: dict, **common_features): @@ -241,6 +211,10 @@ def kubernetes(self, name: str, user: Value, kube_attrs: dict, **common_features :param kube_attrs: resource attributes in kubernetes authorization """ - self.add_item(name, { - "kubernetes": {"user": user.to_dict(), "resourceAttributes": kube_attrs}, - }, **common_features) + self.add_item( + name, + { + "kubernetes": {"user": user.to_dict(), "resourceAttributes": kube_attrs}, + }, + **common_features + ) diff --git a/testsuite/openshift/objects/authorino.py b/testsuite/openshift/objects/authorino.py index 5570f3d7..69bb89dc 100644 --- a/testsuite/openshift/objects/authorino.py +++ b/testsuite/openshift/objects/authorino.py @@ -13,31 +13,27 @@ class AuthorinoCR(OpenShiftObject, Authorino): """Represents Authorino CR objects from Authorino-operator""" @classmethod - def create_instance(cls, openshift: OpenShiftClient, name, image=None, - cluster_wide=False, label_selectors: List[str] = None, listener_certificate_secret=None, - log_level=None): + def create_instance( + cls, + openshift: OpenShiftClient, + name, + image=None, + cluster_wide=False, + label_selectors: List[str] = None, + listener_certificate_secret=None, + log_level=None, + ): """Creates base instance""" model: Dict[str, Any] = { "apiVersion": "operator.authorino.kuadrant.io/v1beta1", "kind": "Authorino", - "metadata": { - "name": name, - "namespace": openshift.project - }, + "metadata": {"name": name, "namespace": openshift.project}, "spec": { "clusterWide": cluster_wide, "logLevel": log_level, - "listener": { - "tls": { - "enabled": False - } - }, - "oidcServer": { - "tls": { - "enabled": False - } - } - } + "listener": {"tls": {"enabled": False}}, + "oidcServer": {"tls": {"enabled": False}}, + }, } if image: model["spec"]["image"] = image @@ -46,10 +42,7 @@ def create_instance(cls, openshift: OpenShiftClient, name, image=None, model["spec"]["authConfigLabelSelectors"] = ",".join(label_selectors) if listener_certificate_secret: - model["spec"]["listener"]["tls"] = { - "enabled": True, - "certSecretRef": {"name": listener_certificate_secret} - } + model["spec"]["listener"]["tls"] = {"enabled": True, "certSecretRef": {"name": listener_certificate_secret}} with openshift.context: return cls(model) @@ -58,8 +51,8 @@ def wait_for_ready(self): """Waits until Authorino CR reports ready status""" with openshift.timeout(90): success, _, _ = self.self_selector().until_all( - success_func=lambda obj: - len(obj.model.status.conditions) > 0 and all(x.status == "True" for x in obj.model.status.conditions) + success_func=lambda obj: len(obj.model.status.conditions) > 0 + and all(x.status == "True" for x in obj.model.status.conditions) ) assert success, "Authorino did got get ready in time" self.refresh() diff --git a/testsuite/openshift/objects/ingress.py b/testsuite/openshift/objects/ingress.py index a639cb90..02f4d45b 100644 --- a/testsuite/openshift/objects/ingress.py +++ b/testsuite/openshift/objects/ingress.py @@ -13,8 +13,13 @@ class Ingress(OpenShiftObject, LifecycleObject): """Represents Kubernetes Ingress object""" @classmethod - def create_instance(cls, openshift: 'OpenShiftClient', name, rules: Optional[List[Dict[str, Any]]] = None, - tls: Optional[List[Dict[str, Any]]] = None): + def create_instance( + cls, + openshift: "OpenShiftClient", + name, + rules: Optional[List[Dict[str, Any]]] = None, + tls: Optional[List[Dict[str, Any]]] = None, + ): """Creates base instance""" if rules is None: rules = [] @@ -25,22 +30,17 @@ def create_instance(cls, openshift: 'OpenShiftClient', name, rules: Optional[Lis model: Dict[str, Any] = { "apiVersion": "networking.k8s.io/v1", "kind": "Ingress", - "metadata": { - "name": name, - "namespace": openshift.project - }, - "spec": { - "rules": rules, - "tls": tls - } + "metadata": {"name": name, "namespace": openshift.project}, + "spec": {"rules": rules, "tls": tls}, } with openshift.context: return cls(model) @classmethod - def create_service_ingress(cls, openshift: 'OpenShiftClient', name, service_name, port_number=80, path="/", - path_type="Prefix", host=None): + def create_service_ingress( + cls, openshift: "OpenShiftClient", name, service_name, port_number=80, path="/", path_type="Prefix", host=None + ): """ Creates Ingress instance for service without tls configured """ @@ -48,16 +48,9 @@ def create_service_ingress(cls, openshift: 'OpenShiftClient', name, service_name "http": { "paths": [ { - "backend": { - "service": { - "name": service_name, - "port": { - "number": port_number - } - } - }, + "backend": {"service": {"name": service_name, "port": {"number": port_number}}}, "path": path, - "pathType": path_type + "pathType": path_type, }, ] } @@ -75,10 +68,12 @@ def rules(self): def wait_for_hosts(self, tolerate_failures: int = 5): """Waits until all rules within the ingress have host fields filled""" + def _all_rules_have_host(obj): return all("host" in r and len(r.get("host")) > 0 for r in obj.model.spec.rules) - success, _, _ = self.self_selector().until_all(success_func=_all_rules_have_host, - tolerate_failures=tolerate_failures) + success, _, _ = self.self_selector().until_all( + success_func=_all_rules_have_host, tolerate_failures=tolerate_failures + ) return success diff --git a/testsuite/openshift/objects/route.py b/testsuite/openshift/objects/route.py index 759ed7ff..38858ebf 100644 --- a/testsuite/openshift/objects/route.py +++ b/testsuite/openshift/objects/route.py @@ -16,6 +16,7 @@ def hostnames(self) -> list[str]: class OpenshiftRoute(OpenShiftObject, Route): """Openshift Route object""" + @cached_property def hostnames(self): return [self.model.spec.host] diff --git a/testsuite/openshift/types/__init__.py b/testsuite/openshift/types/__init__.py index a5ddbc56..14647342 100644 --- a/testsuite/openshift/types/__init__.py +++ b/testsuite/openshift/types/__init__.py @@ -9,7 +9,7 @@ class RemoteMapping: """Dict-like interface to different types of OpenShift Objects""" - def __init__(self, client: 'OpenShiftClient', resource_name: str): + def __init__(self, client: "OpenShiftClient", resource_name: str): self._client = client self._resource_name = resource_name diff --git a/testsuite/openshift/types/routes.py b/testsuite/openshift/types/routes.py index f3407791..15fcb4d4 100644 --- a/testsuite/openshift/types/routes.py +++ b/testsuite/openshift/types/routes.py @@ -17,5 +17,6 @@ def expose(self, name, service, hostname=None, port=None): extra_args.append(f"--hostname={hostname}") if port is not None: extra_args.append(f"--port={port}") - return self._client.do_action("expose", "service", f"--name={name}", "-o", "json", - service, *extra_args, parse_output=True) + return self._client.do_action( + "expose", "service", f"--name={name}", "-o", "json", service, *extra_args, parse_output=True + ) diff --git a/testsuite/perf_utils.py b/testsuite/perf_utils.py index f5c554ea..61b61d83 100644 --- a/testsuite/perf_utils.py +++ b/testsuite/perf_utils.py @@ -25,20 +25,21 @@ def authority(url: str): def prepare_url(url: ParseResult) -> ParseResult: - """ Adds port number to url if it is not set""" + """Adds port number to url if it is not set""" if not url.hostname: raise ValueError("Missing hostname part of url") if not url.port: - url_port = 80 if url.scheme == 'http' else 443 + url_port = 80 if url.scheme == "http" else 443 url = url._replace(netloc=url.hostname + f":{url_port}") return url class HyperfoilUtils(LifecycleObject): """ - Setup class for hyperfoil test and wrapper of Hyperfoil-python-client. + Setup class for hyperfoil test and wrapper of Hyperfoil-python-client. """ - message_1kb = resources.files('testsuite.resources.performance.files').joinpath('message_1kb.txt') + + message_1kb = resources.files("testsuite.resources.performance.files").joinpath("message_1kb.txt") def __init__(self, hyperfoil_client, template_filename): self.hyperfoil_client = hyperfoil_client @@ -61,10 +62,10 @@ def update_benchmark(self, benchmark): def add_shared_template(self, agents_number: int): """Updates benchmark with shared template for hyperfoil agents setup""" - agents: dict = {'agents': {}} + agents: dict = {"agents": {}} for i in range(1, agents_number + 1): - agent = {'host': 'localhost', 'port': 22, 'stop': True} - agents['agents'][f'agent-{i}'] = agent + agent = {"host": "localhost", "port": 22, "stop": True} + agents["agents"][f"agent-{i}"] = agent self.benchmark.update(agents) def delete(self): @@ -79,7 +80,7 @@ def add_host(self, url: str, shared_connections: int, **kwargs): def add_file(self, path): """Adds file to the benchmark""" filename = os.path.basename(path) - self.factory.file(filename, open(path, 'r', encoding="utf8")) + self.factory.file(filename, open(path, "r", encoding="utf8")) def generate_random_file(self, filename: str, size: int): """Generates and adds file with such filename and size to the benchmark""" @@ -104,7 +105,8 @@ def add_rhsso_auth_token(self, rhsso, client_url, filename): :param filename: name of csv file """ rows = [] - token_url_obj = prepare_url(urlparse(rhsso.well_known['token_endpoint'])) - rows.append([client_url, f"{token_url_obj.hostname}:{token_url_obj.port}", token_url_obj.path, - rhsso.token_params()]) + token_url_obj = prepare_url(urlparse(rhsso.well_known["token_endpoint"])) + rows.append( + [client_url, f"{token_url_obj.hostname}:{token_url_obj.port}", token_url_obj.path, rhsso.token_params()] + ) self.factory.csv_data(filename, rows) diff --git a/testsuite/tests/conftest.py b/testsuite/tests/conftest.py index b95c32a9..b2f555eb 100644 --- a/testsuite/tests/conftest.py +++ b/testsuite/tests/conftest.py @@ -21,9 +21,9 @@ def pytest_addoption(parser): """Add options to include various kinds of tests in testrun""" parser.addoption( - "--performance", action="store_true", default=False, help="Run also performance tests (default: False)") - parser.addoption( - "--glbc", action="store_true", default=False, help="Run also glbc tests (default: False)") + "--performance", action="store_true", default=False, help="Run also performance tests (default: False)" + ) + parser.addoption("--glbc", action="store_true", default=False, help="Run also glbc tests (default: False)") def pytest_runtest_setup(item): @@ -35,7 +35,7 @@ def pytest_runtest_setup(item): pytest.skip("Excluding glbc tests") -@pytest.fixture(scope='session', autouse=True) +@pytest.fixture(scope="session", autouse=True) def term_handler(): """ This will handle ^C, cleanup won't be skipped @@ -112,8 +112,15 @@ def rhsso(request, testconfig, blame): try: testconfig.validators.validate(only="rhsso") cnf = testconfig["rhsso"] - info = RHSSO(cnf["url"], cnf["username"], cnf["password"], blame("realm"), blame("client"), - cnf["test_user"]["username"], cnf["test_user"]["password"]) + info = RHSSO( + cnf["url"], + cnf["username"], + cnf["password"], + blame("realm"), + blame("client"), + cnf["test_user"]["username"], + cnf["test_user"]["password"], + ) if not testconfig["skip_cleanup"]: request.addfinalizer(info.delete) @@ -155,6 +162,7 @@ def oidc_provider(rhsso) -> OIDCProvider: @pytest.fixture(scope="session") def blame(request): """Returns function that will add random identifier to the name""" + def _blame(name: str, tail: int = 3) -> str: """Create 'scoped' name within given test @@ -176,6 +184,7 @@ def _blame(name: str, tail: int = 3) -> str: context = context.split(".")[0] return randomize(f"{name[:8]}-{_whoami()[:8]}-{context[:9]}", tail=tail) + return _blame diff --git a/testsuite/tests/kuadrant/authorino/conftest.py b/testsuite/tests/kuadrant/authorino/conftest.py index cc3f6af3..8f5bba78 100644 --- a/testsuite/tests/kuadrant/authorino/conftest.py +++ b/testsuite/tests/kuadrant/authorino/conftest.py @@ -30,12 +30,14 @@ def authorino(authorino, openshift, blame, request, testconfig, module_label, au labels = authorino_parameters.setdefault("label_selectors", []) labels.append(f"testRun={module_label}") - authorino_parameters.setdefault('name', blame("authorino")) - - authorino = AuthorinoCR.create_instance(openshift, - image=weakget(testconfig)["authorino"]["image"] % None, - log_level=weakget(testconfig)["authorino"]["log_level"] % None, - **authorino_parameters) + authorino_parameters.setdefault("name", blame("authorino")) + + authorino = AuthorinoCR.create_instance( + openshift, + image=weakget(testconfig)["authorino"]["image"] % None, + log_level=weakget(testconfig)["authorino"]["log_level"] % None, + **authorino_parameters, + ) request.addfinalizer(lambda: authorino.delete(ignore_not_found=True)) authorino.commit() authorino.wait_for_ready() @@ -44,12 +46,14 @@ def authorino(authorino, openshift, blame, request, testconfig, module_label, au # pylint: disable=unused-argument @pytest.fixture(scope="module") -def authorization(authorization, oidc_provider, authorino, envoy, - authorization_name, openshift, module_label) -> Authorization: +def authorization( + authorization, oidc_provider, authorino, envoy, authorization_name, openshift, module_label +) -> Authorization: """In case of Authorino, AuthConfig used for authorization""" if authorization is None: - authorization = AuthConfig.create_instance(openshift, authorization_name, - envoy.route, labels={"testRun": module_label}) + authorization = AuthConfig.create_instance( + openshift, authorization_name, envoy.route, labels={"testRun": module_label} + ) authorization.identity.oidc("rhsso", oidc_provider.well_known["issuer"]) return authorization @@ -71,10 +75,12 @@ def client(authorization, envoy): @pytest.fixture(scope="module") def create_api_key(blame, request, openshift): """Creates API key Secret""" + def _create_secret(name, label_selector, api_key, ocp: OpenShiftClient = openshift): secret_name = blame(name) secret = APIKey.create_instance(ocp, secret_name, label_selector, api_key) request.addfinalizer(lambda: secret.delete(ignore_not_found=True)) secret.commit() return secret + return _create_secret diff --git a/testsuite/tests/kuadrant/authorino/dinosaur/conftest.py b/testsuite/tests/kuadrant/authorino/dinosaur/conftest.py index 0ad5ccf4..522c3df4 100644 --- a/testsuite/tests/kuadrant/authorino/dinosaur/conftest.py +++ b/testsuite/tests/kuadrant/authorino/dinosaur/conftest.py @@ -20,8 +20,15 @@ def run_on_kuadrant(): def admin_rhsso(request, testconfig, blame, rhsso): """RHSSO OIDC Provider fixture""" - info = RHSSO(rhsso.server_url, rhsso.username, rhsso.password, blame("realm"), blame("client"), - rhsso.test_username, rhsso.test_password) + info = RHSSO( + rhsso.server_url, + rhsso.username, + rhsso.password, + blame("realm"), + blame("client"), + rhsso.test_username, + rhsso.test_password, + ) if not testconfig["skip_cleanup"]: request.addfinalizer(info.delete) @@ -56,9 +63,7 @@ def cluster_info(request, mockserver, module_label): def _cluster_info(value): return mockserver.create_expectation( - f"{module_label}-cluster", - {"client_id": value}, - ContentType.APPLICATION_JSON + f"{module_label}-cluster", {"client_id": value}, ContentType.APPLICATION_JSON ) request.addfinalizer(lambda: mockserver.clear_expectation(f"{module_label}-cluster")) @@ -86,21 +91,34 @@ def commit(): @pytest.fixture(scope="module") -def authorization(openshift, blame, envoy, module_label, rhsso, terms_and_conditions, cluster_info, admin_rhsso, - resource_info, request): +def authorization( + openshift, + blame, + envoy, + module_label, + rhsso, + terms_and_conditions, + cluster_info, + admin_rhsso, + resource_info, + request, +): """Creates AuthConfig object from template""" with resources.path("testsuite.resources", "dinosaur_config.yaml") as path: - auth = openshift.new_app(path, { - "NAME": blame("ac"), - "NAMESPACE": openshift.project, - "LABEL": module_label, - "HOST": envoy.hostname, - "RHSSO_ISSUER": rhsso.well_known['issuer'], - "ADMIN_ISSUER": admin_rhsso.well_known["issuer"], - "TERMS_AND_CONDITIONS": terms_and_conditions("false"), - "CLUSTER_INFO": cluster_info(rhsso.client_name), - "RESOURCE_INFO": resource_info("123", rhsso.client_name) - }) + auth = openshift.new_app( + path, + { + "NAME": blame("ac"), + "NAMESPACE": openshift.project, + "LABEL": module_label, + "HOST": envoy.hostname, + "RHSSO_ISSUER": rhsso.well_known["issuer"], + "ADMIN_ISSUER": admin_rhsso.well_known["issuer"], + "TERMS_AND_CONDITIONS": terms_and_conditions("false"), + "CLUSTER_INFO": cluster_info(rhsso.client_name), + "RESOURCE_INFO": resource_info("123", rhsso.client_name), + }, + ) def _delete(): auth.delete() diff --git a/testsuite/tests/kuadrant/authorino/dinosaur/test_auth_config.py b/testsuite/tests/kuadrant/authorino/dinosaur/test_auth_config.py index 06bb085e..8a9cf48e 100644 --- a/testsuite/tests/kuadrant/authorino/dinosaur/test_auth_config.py +++ b/testsuite/tests/kuadrant/authorino/dinosaur/test_auth_config.py @@ -4,9 +4,13 @@ import pytest -ERROR_MESSAGE = {'kind': 'Error', 'id': '403', 'href': '/api/dinosaurs_mgmt/v1/errors/403', - 'code': 'DINOSAURS-MGMT-403', - 'reason': 'Forbidden'} +ERROR_MESSAGE = { + "kind": "Error", + "id": "403", + "href": "/api/dinosaurs_mgmt/v1/errors/403", + "code": "DINOSAURS-MGMT-403", + "reason": "Forbidden", +} def test_deny_email(client, user_with_invalid_email): @@ -41,8 +45,7 @@ def test_deny_invalid_org_id(client, user_with_invalid_org_id): assert response.json() == ERROR_MESSAGE -@pytest.mark.parametrize("user", ["user_with_full_role", "user_with_read_role", - "user_with_write_role"]) +@pytest.mark.parametrize("user", ["user_with_full_role", "user_with_read_role", "user_with_write_role"]) def test_admin_sso_get(client, user_with_valid_org_id, user, request): """ Test: diff --git a/testsuite/tests/kuadrant/authorino/identity/anonymous/test_anonymous_context.py b/testsuite/tests/kuadrant/authorino/identity/anonymous/test_anonymous_context.py index 3a291567..6ff395c9 100644 --- a/testsuite/tests/kuadrant/authorino/identity/anonymous/test_anonymous_context.py +++ b/testsuite/tests/kuadrant/authorino/identity/anonymous/test_anonymous_context.py @@ -8,8 +8,12 @@ def authorization(authorization): """Setup AuthConfig for test""" authorization.identity.anonymous("anonymous") - authorization.responses.add({"name": "auth-json", "json": { - "properties": [{"name": "auth", "valueFrom": {"authJSON": "auth.identity.anonymous"}}]}}) + authorization.responses.add( + { + "name": "auth-json", + "json": {"properties": [{"name": "auth", "valueFrom": {"authJSON": "auth.identity.anonymous"}}]}, + } + ) return authorization diff --git a/testsuite/tests/kuadrant/authorino/identity/api_key/test_api_key_context.py b/testsuite/tests/kuadrant/authorino/identity/api_key/test_api_key_context.py index 58bbc0fb..dfcf8e8e 100644 --- a/testsuite/tests/kuadrant/authorino/identity/api_key/test_api_key_context.py +++ b/testsuite/tests/kuadrant/authorino/identity/api_key/test_api_key_context.py @@ -8,8 +8,9 @@ def authorization(authorization, module_label): """Setup AuthConfig for test""" authorization.identity.api_key("api_key", match_label=module_label) - authorization.responses.add({"name": "auth-json", "json": { - "properties": [{"name": "auth", "valueFrom": {"authJSON": "auth.identity"}}]}}) + authorization.responses.add( + {"name": "auth-json", "json": {"properties": [{"name": "auth", "valueFrom": {"authJSON": "auth.identity"}}]}} + ) return authorization @@ -22,6 +23,6 @@ def tests_api_key_context(client, auth, api_key, module_label, testconfig): response = client.get("get", auth=auth) assert response.status_code == 200 identity = json.loads(response.json()["headers"]["Auth-Json"])["auth"] - assert identity['data']['api_key'] == api_key.model.data.api_key + assert identity["data"]["api_key"] == api_key.model.data.api_key assert identity["metadata"]["namespace"] == testconfig["openshift"].project assert identity["metadata"]["labels"]["group"] == module_label diff --git a/testsuite/tests/kuadrant/authorino/identity/api_key/test_auth_credentials.py b/testsuite/tests/kuadrant/authorino/identity/api_key/test_auth_credentials.py index a480730a..98423e1d 100644 --- a/testsuite/tests/kuadrant/authorino/identity/api_key/test_auth_credentials.py +++ b/testsuite/tests/kuadrant/authorino/identity/api_key/test_auth_credentials.py @@ -4,12 +4,7 @@ from testsuite.openshift.objects.auth_config import AuthConfig -@pytest.fixture(scope="module", params=[ - "authorization_header", - "custom_header", - "query", - "cookie" -]) +@pytest.fixture(scope="module", params=["authorization_header", "custom_header", "query", "cookie"]) def credentials(request): """Location where are auth credentials passed""" return request.param @@ -18,32 +13,30 @@ def credentials(request): @pytest.fixture(scope="module") def authorization(openshift, blame, envoy, module_label, credentials): """Add API key identity to AuthConfig""" - authorization = AuthConfig.create_instance(openshift, blame("ac"), - envoy.route, labels={"testRun": module_label}) - authorization.identity.api_key("api_key", match_label=module_label, credentials=credentials, - selector="API_KEY") + authorization = AuthConfig.create_instance(openshift, blame("ac"), envoy.route, labels={"testRun": module_label}) + authorization.identity.api_key("api_key", match_label=module_label, credentials=credentials, selector="API_KEY") return authorization def test_custom_selector(client, auth, credentials): """Test if auth credentials are stored in right place""" - response = client.get("/get", headers={'authorization': "API_KEY " + auth.api_key}) + response = client.get("/get", headers={"authorization": "API_KEY " + auth.api_key}) assert response.status_code == 200 if credentials == "authorization_header" else 401 def test_custom_header(client, auth, credentials): """Test if auth credentials are stored in right place""" - response = client.get("/get", headers={'API_KEY': auth.api_key}) + response = client.get("/get", headers={"API_KEY": auth.api_key}) assert response.status_code == 200 if credentials == "custom_header" else 401 def test_query(client, auth, credentials): """Test if auth credentials are stored in right place""" - response = client.get("/get", params={'API_KEY': auth.api_key}) + response = client.get("/get", params={"API_KEY": auth.api_key}) assert response.status_code == 200 if credentials == "query" else 401 def test_cookie(client, auth, credentials): """Test if auth credentials are stored in right place""" - response = client.get("/get", cookies={'API_KEY': auth.api_key}) + response = client.get("/get", cookies={"API_KEY": auth.api_key}) assert response.status_code == 200 if credentials == "cookie" else 401 diff --git a/testsuite/tests/kuadrant/authorino/identity/rhsso/test_auth_credentials.py b/testsuite/tests/kuadrant/authorino/identity/rhsso/test_auth_credentials.py index 3cf88632..aa35600a 100644 --- a/testsuite/tests/kuadrant/authorino/identity/rhsso/test_auth_credentials.py +++ b/testsuite/tests/kuadrant/authorino/identity/rhsso/test_auth_credentials.py @@ -4,12 +4,7 @@ from testsuite.openshift.objects.auth_config import AuthConfig -@pytest.fixture(scope="module", params=[ - "authorization_header", - "custom_header", - "query", - "cookie" -]) +@pytest.fixture(scope="module", params=["authorization_header", "custom_header", "query", "cookie"]) def credentials(request): """Location where are auth credentials passed""" return request.param @@ -18,31 +13,30 @@ def credentials(request): @pytest.fixture(scope="module") def authorization(rhsso, openshift, blame, envoy, module_label, credentials): """Add RHSSO identity to AuthConfig""" - authorization = AuthConfig.create_instance(openshift, blame("ac"), - envoy.route, labels={"testRun": module_label}) + authorization = AuthConfig.create_instance(openshift, blame("ac"), envoy.route, labels={"testRun": module_label}) authorization.identity.oidc("rhsso", rhsso.well_known["issuer"], credentials, "Token") return authorization def test_custom_selector(client, auth, credentials): """Test if auth credentials are stored in right place""" - response = client.get("/get", headers={'authorization': "Token " + auth.token.access_token}) + response = client.get("/get", headers={"authorization": "Token " + auth.token.access_token}) assert response.status_code == 200 if credentials == "authorization_header" else 401 def test_custom_header(client, auth, credentials): """Test if auth credentials are stored in right place""" - response = client.get("/get", headers={'Token': auth.token.access_token}) + response = client.get("/get", headers={"Token": auth.token.access_token}) assert response.status_code == 200 if credentials == "custom_header" else 401 def test_query(client, auth, credentials): """Test if auth credentials are stored in right place""" - response = client.get("/get", params={'Token': auth.token.access_token}) + response = client.get("/get", params={"Token": auth.token.access_token}) assert response.status_code == 200 if credentials == "query" else 401 def test_cookie(client, auth, credentials): """Test if auth credentials are stored in right place""" - response = client.get("/get", cookies={'Token': auth.token.access_token}) + response = client.get("/get", cookies={"Token": auth.token.access_token}) assert response.status_code == 200 if credentials == "cookie" else 401 diff --git a/testsuite/tests/kuadrant/authorino/identity/rhsso/test_rhsso_context.py b/testsuite/tests/kuadrant/authorino/identity/rhsso/test_rhsso_context.py index 279e57a0..f1b2065f 100644 --- a/testsuite/tests/kuadrant/authorino/identity/rhsso/test_rhsso_context.py +++ b/testsuite/tests/kuadrant/authorino/identity/rhsso/test_rhsso_context.py @@ -8,9 +8,17 @@ @pytest.fixture(scope="module") def authorization(authorization): """Setup AuthConfig for test""" - authorization.responses.add({"name": "auth-json", "json": { - "properties": [{"name": "auth", "valueFrom": {"authJSON": "auth.identity"}}, - {"name": "context", "valueFrom": {"authJSON": "context.request.http.headers.authorization"}}]}}) + authorization.responses.add( + { + "name": "auth-json", + "json": { + "properties": [ + {"name": "auth", "valueFrom": {"authJSON": "auth.identity"}}, + {"name": "context", "valueFrom": {"authJSON": "context.request.http.headers.authorization"}}, + ] + }, + } + ) return authorization @@ -38,4 +46,4 @@ def tests_rhsso_context(client, auth, rhsso, realm_role): assert float(identity["iat"]) <= now assert auth_json["context"] == f"Bearer {auth.token.access_token}" assert realm_role["name"] in identity["realm_access"]["roles"] - assert identity['email'] == rhsso.user.properties["email"] + assert identity["email"] == rhsso.user.properties["email"] diff --git a/testsuite/tests/kuadrant/authorino/metadata/conftest.py b/testsuite/tests/kuadrant/authorino/metadata/conftest.py index e4f86155..d98a9917 100644 --- a/testsuite/tests/kuadrant/authorino/metadata/conftest.py +++ b/testsuite/tests/kuadrant/authorino/metadata/conftest.py @@ -7,6 +7,7 @@ @pytest.fixture(scope="module") def create_client_secret(request, openshift): """Creates Client Secret, used by Authorino to start the authentication with the UMA registry""" + def _create_secret(name, client_id, client_secret): model = { "apiVersion": "v1", @@ -14,14 +15,12 @@ def _create_secret(name, client_id, client_secret): "metadata": { "name": name, }, - "stringData": { - "clientID": client_id, - "clientSecret": client_secret - }, - "type": "Opaque" + "stringData": {"clientID": client_id, "clientSecret": client_secret}, + "type": "Opaque", } secret = OpenShiftObject(model, context=openshift.context) request.addfinalizer(lambda: secret.delete(ignore_not_found=True)) secret.commit() return secret + return _create_secret diff --git a/testsuite/tests/kuadrant/authorino/metadata/test_user_info.py b/testsuite/tests/kuadrant/authorino/metadata/test_user_info.py index 36a4bead..8d2e7947 100644 --- a/testsuite/tests/kuadrant/authorino/metadata/test_user_info.py +++ b/testsuite/tests/kuadrant/authorino/metadata/test_user_info.py @@ -21,8 +21,9 @@ def authorization(authorization, rhsso): Adds a simple rule that accepts only when fetched UserInfo contains the email address of the default RHSSO user. """ authorization.metadata.user_info_metadata("user-info", "rhsso") - authorization.authorization.auth_rule("rule", - Rule("auth.metadata.user-info.email", "eq", rhsso.user.properties["email"])) + authorization.authorization.auth_rule( + "rule", Rule("auth.metadata.user-info.email", "eq", rhsso.user.properties["email"]) + ) return authorization diff --git a/testsuite/tests/kuadrant/authorino/multiple_hosts/conftest.py b/testsuite/tests/kuadrant/authorino/multiple_hosts/conftest.py index 37822fe8..00bc69ea 100644 --- a/testsuite/tests/kuadrant/authorino/multiple_hosts/conftest.py +++ b/testsuite/tests/kuadrant/authorino/multiple_hosts/conftest.py @@ -13,7 +13,7 @@ def hostname(envoy): @pytest.fixture(scope="module") def second_hostname(envoy, blame): """Second valid hostname""" - return envoy.add_hostname(blame('second')) + return envoy.add_hostname(blame("second")) @pytest.fixture(scope="module") diff --git a/testsuite/tests/kuadrant/authorino/operator/clusterwide/conftest.py b/testsuite/tests/kuadrant/authorino/operator/clusterwide/conftest.py index fb54e99c..70c8e167 100644 --- a/testsuite/tests/kuadrant/authorino/operator/clusterwide/conftest.py +++ b/testsuite/tests/kuadrant/authorino/operator/clusterwide/conftest.py @@ -19,8 +19,9 @@ def hostname2(envoy, blame): @pytest.fixture(scope="module") def authorization2(hostname2, blame, openshift2, module_label, oidc_provider): """Second valid hostname""" - auth = AuthConfig.create_instance(openshift2, blame("ac"), None, - hostnames=[hostname2], labels={"testRun": module_label}) + auth = AuthConfig.create_instance( + openshift2, blame("ac"), None, hostnames=[hostname2], labels={"testRun": module_label} + ) auth.identity.oidc("rhsso", oidc_provider.well_known["issuer"]) return auth diff --git a/testsuite/tests/kuadrant/authorino/operator/clusterwide/test_clusterwide.py b/testsuite/tests/kuadrant/authorino/operator/clusterwide/test_clusterwide.py index ac213b40..60366e6e 100644 --- a/testsuite/tests/kuadrant/authorino/operator/clusterwide/test_clusterwide.py +++ b/testsuite/tests/kuadrant/authorino/operator/clusterwide/test_clusterwide.py @@ -2,10 +2,13 @@ import pytest -@pytest.mark.parametrize("client_fixture", [ - pytest.param("client", id="First namespace"), - pytest.param("client2", id="Second namespace"), -]) +@pytest.mark.parametrize( + "client_fixture", + [ + pytest.param("client", id="First namespace"), + pytest.param("client2", id="Second namespace"), + ], +) def test_auth(request, client_fixture, auth): """Tests that both AuthConfigs were reconciled in both namespaces""" client = request.getfixturevalue(client_fixture) diff --git a/testsuite/tests/kuadrant/authorino/operator/clusterwide/test_wildcard_collision.py b/testsuite/tests/kuadrant/authorino/operator/clusterwide/test_wildcard_collision.py index 2d1cb4b8..db274faa 100644 --- a/testsuite/tests/kuadrant/authorino/operator/clusterwide/test_wildcard_collision.py +++ b/testsuite/tests/kuadrant/authorino/operator/clusterwide/test_wildcard_collision.py @@ -29,10 +29,13 @@ def authorization2(authorino, blame, openshift2, module_label, envoy, wildcard_d return auth -@pytest.mark.parametrize(("client_fixture", "auth_fixture", "hosts"), [ - pytest.param("client", "authorization", "wildcard_domain", id="First namespace"), - pytest.param("client2", "authorization2", [], id="Second namespace"), -]) +@pytest.mark.parametrize( + ("client_fixture", "auth_fixture", "hosts"), + [ + pytest.param("client", "authorization", "wildcard_domain", id="First namespace"), + pytest.param("client2", "authorization2", [], id="Second namespace"), + ], +) def test_wildcard_collision(client_fixture, auth_fixture, hosts, request): """ Preparation: diff --git a/testsuite/tests/kuadrant/authorino/operator/http/conftest.py b/testsuite/tests/kuadrant/authorino/operator/http/conftest.py index b80a3ba5..045f53c7 100644 --- a/testsuite/tests/kuadrant/authorino/operator/http/conftest.py +++ b/testsuite/tests/kuadrant/authorino/operator/http/conftest.py @@ -11,11 +11,11 @@ def authorization(authorization, wildcard_domain, openshift, module_label) -> Au """In case of Authorino, AuthConfig used for authorization""" authorization.remove_all_hosts() authorization.add_host(wildcard_domain) - resp = {'name': 'another-json-returned-in-a-header', - 'wrapperKey': 'x-ext-auth-other-json', - 'json': {'properties': [ - {'name': 'propX', 'value': 'valueX'} - ]}} + resp = { + "name": "another-json-returned-in-a-header", + "wrapperKey": "x-ext-auth-other-json", + "json": {"properties": [{"name": "propX", "value": "valueX"}]}, + } authorization.responses.add(response=resp) return authorization @@ -31,7 +31,6 @@ def client(authorization, authorino_route): @pytest.fixture(scope="module") def authorino_route(authorino, blame, openshift): """Add route for authorino http port to be able to access it.""" - route = openshift.routes.expose(blame('route'), f"{authorino.name()}-authorino-authorization", - port='http') + route = openshift.routes.expose(blame("route"), f"{authorino.name()}-authorino-authorization", port="http") yield route route.delete() diff --git a/testsuite/tests/kuadrant/authorino/operator/http/test_raw_http.py b/testsuite/tests/kuadrant/authorino/operator/http/test_raw_http.py index 355eabbc..1186206a 100644 --- a/testsuite/tests/kuadrant/authorino/operator/http/test_raw_http.py +++ b/testsuite/tests/kuadrant/authorino/operator/http/test_raw_http.py @@ -8,8 +8,8 @@ def test_authorized_via_http(authorization, client, auth): """Test raw http authentization with Keycloak.""" response = client.get("/check", auth=auth) assert response.status_code == 200 - assert response.text == '' - assert response.headers.get('x-ext-auth-other-json', '') == '{"propX":"valueX"}' + assert response.text == "" + assert response.headers.get("x-ext-auth-other-json", "") == '{"propX":"valueX"}' # pylint: disable=unused-argument @@ -17,4 +17,4 @@ def test_unauthorized_via_http(authorization, client): """Test raw http authentization with unauthorized request.""" response = client.get("/check") assert response.status_code == 401 - assert response.text == '' + assert response.text == "" diff --git a/testsuite/tests/kuadrant/authorino/operator/sharding/conftest.py b/testsuite/tests/kuadrant/authorino/operator/sharding/conftest.py index 782f686a..f4d9d129 100644 --- a/testsuite/tests/kuadrant/authorino/operator/sharding/conftest.py +++ b/testsuite/tests/kuadrant/authorino/operator/sharding/conftest.py @@ -24,8 +24,13 @@ def authorization(request, authorino, blame, openshift, module_label): """In case of Authorino, AuthConfig used for authorization""" def _authorization(hostname=None, sharding_label=None): - auth = AuthConfig.create_instance(openshift, blame("ac"), None, hostnames=[hostname], - labels={"testRun": module_label, "sharding": sharding_label}) + auth = AuthConfig.create_instance( + openshift, + blame("ac"), + None, + hostnames=[hostname], + labels={"testRun": module_label, "sharding": sharding_label}, + ) auth.responses.add({"name": "header", "json": {"properties": [{"name": "anything", "value": sharding_label}]}}) request.addfinalizer(auth.delete) auth.commit() diff --git a/testsuite/tests/kuadrant/authorino/operator/sharding/test_preexisting_auth.py b/testsuite/tests/kuadrant/authorino/operator/sharding/test_preexisting_auth.py index 4df7e45b..277fbce2 100644 --- a/testsuite/tests/kuadrant/authorino/operator/sharding/test_preexisting_auth.py +++ b/testsuite/tests/kuadrant/authorino/operator/sharding/test_preexisting_auth.py @@ -12,10 +12,12 @@ def authorino(openshift, blame, testconfig, module_label, request): def _authorino(sharding_label): authorino_parameters = {"label_selectors": [f"sharding={sharding_label}", f"testRun={module_label}"]} - authorino = AuthorinoCR.create_instance(openshift, - blame("authorino"), - image=weakget(testconfig)["authorino"]["image"] % None, - **authorino_parameters) + authorino = AuthorinoCR.create_instance( + openshift, + blame("authorino"), + image=weakget(testconfig)["authorino"]["image"] % None, + **authorino_parameters, + ) request.addfinalizer(lambda: authorino.delete(ignore_not_found=True)) authorino.commit() authorino.wait_for_ready() diff --git a/testsuite/tests/kuadrant/authorino/operator/tls/conftest.py b/testsuite/tests/kuadrant/authorino/operator/tls/conftest.py index 59b960a3..67e1df45 100644 --- a/testsuite/tests/kuadrant/authorino/operator/tls/conftest.py +++ b/testsuite/tests/kuadrant/authorino/operator/tls/conftest.py @@ -23,11 +23,13 @@ def cert_attributes() -> Dict[str, str]: @pytest.fixture(scope="session") def cert_attributes_other(cert_attributes) -> Dict[str, str]: """Certificate attributes that are partially different from the default ones""" - return {"O": "Other Organization", - "OU": "Other Unit", - "L": cert_attributes["L"], - "ST": cert_attributes["ST"], - "C": cert_attributes["C"]} + return { + "O": "Other Organization", + "OU": "Other Unit", + "L": cert_attributes["L"], + "ST": cert_attributes["ST"], + "C": cert_attributes["C"], + } @pytest.fixture(scope="session") @@ -37,17 +39,19 @@ def certificates(cfssl, authorino_domain, wildcard_domain, cert_attributes, cert May be overwritten to configure different test cases """ chain = { - "envoy_ca": CertInfo(children={ - "envoy_cert": None, - "valid_cert": CertInfo(names=[cert_attributes]), - "custom_cert": CertInfo(names=[cert_attributes_other]) - }), - "authorino_ca": CertInfo(children={ - "authorino_cert": CertInfo(hosts=authorino_domain), - }), - "invalid_ca": CertInfo(children={ - "invalid_cert": None - }) + "envoy_ca": CertInfo( + children={ + "envoy_cert": None, + "valid_cert": CertInfo(names=[cert_attributes]), + "custom_cert": CertInfo(names=[cert_attributes_other]), + } + ), + "authorino_ca": CertInfo( + children={ + "authorino_cert": CertInfo(hosts=authorino_domain), + } + ), + "invalid_ca": CertInfo(children={"invalid_cert": None}), } return cert_builder(cfssl, chain, wildcard_domain) @@ -55,11 +59,13 @@ def certificates(cfssl, authorino_domain, wildcard_domain, cert_attributes, cert @pytest.fixture(scope="module") def create_secret(blame, request, openshift): """Creates TLS secret from Certificate""" + def _create_secret(certificate: Certificate, name: str, labels: Optional[Dict[str, str]] = None): secret_name = blame(name) secret = openshift.create_tls_secret(secret_name, certificate, labels=labels) request.addfinalizer(lambda: openshift.delete_selector(secret)) return secret_name + return _create_secret @@ -138,24 +144,42 @@ def selector_params(module_label): @pytest.fixture(scope="module") def authorino_labels(selector_params) -> Dict[str, str]: """Labels for the proper Authorino discovery""" - labels = { - "authorino.kuadrant.io/managed-by": "authorino", - selector_params[0]: selector_params[1] - } + labels = {"authorino.kuadrant.io/managed-by": "authorino", selector_params[0]: selector_params[1]} return labels # pylint: disable-msg=too-many-locals @pytest.fixture(scope="module") -def envoy(request, authorino, openshift, create_secret, blame, label, backend, - authorino_authority, envoy_authority, envoy_cert, testconfig, authorino_labels): +def envoy( + request, + authorino, + openshift, + create_secret, + blame, + label, + backend, + authorino_authority, + envoy_authority, + envoy_cert, + testconfig, + authorino_labels, +): """Envoy + Httpbin backend""" authorino_secret = create_secret(authorino_authority, "authca") envoy_ca_secret = create_secret(envoy_authority, "backendca", labels=authorino_labels) envoy_secret = create_secret(envoy_cert, "envoycert") - envoy = TLSEnvoy(openshift, authorino, blame("backend"), label, backend, testconfig["envoy"]["image"], - authorino_secret, envoy_ca_secret, envoy_secret) + envoy = TLSEnvoy( + openshift, + authorino, + blame("backend"), + label, + backend, + testconfig["envoy"]["image"], + authorino_secret, + envoy_ca_secret, + envoy_secret, + ) request.addfinalizer(envoy.delete) envoy.commit() return envoy diff --git a/testsuite/tests/kuadrant/authorino/operator/tls/mtls/conftest.py b/testsuite/tests/kuadrant/authorino/operator/tls/mtls/conftest.py index 1bc385fc..f65d0d2a 100644 --- a/testsuite/tests/kuadrant/authorino/operator/tls/mtls/conftest.py +++ b/testsuite/tests/kuadrant/authorino/operator/tls/mtls/conftest.py @@ -21,25 +21,29 @@ def authorization(authorization, blame, selector_params, cert_attributes): def certificates(cfssl, authorino_domain, wildcard_domain, cert_attributes, cert_attributes_other): """Certificate hierarchy used for the mTLS tests""" chain = { - "envoy_ca": CertInfo(children={ - "envoy_cert": None, - "valid_cert": CertInfo(names=[cert_attributes]), - "custom_cert": CertInfo(names=[cert_attributes_other]), - "intermediate_ca": CertInfo(children={ - "intermediate_valid_cert": CertInfo(names=[cert_attributes]), - "intermediate_custom_cert": CertInfo(names=[cert_attributes_other]) - }), - "intermediate_ca_unlabeled": CertInfo(children={ - "intermediate_cert_unlabeled": CertInfo(names=[cert_attributes]) - }) - }), - "authorino_ca": CertInfo(children={ - "authorino_cert": CertInfo(hosts=authorino_domain), - }), - "invalid_ca": CertInfo(children={ - "invalid_cert": None - }), - "self_signed_cert": None + "envoy_ca": CertInfo( + children={ + "envoy_cert": None, + "valid_cert": CertInfo(names=[cert_attributes]), + "custom_cert": CertInfo(names=[cert_attributes_other]), + "intermediate_ca": CertInfo( + children={ + "intermediate_valid_cert": CertInfo(names=[cert_attributes]), + "intermediate_custom_cert": CertInfo(names=[cert_attributes_other]), + } + ), + "intermediate_ca_unlabeled": CertInfo( + children={"intermediate_cert_unlabeled": CertInfo(names=[cert_attributes])} + ), + } + ), + "authorino_ca": CertInfo( + children={ + "authorino_cert": CertInfo(hosts=authorino_domain), + } + ), + "invalid_ca": CertInfo(children={"invalid_cert": None}), + "self_signed_cert": None, } return cert_builder(cfssl, chain, wildcard_domain) diff --git a/testsuite/tests/kuadrant/authorino/operator/tls/mtls/test_mtls_identity.py b/testsuite/tests/kuadrant/authorino/operator/tls/mtls/test_mtls_identity.py index 44214216..38c8afc3 100644 --- a/testsuite/tests/kuadrant/authorino/operator/tls/mtls/test_mtls_identity.py +++ b/testsuite/tests/kuadrant/authorino/operator/tls/mtls/test_mtls_identity.py @@ -10,12 +10,17 @@ def test_mtls_success(envoy_authority, valid_cert, envoy): assert response.status_code == 200 -@pytest.mark.parametrize("cert_authority, certificate, err, err_match", [ - pytest.param("envoy_authority", "self_signed_cert", ReadError, "unknown ca", id="Self-Signed Certificate"), - pytest.param("envoy_authority", "invalid_cert", ReadError, "unknown ca", id="Invalid certificate"), - pytest.param("envoy_authority", None, ReadError, "certificate required", id="Without certificate"), - pytest.param("invalid_authority", "valid_cert", ConnectError, "certificate verify failed", id="Unknown authority"), -]) +@pytest.mark.parametrize( + "cert_authority, certificate, err, err_match", + [ + pytest.param("envoy_authority", "self_signed_cert", ReadError, "unknown ca", id="Self-Signed Certificate"), + pytest.param("envoy_authority", "invalid_cert", ReadError, "unknown ca", id="Invalid certificate"), + pytest.param("envoy_authority", None, ReadError, "certificate required", id="Without certificate"), + pytest.param( + "invalid_authority", "valid_cert", ConnectError, "certificate verify failed", id="Unknown authority" + ), + ], +) def test_mtls_fail(request, cert_authority, certificate, err, err_match: str, envoy): """Test failed mtls verification""" ca = request.getfixturevalue(cert_authority) diff --git a/testsuite/tests/kuadrant/authorino/operator/tls/test_webhook.py b/testsuite/tests/kuadrant/authorino/operator/tls/test_webhook.py index e233305f..7b33de94 100644 --- a/testsuite/tests/kuadrant/authorino/operator/tls/test_webhook.py +++ b/testsuite/tests/kuadrant/authorino/operator/tls/test_webhook.py @@ -27,7 +27,7 @@ @pytest.fixture(scope="session") def specific_authorino_name(blame): """Define specific name for authorino which matches with name in authorino certificate""" - return blame('authorino') + return blame("authorino") @pytest.fixture(scope="session") @@ -45,16 +45,13 @@ def certificates(cfssl, authorino_domain, wildcard_domain): Authorino certificate has *hosts* set to *authorino_domain* value. """ chain = { - "envoy_ca": CertInfo(children={ - "envoy_cert": None, - "valid_cert": None - }), - "authorino_ca": CertInfo(children={ - "authorino_cert": CertInfo(hosts=authorino_domain), - }), - "invalid_ca": CertInfo(children={ - "invalid_cert": None - }) + "envoy_ca": CertInfo(children={"envoy_cert": None, "valid_cert": None}), + "authorino_ca": CertInfo( + children={ + "authorino_cert": CertInfo(hosts=authorino_domain), + } + ), + "invalid_ca": CertInfo(children={"invalid_cert": None}), } return cert_builder(cfssl, chain, wildcard_domain) @@ -62,7 +59,7 @@ def certificates(cfssl, authorino_domain, wildcard_domain): @pytest.fixture(scope="module") def authorino_parameters(authorino_parameters, specific_authorino_name): """Setup TLS with specific name for authorino.""" - authorino_parameters['name'] = specific_authorino_name + authorino_parameters["name"] = specific_authorino_name return authorino_parameters @@ -77,78 +74,75 @@ def authorization(authorization, openshift, module_label, authorino_domain) -> A # get user info from admission webhook authorization.identity.remove_all() - authorization.identity.kubernetes('k8s-userinfo', - 'context.request.http.body.@fromstr|request.userInfo') + authorization.identity.kubernetes("k8s-userinfo", "context.request.http.body.@fromstr|request.userInfo") # add OPA policy to process admission webhook request - authorization.authorization.opa_policy('features', OPA_POLICY) + authorization.authorization.opa_policy("features", OPA_POLICY) user_value = Value(jsonPath="auth.identity.username") - when = [Rule("auth.authorization.features.allow", "eq", "true"), - Rule("auth.authorization.features.verb", "eq", "CREATE")] + when = [ + Rule("auth.authorization.features.allow", "eq", "true"), + Rule("auth.authorization.features.verb", "eq", "CREATE"), + ] kube_attrs = { - 'namespace': {'value': openshift.project}, - 'group': {'value': 'networking.k8s.io'}, - 'resources': {'value': 'Ingress'}, - 'verb': {'value': 'create'} - } + "namespace": {"value": openshift.project}, + "group": {"value": "networking.k8s.io"}, + "resources": {"value": "Ingress"}, + "verb": {"value": "create"}, + } # add response for admission webhook for creating Ingress - authorization.authorization.kubernetes('ingress-authn-k8s-binding-create', - user_value, kube_attrs, when=when, priority=1) - - when = [Rule("auth.authorization.features.allow", "eq", "true"), - Rule("auth.authorization.features.verb", "eq", "DELETE")] + authorization.authorization.kubernetes( + "ingress-authn-k8s-binding-create", user_value, kube_attrs, when=when, priority=1 + ) + + when = [ + Rule("auth.authorization.features.allow", "eq", "true"), + Rule("auth.authorization.features.verb", "eq", "DELETE"), + ] kube_attrs = { - 'namespace': {'value': openshift.project}, - 'group': {'value': 'networking.k8s.io'}, - 'resources': {'value': 'Ingress'}, - 'verb': {'value': 'delete'} - } + "namespace": {"value": openshift.project}, + "group": {"value": "networking.k8s.io"}, + "resources": {"value": "Ingress"}, + "verb": {"value": "delete"}, + } # add response for admission webhook for deleting Ingress - authorization.authorization.kubernetes('ingress-authn-k8s-binding-delete', - user_value, kube_attrs, when=when, priority=1) + authorization.authorization.kubernetes( + "ingress-authn-k8s-binding-delete", user_value, kube_attrs, when=when, priority=1 + ) return authorization @pytest.fixture(scope="module") def validating_webhook(openshift, authorino_domain, certificates, blame): """Create validating webhook.""" - name = blame('check-ingress') + '.authorino.kuadrant.io' - service_name = authorino_domain.split('.')[0] + name = blame("check-ingress") + ".authorino.kuadrant.io" + service_name = authorino_domain.split(".")[0] - cert_string = base64.b64encode(certificates['authorino_ca'].certificate.encode('ascii')).decode('ascii') + cert_string = base64.b64encode(certificates["authorino_ca"].certificate.encode("ascii")).decode("ascii") model: Dict[str, Any] = { - 'apiVersion': 'admissionregistration.k8s.io/v1', - 'kind': 'ValidatingWebhookConfiguration', - 'metadata': { - 'name': name, - 'namespace': openshift.project - }, - 'webhooks': [ + "apiVersion": "admissionregistration.k8s.io/v1", + "kind": "ValidatingWebhookConfiguration", + "metadata": {"name": name, "namespace": openshift.project}, + "webhooks": [ { - 'name': name, - 'clientConfig': { - 'service': { - 'namespace': openshift.project, - 'name': service_name, - 'port': 5001, - 'path': '/check' - }, - 'caBundle': cert_string, + "name": name, + "clientConfig": { + "service": {"namespace": openshift.project, "name": service_name, "port": 5001, "path": "/check"}, + "caBundle": cert_string, }, - 'rules': [ + "rules": [ { - 'apiGroups': ['networking.k8s.io'], - 'apiVersions': ['v1'], - 'resources': ['ingresses'], - 'operations': ['CREATE', 'UPDATE', 'DELETE'], - 'scope': '*', + "apiGroups": ["networking.k8s.io"], + "apiVersions": ["v1"], + "resources": ["ingresses"], + "operations": ["CREATE", "UPDATE", "DELETE"], + "scope": "*", } ], - 'sideEffects': 'None', - 'admissionReviewVersions': ['v1'] + "sideEffects": "None", + "admissionReviewVersions": ["v1"], } - ] + ], } webhook = None @@ -159,19 +153,17 @@ def validating_webhook(openshift, authorino_domain, certificates, blame): # pylint: disable=unused-argument -def test_authorized_via_http(authorization, openshift, authorino, authorino_domain, - validating_webhook, blame): +def test_authorized_via_http(authorization, openshift, authorino, authorino_domain, validating_webhook, blame): """Test raw http authorization via webhooks.""" - ingress = Ingress.create_instance(openshift, blame('minimal-ingress'), rules=[{}]) + ingress = Ingress.create_instance(openshift, blame("minimal-ingress"), rules=[{}]) ingress.commit() assert ingress.model.metadata.creationTimestamp ingress.delete() # pylint: disable=unused-argument -def test_unauthorized_via_http(authorization, openshift, authorino, authorino_domain, - validating_webhook, blame): +def test_unauthorized_via_http(authorization, openshift, authorino, authorino_domain, validating_webhook, blame): """Test raw http authorization via webhooks but for unauthorized object.""" - ingress = Ingress.create_instance(openshift, blame('minimal-ingress'), rules=[{}, {}]) + ingress = Ingress.create_instance(openshift, blame("minimal-ingress"), rules=[{}, {}]) with pytest.raises(OpenShiftPythonException, match="Unauthorized"): ingress.commit() diff --git a/testsuite/tests/kuadrant/authorino/performance/conftest.py b/testsuite/tests/kuadrant/authorino/performance/conftest.py index 5370b397..61668930 100644 --- a/testsuite/tests/kuadrant/authorino/performance/conftest.py +++ b/testsuite/tests/kuadrant/authorino/performance/conftest.py @@ -9,16 +9,16 @@ from testsuite.httpx.auth import HttpxOidcClientAuth -@pytest.fixture(scope='session') +@pytest.fixture(scope="session") def hyperfoil_client(testconfig): """Hyperfoil client""" try: - return HyperfoilClient(testconfig['hyperfoil']['url']) + return HyperfoilClient(testconfig["hyperfoil"]["url"]) except (KeyError, ValidationError) as exc: return pytest.skip(f"Hyperfoil configuration item is missing: {exc}") -@pytest.fixture(scope='module') +@pytest.fixture(scope="module") def hyperfoil_utils(hyperfoil_client, template, request): """Init of hyperfoil utils""" utils = HyperfoilUtils(hyperfoil_client, template) @@ -33,7 +33,7 @@ def rhsso_auth(rhsso): return HttpxOidcClientAuth(rhsso.get_token) -@pytest.fixture(scope='module') +@pytest.fixture(scope="module") def number_of_agents(): """Number of spawned HyperFoil agents""" return 1 diff --git a/testsuite/tests/kuadrant/authorino/performance/test_perf_basic.py b/testsuite/tests/kuadrant/authorino/performance/test_perf_basic.py index ad4a6597..3b1cd191 100644 --- a/testsuite/tests/kuadrant/authorino/performance/test_perf_basic.py +++ b/testsuite/tests/kuadrant/authorino/performance/test_perf_basic.py @@ -19,20 +19,21 @@ pytestmark = [pytest.mark.performance] -@pytest.fixture(scope='module') +@pytest.fixture(scope="module") def number_of_agents(): """Number of spawned HyperFoil agents""" return AGENTS -@pytest.fixture(scope='module') +@pytest.fixture(scope="module") def template(): """Path to template""" - return resources.files("testsuite.tests.kuadrant.authorino.performance.templates")\ - .joinpath('template_perf_basic_query_rhsso.hf.yaml') + return resources.files("testsuite.tests.kuadrant.authorino.performance.templates").joinpath( + "template_perf_basic_query_rhsso.hf.yaml" + ) -@pytest.fixture(scope='module') +@pytest.fixture(scope="module") def hyperfoil_utils(hyperfoil_client, template, request): """Init of hyperfoil utils""" utils = HyperfoilUtils(hyperfoil_client, template) @@ -41,16 +42,16 @@ def hyperfoil_utils(hyperfoil_client, template, request): return utils -@pytest.fixture(scope='module') +@pytest.fixture(scope="module") def setup_benchmark_rhsso(hyperfoil_utils, client, rhsso, number_of_agents): """Setup of benchmark. It will add necessary host connections, csv data and files.""" # currently number of shared connections is set as a placeholder and later should be determined by test results - url_pool = [{'url': rhsso.server_url, 'connections': 100}, {'url': str(client.base_url), 'connections': 20}] + url_pool = [{"url": rhsso.server_url, "connections": 100}, {"url": str(client.base_url), "connections": 20}] for url in url_pool: - complete_url = prepare_url(urlparse(url['url'])) - hyperfoil_utils.add_host(complete_url._replace(path="").geturl(), shared_connections=url['connections']) + complete_url = prepare_url(urlparse(url["url"])) + hyperfoil_utils.add_host(complete_url._replace(path="").geturl(), shared_connections=url["connections"]) - hyperfoil_utils.add_rhsso_auth_token(rhsso, prepare_url(urlparse(str(client.base_url))).netloc, 'rhsso_auth.csv') + hyperfoil_utils.add_rhsso_auth_token(rhsso, prepare_url(urlparse(str(client.base_url))).netloc, "rhsso_auth.csv") hyperfoil_utils.add_file(HyperfoilUtils.message_1kb) hyperfoil_utils.add_shared_template(number_of_agents) return hyperfoil_utils @@ -64,9 +65,9 @@ def wait_run(run): def test_basic_perf_rhsso(client, rhsso_auth, setup_benchmark_rhsso): """ - Test checks that authorino is set up correctly. - Runs the created benchmark. - Asserts it was successful. + Test checks that authorino is set up correctly. + Runs the created benchmark. + Asserts it was successful. """ get_response = client.get("/get", auth=rhsso_auth) post_response = client.post("/post", auth=rhsso_auth) @@ -81,6 +82,6 @@ def test_basic_perf_rhsso(client, rhsso_auth, setup_benchmark_rhsso): stats = run.all_stats() assert stats - assert stats.get('info', {}).get('errors') == [] - assert stats.get('failures') == [] - assert stats.get('stats', []) != [] + assert stats.get("info", {}).get("errors") == [] + assert stats.get("failures") == [] + assert stats.get("stats", []) != [] diff --git a/testsuite/tests/kuadrant/authorino/response/test_auth_json.py b/testsuite/tests/kuadrant/authorino/response/test_auth_json.py index 65941878..a820ceb9 100644 --- a/testsuite/tests/kuadrant/authorino/response/test_auth_json.py +++ b/testsuite/tests/kuadrant/authorino/response/test_auth_json.py @@ -17,10 +17,7 @@ def non_existing(): return None -@pytest.fixture(scope="module", params=[ - ("auth.identity.iss", "issuer"), - ("auth.non_existing.value", "non_existing") -]) +@pytest.fixture(scope="module", params=[("auth.identity.iss", "issuer"), ("auth.non_existing.value", "non_existing")]) def path_and_value(request): """Returns authJSON path and expected value""" return request.param[0], request.getfixturevalue(request.param[1]) @@ -30,17 +27,7 @@ def path_and_value(request): def responses(path_and_value): """Returns response to be added to the AuthConfig""" path, _ = path_and_value - return [{"name": "header", - "json": { - "properties": [ - { - "name": "anything", - "valueFrom": { - "authJSON": path - } - } - ] - }}] + return [{"name": "header", "json": {"properties": [{"name": "anything", "valueFrom": {"authJSON": path}}]}}] def test_auth_json_path(auth, client, path_and_value): diff --git a/testsuite/tests/kuadrant/authorino/response/test_multiple_responses.py b/testsuite/tests/kuadrant/authorino/response/test_multiple_responses.py index 5e7d5dfb..59fdfd74 100644 --- a/testsuite/tests/kuadrant/authorino/response/test_multiple_responses.py +++ b/testsuite/tests/kuadrant/authorino/response/test_multiple_responses.py @@ -7,19 +7,10 @@ @pytest.fixture(scope="module") def responses(): """Returns response to be added to the AuthConfig""" - return [{"name": "Header", - "json": { - "properties": [ - {"name": "anything", "value": "one"} - ] - }}, - {"name": "X-Test", - "json": { - "properties": [ - {"name": "anything", "value": "two"} - ] - }}, - ] + return [ + {"name": "Header", "json": {"properties": [{"name": "anything", "value": "one"}]}}, + {"name": "X-Test", "json": {"properties": [{"name": "anything", "value": "two"}]}}, + ] def test_multiple_responses(auth, client): diff --git a/testsuite/tests/kuadrant/authorino/response/test_simple_response.py b/testsuite/tests/kuadrant/authorino/response/test_simple_response.py index 734fb9eb..ec2fb33f 100644 --- a/testsuite/tests/kuadrant/authorino/response/test_simple_response.py +++ b/testsuite/tests/kuadrant/authorino/response/test_simple_response.py @@ -7,12 +7,7 @@ @pytest.fixture(scope="module") def responses(): """Returns response to be added to the AuthConfig""" - return [{"name": "header", - "json": { - "properties": [ - {"name": "anything", "value": "one"} - ] - }}] + return [{"name": "header", "json": {"properties": [{"name": "anything", "value": "one"}]}}] def test_simple_response_with(auth, client): diff --git a/testsuite/tests/kuadrant/authorino/response/test_wrapper_key.py b/testsuite/tests/kuadrant/authorino/response/test_wrapper_key.py index 9bf45dde..2224a829 100644 --- a/testsuite/tests/kuadrant/authorino/response/test_wrapper_key.py +++ b/testsuite/tests/kuadrant/authorino/response/test_wrapper_key.py @@ -4,11 +4,7 @@ import pytest -@pytest.fixture(scope="module", params=[ - "123456789", - "standardCharacters", - "specialcharacters/+*-." -]) +@pytest.fixture(scope="module", params=["123456789", "standardCharacters", "specialcharacters/+*-."]) def header_name(request): """Name of the headers""" return request.param @@ -17,13 +13,9 @@ def header_name(request): @pytest.fixture(scope="module") def responses(header_name): """Returns response to be added to the AuthConfig""" - return [{"name": "header", - "wrapperKey": header_name, - "json": { - "properties": [ - {"name": "anything", "value": "one"} - ] - }}] + return [ + {"name": "header", "wrapperKey": header_name, "json": {"properties": [{"name": "anything", "value": "one"}]}} + ] def test_wrapper_key_with(auth, client, header_name): diff --git a/testsuite/tests/kuadrant/authorino/test_redirect.py b/testsuite/tests/kuadrant/authorino/test_redirect.py index 547eb8d8..56539c82 100644 --- a/testsuite/tests/kuadrant/authorino/test_redirect.py +++ b/testsuite/tests/kuadrant/authorino/test_redirect.py @@ -4,7 +4,7 @@ import pytest STATUS_CODE = 302 -REDIRECT_URL = 'http://anything.inavlid?redirect_to=' +REDIRECT_URL = "http://anything.inavlid?redirect_to=" @pytest.fixture(scope="module") diff --git a/testsuite/tests/kuadrant/conftest.py b/testsuite/tests/kuadrant/conftest.py index 10f0dfe4..1bf314e8 100644 --- a/testsuite/tests/kuadrant/conftest.py +++ b/testsuite/tests/kuadrant/conftest.py @@ -38,8 +38,9 @@ def authorization_name(blame): def authorization(authorino, kuadrant, envoy, authorization_name, openshift, module_label): """Authorization object (In case of Kuadrant AuthPolicy)""" if kuadrant: - policy = AuthPolicy.create_instance(openshift, authorization_name, - envoy.route, labels={"testRun": module_label}) + policy = AuthPolicy.create_instance( + openshift, authorization_name, envoy.route, labels={"testRun": module_label} + ) return policy return None diff --git a/testsuite/utils.py b/testsuite/utils.py index 82324f77..d4ff561c 100644 --- a/testsuite/utils.py +++ b/testsuite/utils.py @@ -11,6 +11,7 @@ class ContentType(enum.Enum): """Content-type options for expectation headers""" + PLAIN_TEXT = "plain/text" APPLICATION_JSON = "application/json" @@ -30,8 +31,8 @@ def randomize(name, tail=5): def _whoami(): """Returns username""" - if 'tester' in settings: - return settings['tester'] + if "tester" in settings: + return settings["tester"] try: return os.getlogin() @@ -41,8 +42,9 @@ def _whoami(): return str(os.getuid()) -def cert_builder(cfssl: CFSSLClient, chain: dict, hosts: Union[str, Collection[str]] = None, - parent: Certificate = None) -> Dict[str, Certificate]: +def cert_builder( + cfssl: CFSSLClient, chain: dict, hosts: Union[str, Collection[str]] = None, parent: Certificate = None +) -> Dict[str, Certificate]: """ Recursively create certificates based on their given CertInfo. If CertInfo has children or is marked as CA, it will be generated as a Certificate Authority, @@ -65,11 +67,9 @@ def cert_builder(cfssl: CFSSLClient, chain: dict, hosts: Union[str, Collection[s parsed_hosts = [parsed_hosts] # type: ignore if info.ca or info.children: - cert = cfssl.create_authority(name, names=info.names, - hosts=parsed_hosts, certificate_authority=parent) + cert = cfssl.create_authority(name, names=info.names, hosts=parsed_hosts, certificate_authority=parent) else: - cert = cfssl.create(name, names=info.names, - hosts=parsed_hosts, certificate_authority=parent) + cert = cfssl.create(name, names=info.names, hosts=parsed_hosts, certificate_authority=parent) if info.children is not None: result.update(cert_builder(cfssl, info.children, parsed_hosts, cert)) @@ -79,4 +79,4 @@ def cert_builder(cfssl: CFSSLClient, chain: dict, hosts: Union[str, Collection[s def rego_allow_header(key, value): """Rego query that allows all requests that contain specific header with`key` and `value`""" - return f"allow {{ input.context.request.http.headers.{key} == \"{value}\" }}" + return f'allow {{ input.context.request.http.headers.{key} == "{value}" }}'