Terarea  2
The automation project
Loading...
Searching...
No Matches
constants.py
Go to the documentation of this file.
1"""_summary_
2This is the file in charge of storing the variable constants
3
4Raises:
5 ValueError: _description_
6 KeyError: _description_
7 KeyError: _description_
8 RuntimeError: _description_
9
10Returns:
11 _type_: _description_
12"""
13import json
14from os import getpid
15from uuid import uuid4
16from random import randint
17from typing import Dict, Any
18from string import ascii_letters, digits
19
20import toml
21import dotenv
22from display_tty import IDISP
23
24
25# Variable that will enable/disable the debug logging of the functions
26DEBUG = False
27DEBUG = True
28IDISP.debug = DEBUG
29
30IDISP.logger.name = "Constants_tests"
31
32DB_PORT = 3307
33DB_HOST = "127.0.0.1"
34DB_USER = "root"
35DB_PASSWORD = ""
36DB_DATABASE = "terarea"
37
38SERVER_HOST = "0.0.0.0"
39QUERY_HOST = "http://127.0.0.1"
40PORT = 6000
41
42# For the client
43QUERY_DELAY = 2
44
45SUCCESS = 0
46ERROR = 1
47
48APP_NAME = "Area - Testing"
49
50
51# Creating a string that is void of injection material
52SAFE_STRING = ascii_letters+digits
53SAFE_STRING_LENGTH = len(SAFE_STRING)
54
55
56def get_cache_busting() -> str:
57 """_summary_
58 This function is in charge of generating a cache busting string.
59 This is done in order to avoid creating already existing accounts
60
61 Returns:
62 str: _description_
63 """
64 cache: str = ""
65 length: int = 20
66 iterations: int = 0
67
68 cache += "startCacheBusting"
69 cache += str(getpid())
70 cache += str(uuid4()).replace("-", "")
71 while iterations < length:
72 cache += SAFE_STRING[
73 randint(
74 0, SAFE_STRING_LENGTH - 1
75 )
76 ]
77 iterations += 1
78 cache += str(getpid())
79 cache += "endCacheBusting"
80 return cache
81
82
83def _get_env_node(env: Dict[str, Any], key: str, default: str) -> Any:
84 """_summary_
85 Load the variable from the environement.
86 Otherwise, use the default value provided.
87 Args:
88 key (_type_): _description_
89 default (_type_): _description_
90
91 Returns:
92 Any: _description_
93 """
94 node = env.get(key)
95 if node is None:
96 return default
97 return node
98
99
100def _get_environement_variable(environement: dotenv, variable_name: str) -> str:
101 """_summary_
102 Get the content of an environement variable.
103
104 Args:
105 variable_name (str): _description_
106
107 Returns:
108 str: _description_: the value of that variable, otherwise an exception is raised.
109 """
110 data = environement.get(variable_name)
111 if data is None:
112 raise ValueError(
113 f"Variable {variable_name} not found in the environement"
114 )
115 return data
116
117
118def _get_toml_variable(toml_conf: dict, section: str, key: str, default=None) -> str:
119 """
120 Get the value of a configuration variable from the TOML file.
121
122 Args:
123 toml_conf (dict): The loaded TOML configuration as a dictionary.
124 section (str): The section of the TOML file to search in.
125 key (str): The key within the section to fetch.
126 default: The default value to return if the key is not found. Defaults to None.
127
128 Returns:
129 str: The value of the configuration variable, or the default value if the key is not found.
130
131 Raises:
132 KeyError: If the section is not found in the TOML configuration.
133 """
134 try:
135 keys = section.split('.')
136 current_section = toml_conf
137
138 for k in keys:
139 if k in current_section:
140 current_section = current_section[k]
141 else:
142 raise KeyError(
143 f"Section '{section}' not found in TOML configuration."
144 )
145
146 if key in current_section:
147 return current_section[key]
148 if default is None:
149 msg = f"Key '{key}' not found in section '{section}' "
150 msg += "of TOML configuration."
151 raise KeyError(msg)
152 return default
153
154 except KeyError as err:
155 IDISP.log_warning(f"{err}", "_get_toml_variable")
156 return default
157
158
159def _password_generator(length: int = 20, encapsulation_node: str = "password") -> str:
160 """_summary_
161 This is a function in charge of generating a password for on the fly accounts.
162
163 Args:
164 length (int, optional): _description_. Defaults to 20.
165
166 Returns:
167 str: _description_
168 """
169 password = ""
170
171 password += str(encapsulation_node)
172 password += "_"
173
174 iterations = 0
175 while iterations < length:
176 password += SAFE_STRING[
177 randint(
178 0,
179 SAFE_STRING_LENGTH - 1
180 )
181 ]
182 iterations += 1
183 password += "_"
184 password += str(encapsulation_node)
185 return password
186
187
188def are_json_responses_identical(json_response1: Dict[str, Any], json_response2: Dict[str, Any], test_name: str = "are_json_responses_identical") -> bool:
189 """_summary_
190 This function is in charge of comparing two json responses to see if they are identical.
191
192 Args:
193 json_response1 (Dict[str,Any]): _description_: The first json response you wish to compare
194 json_response2 (Dict[str,Any]): _description_: The json response that the first response will be compared against
195
196 Returns:
197 bool: _description_: Returns True if they are identical, False otherwise.
198 """
199 try:
200 json_response1_str = json.dumps(json_response1)
201 except TypeError:
202 IDISP.log_warning(
203 "Failed to convert json_response1 to json format", test_name
204 )
205 return False
206 try:
207 json_response2_str = json.dumps(json_response2)
208 except TypeError:
209 IDISP.log_warning(
210 "Failed to convert json_response2 to json format", test_name
211 )
212 return False
213 if json_response1_str == json_response2_str:
214 return True
215 msg = "The content of json_response1 is different from json_response2:\n"
216 msg += f"- json_response1_str = {json_response1_str}\n"
217 msg += f"- json_response2_str = {json_response2_str}\n"
218 IDISP.log_warning(msg, test_name)
219 return False
220
221
222CACHE_BUSTER = get_cache_busting()
223CACHE_BUSTER_ADMIN = f"admin_{get_cache_busting()}_admin"
224
225TEST_ENV = ".env"
226try:
227 dotenv.load_dotenv(TEST_ENV)
228 ENV = dict(dotenv.dotenv_values())
229
230 DB_PORT = int(_get_env_node(ENV, "DB_PORT", DB_PORT))
231 DB_HOST = _get_env_node(ENV, "DB_HOST", DB_HOST)
232 DB_USER = _get_env_node(ENV, "DB_USER", DB_USER)
233 DB_PASSWORD = _get_environement_variable(ENV, "DB_PASSWORD")
234 DB_DATABASE = _get_env_node(ENV, "DB_DATABASE", DB_DATABASE)
235 MINIO_HOST = _get_env_node(ENV, "MINIO_HOST", "minio")
236 MINIO_PORT = int(_get_env_node(ENV, "MINIO_PORT", 9000))
237 MINIO_ROOT_USER = _get_env_node(ENV, "MINIO_ROOT_USER", "root")
238 MINIO_ROOT_PASSWORD = _get_environement_variable(
239 ENV, "MINIO_ROOT_PASSWORD"
240 )
241
242
243except Exception as e:
244 raise RuntimeError(
245 f"Environement {TEST_ENV} failed to load, aborting"
246 ) from e
247
248TOML_CONF = toml.load("config.toml")
249
250# |- Toml status codes
251SUCCESS = int(_get_toml_variable(
252 TOML_CONF, "Status_codes", "success", SUCCESS
253))
254ERROR = int(_get_toml_variable(TOML_CONF, "Status_codes", "error", ERROR))
255# |- Toml test configuration
256SERVER_HOST = str(_get_toml_variable(
257 TOML_CONF, "Test.host", "server", SERVER_HOST
258))
259QUERY_HOST = str(_get_toml_variable(
260 TOML_CONF, "Test.host", "client", QUERY_HOST
261))
262PORT = int(_get_toml_variable(
263 TOML_CONF, "Test.host", "port", PORT
264))
265
266# Endpoints to test the server
267PATH_GET_HOME = "/"
268PATH_GET_API_HOME = "/api/v1/"
269PATH_PUT_REGISTER = "/api/v1/register"
270PATH_POST_LOGIN = "/api/v1/login"
271PATH_PATCH_USER = "/api/v1/user"
272PATH_PUT_USER = "/api/v1/user"
273PATH_DELETE_USER = "/api/v1/user"
274PATH_GET_USER = "/api/v1/user"
275PATH_GET_USER_ID = "/api/v1/user_id"
276PATH_POST_LOGOUT = "/api/v1/logout"
277
278# Token key references
279LAMBDA_USER_TOKEN_KEY: str = "lambda_user"
280ADMIN_USER_TOKEN_KEY: str = "admin_user"
281TOKEN_AUTH_ID_STR: str = "Authorization"
282PRETTY_TOKEN_KEY: str = "token_header"
283RAW_TOKEN_KEY: str = "token_key"
284
285# User data (test input)
286USER_DATA_EMAIL = f"some_email_{CACHE_BUSTER}@company.example"
287USER_DATA_USERNAME = USER_DATA_EMAIL.split("@")[0]
288USER_DATA_PASSWORD = _password_generator(
289 length=20, encapsulation_node="some_user"
290)
291USER_DATA_METHOD = "local"
292USER_DATA_FAVICON = "NULL"
293USER_DATA_ADMIN = "0"
294USER_DATA_TOKEN = f"some_token_{CACHE_BUSTER}_some_token"
295USER_DATA_TOKEN_LIFESPAN = 3600 # seconds
296
297# User data rebind
298USER_DATA_EMAIL_REBIND = f"some_email_{CACHE_BUSTER}_rebind@company.example"
299USER_DATA_USERNAME_REBIND = USER_DATA_EMAIL_REBIND.split("@")[0]
300USER_DATA_PASSWORD_REBIND = _password_generator(
301 length=20, encapsulation_node="some_user_rebind"
302)
303
304# User data patch
305USER_DATA_EMAIL_PATCH = f"some_email_{CACHE_BUSTER}_patch@company.com"
306USER_DATA_USERNAME_PATCH = USER_DATA_EMAIL_PATCH.split("@")[0]
307USER_DATA_PASSWORD_PATCH = _password_generator(
308 length=20, encapsulation_node="some_user_patch"
309)
310
311# Admin data (test input)
312ADMIN_DATA_EMAIL = f"some_email_{CACHE_BUSTER_ADMIN}@company.example"
313ADMIN_DATA_USERNAME = ADMIN_DATA_EMAIL.split("@")[0]
314ADMIN_DATA_PASSWORD = _password_generator(
315 length=20, encapsulation_node="some_admin"
316)
317ADMIN_DATA_METHOD = "local"
318ADMIN_DATA_FAVICON = "NULL"
319ADMIN_DATA_ADMIN = "1"
320ADMIN_DATA_TOKEN = f"some_token_{CACHE_BUSTER_ADMIN}_some_token"
321ADMIN_DATA_TOKEN_LIFESPAN = 3600 # seconds
322
323# Admin data rebind
324ADMIN_DATA_EMAIL_REBIND = f"some_email_{CACHE_BUSTER_ADMIN}_"
325ADMIN_DATA_EMAIL_REBIND += "rebind@company.example"
326ADMIN_DATA_USERNAME_REBIND = ADMIN_DATA_EMAIL_REBIND.split("@")[0]
327ADMIN_DATA_PASSWORD_REBIND = _password_generator(
328 length=20, encapsulation_node="some_admin_rebind"
329)
330
331# Admin data patch
332ADMIN_DATA_EMAIL_PATCH = f"some_email_{CACHE_BUSTER_ADMIN}_patch@company.com"
333ADMIN_DATA_USERNAME_PATCH = ADMIN_DATA_EMAIL_PATCH.split("@")[0]
334ADMIN_DATA_PASSWORD_PATCH = _password_generator(
335 length=20, encapsulation_node="some_admin_patch"
336)
337
338# User dictionnary keys
339UNODE_EMAIL_KEY = "email"
340UNODE_PASSWORD_KEY = "password"
341UNODE_USERNAME_KEY = "username"
342UNODE_METHOD_KEY = "method"
343UNODE_FAVICON_KEY = "favicon"
344UNODE_ADMIN_KEY = "admin"
345
346# Sets of info per users
347USER_NORMAL_MODE = "normal"
348USER_PUT_MODE = "put"
349USER_PATCH_MODE = "patch"
350
351# Critical node (tracking)
352RUNTIME_NODE_CRITICAL_KEY = "critical"
353
354# Pre-built response bodies for certain endpoints
355RESPONSE_GET_HOME_RESPONSE_NOT_LOGGED_IN = {
356 'title': 'Home',
357 'msg': 'Welcome to the control server.',
358 'resp': '',
359 'logged in': False
360}
361RESPONSE_GET_HOME_API_RESPONSE_NOT_LOGGED_IN = {
362 'title': 'Home',
363 'msg': 'Welcome to the control server.',
364 'resp': '',
365 'logged in': False
366}
367RESPONSE_POST_LOGIN = {
368 'title': 'Login',
369 'msg': 'Welcome {name}',
370 'resp': 'success',
371 'logged in': True,
372 'token': ''
373}
374RESPONSE_POST_REGISTER = {
375 'title': 'Register',
376 "msg": "Account created successfully.",
377 'resp': 'success',
378 'logged in': True
379}
380RESPONSE_PUT_USER = {
381 "title": "Put user",
382 "msg": "The account information has been updated.",
383 "resp": "success",
384 "logged in": True
385}
386RESPONSE_PATCH_USER = {
387 "title": "Patch user",
388 "msg": "The account information has been updated.",
389 "resp": "success",
390 "logged in": True
391}
392RESPONSE_GET_USER = {
393 "title": "Get user",
394 "msg": "The user information has been retrieved.",
395 "resp": "success",
396 "logged in": True
397}
398RESPONSE_GET_USER_ID = {
399 "title": "Get user id",
400 "msg": "The user information has been retrieved.",
401 "resp": 0,
402 "logged in": True
403}
404RESPONSE_POST_LOGOUT = {
405 "title": "Logout",
406 "msg": "You have successfully logged out...",
407 "resp": "success",
408 "logged in": False
409}
410RESPONSE_DELETE_USER = {
411 "title": "Delete user",
412 "msg": "The account has successfully been deleted.",
413 "resp": "success",
414 "logged in": False
415}
Any _get_env_node(Dict[str, Any] env, str key, str default)
Definition constants.py:83
str _password_generator(int length=20, str encapsulation_node="password")
Definition constants.py:159
str _get_toml_variable(dict toml_conf, str section, str key, default=None)
Definition constants.py:118
str get_cache_busting()
Definition constants.py:56
str _get_environement_variable(dotenv environement, str variable_name)
Definition constants.py:100
bool are_json_responses_identical(Dict[str, Any] json_response1, Dict[str, Any] json_response2, str test_name="are_json_responses_identical")
Definition constants.py:188