|
| 1 | +import logging |
| 2 | + |
| 3 | +from locust import FastHttpUser |
| 4 | + |
| 5 | +from .auth_settings import DeploymentAuth, OsparcAuth |
| 6 | + |
| 7 | +_logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | + |
| 10 | +class OsparcUserBase(FastHttpUser): |
| 11 | + """ |
| 12 | + Base class for Locust users that provides common functionality. |
| 13 | + This class can be extended by specific user classes to implement |
| 14 | + different behaviors or tasks. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__(self, *args, **kwargs): |
| 18 | + super().__init__(*args, **kwargs) |
| 19 | + self.deploy_auth = DeploymentAuth() |
| 20 | + _logger.debug("Using deployment auth: %s", self.deploy_auth) |
| 21 | + |
| 22 | + |
| 23 | +class OsparcWebUserBase(OsparcUserBase): |
| 24 | + """ |
| 25 | + Base class for web users in Locust that provides common functionality. |
| 26 | + This class can be extended by specific web user classes to implement |
| 27 | + different behaviors or tasks. |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__(self, *args, **kwargs): |
| 31 | + super().__init__(*args, **kwargs) |
| 32 | + if self.environment.parsed_options.requires_login: |
| 33 | + self.osparc_auth = OsparcAuth() |
| 34 | + _logger.debug("Using OsparcAuth for login: %s", self.osparc_auth) |
| 35 | + |
| 36 | + def on_start(self) -> None: |
| 37 | + """ |
| 38 | + Called when a web user starts. Can be overridden by subclasses |
| 39 | + to implement custom startup behavior, such as logging in. |
| 40 | + """ |
| 41 | + if self.environment.parsed_options.requires_login: |
| 42 | + self._login() |
| 43 | + |
| 44 | + def on_stop(self) -> None: |
| 45 | + """ |
| 46 | + Called when a web user stops. Can be overridden by subclasses |
| 47 | + to implement custom shutdown behavior, such as logging out. |
| 48 | + """ |
| 49 | + if self.environment.parsed_options.requires_login: |
| 50 | + self._logout() |
| 51 | + |
| 52 | + def _login(self) -> None: |
| 53 | + # Implement login logic here |
| 54 | + logging.info( |
| 55 | + "Loggin in user with email: %s", |
| 56 | + { |
| 57 | + "email": self.osparc_auth.OSPARC_USER_NAME, |
| 58 | + "password": self.osparc_auth.OSPARC_PASSWORD.get_secret_value(), |
| 59 | + }, |
| 60 | + ) |
| 61 | + response = self.client.post( |
| 62 | + "/v0/auth/login", |
| 63 | + json={ |
| 64 | + "email": self.osparc_auth.OSPARC_USER_NAME, |
| 65 | + "password": self.osparc_auth.OSPARC_PASSWORD.get_secret_value(), |
| 66 | + }, |
| 67 | + auth=self.deploy_auth.to_auth(), |
| 68 | + ) |
| 69 | + response.raise_for_status() |
| 70 | + logging.info("Logged in user with email: %s", self.osparc_auth) |
| 71 | + |
| 72 | + def _logout(self) -> None: |
| 73 | + # Implement logout logic here |
| 74 | + self.client.post("/v0/auth/logout", auth=self.deploy_auth.to_auth()) |
| 75 | + logging.info("Logged out user with email: %s", self.osparc_auth) |
0 commit comments