holado 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of holado might be problematic. Click here for more details.

@@ -0,0 +1,436 @@
1
+
2
+ #################################################
3
+ # HolAdo (Holistic Automation do)
4
+ #
5
+ # (C) Copyright 2021-2025 by Eric Klumpp
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
8
+ #
9
+ # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10
+
11
+ # The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software.
12
+ #################################################
13
+
14
+ from builtins import super
15
+ from _datetime import datetime
16
+ import logging
17
+ import os.path
18
+ from holado.common.context.context import Context
19
+ from holado_core.common.tools.tools import Tools
20
+ import threading
21
+
22
+
23
+ logger = logging
24
+
25
+ def initialize_logger():
26
+ global logger
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ class SessionContext(Context):
31
+ TSessionContext = None
32
+
33
+ # Singleton management
34
+ __instance = None
35
+
36
+ @staticmethod
37
+ def instance() -> TSessionContext:
38
+ if SessionContext.__instance is None:
39
+ SessionContext.__instance = SessionContext.TSessionContext()
40
+ # print(f"Created session context of type {SessionContext.TSessionContext}")
41
+ # import traceback
42
+ # print("".join(traceback.format_list(traceback.extract_stack())))
43
+ return SessionContext.__instance
44
+
45
+
46
+ def __init__(self, name="Session"):
47
+ super().__init__(name)
48
+
49
+ self.__with_session_path = None
50
+
51
+ from holado.common.context.service_manager import ServiceManager
52
+ self.__service_manager = ServiceManager(type(self))
53
+
54
+ # Manage multitasking
55
+ self.__multitask_lock = threading.RLock()
56
+ self.__multitask_step_lock = threading.RLock()
57
+
58
+ def _delete_object(self):
59
+ logger.info(f"Delete session context - Interrupting and unregistering all threads...")
60
+ # if Tools.do_log(logger, logging.DEBUG):
61
+ # logger.debug("Interrupting and unregistering all threads for scenario [{}]".format(scenario.name))
62
+ self.threads_manager.interrupt_all_threads(scope="Session")
63
+ self.threads_manager.unregister_all_threads(scope="Session", keep_alive=False)
64
+
65
+ # Delete session context
66
+ logger.info(f"Delete session context - Deleting context objects...")
67
+ super()._delete_object()
68
+
69
+ def configure(self, session_kwargs=None):
70
+ """
71
+ Override this method to configure the session context before new session creation.
72
+ It is usually used to register new services.
73
+ """
74
+ if session_kwargs is None:
75
+ session_kwargs = {}
76
+
77
+ self.__with_session_path = session_kwargs.get("with_session_path", True)
78
+
79
+ # Register default behave parameter types
80
+ #TODO: make step tools a service
81
+ from holado_test.behave.scenario.behave_step_tools import BehaveStepTools
82
+ BehaveStepTools.register_default_types()
83
+
84
+ # Create this thread context
85
+ self.multitask_manager.get_thread_context()
86
+
87
+ def initialize(self, session_kwargs=None):
88
+ """
89
+ Override this method to initialize the session context after its configuration and new session creation.
90
+ """
91
+ pass
92
+
93
+ @property
94
+ def services(self):
95
+ return self.__service_manager
96
+
97
+ @property
98
+ def with_session_path(self):
99
+ return self.__with_session_path
100
+
101
+ def get_object_getter_eval_string(self, obj, raise_not_found=True):
102
+ from holado_python.standard_library.typing import Typing
103
+
104
+ name = self.get_object_name(obj)
105
+ if name is not None:
106
+ if self.__service_manager.has_service(name):
107
+ return f"{Typing.get_object_class_fullname(self)}.instance().{name}"
108
+ else:
109
+ return f"{Typing.get_object_class_fullname(self)}.instance().get_object('{name}')"
110
+
111
+ if raise_not_found:
112
+ from holado_core.common.exceptions.element_exception import ElementNotFoundException
113
+ raise ElementNotFoundException(f"[{self.name}] Failed to find object of id {id(obj)}")
114
+ else:
115
+ return None
116
+
117
+ def new_session(self, session_kwargs=None):
118
+ # Report session
119
+ report_path = None
120
+ if self.with_session_path:
121
+ # Create new report path for this session
122
+ name = "session_{}".format(datetime.now().strftime("%Y-%m-%d_%H-%M-%S"))
123
+ report_path = self.path_manager.get_reports_path(name)
124
+ logger.info(f"Reports location: {report_path}")
125
+ # print(f"Reports location: {report_path}")
126
+ self.report_manager.new_session(report_path)
127
+
128
+ # Logging configuration
129
+ if self.with_session_path and SessionContext.instance().log_manager.in_file:
130
+ log_filename = os.path.join(report_path, "logs", "report.log")
131
+ self.path_manager.makedirs(log_filename)
132
+ SessionContext.instance().log_manager.on_console = False
133
+ SessionContext.instance().log_manager.set_root_log_file(log_filename)
134
+ SessionContext.instance().log_manager.set_config()
135
+
136
+ def before_all(self, behave_context):
137
+ with self.__multitask_lock:
138
+ self.behave_manager.set_main_context(behave_context)
139
+ self.report_manager.before_all()
140
+
141
+ def after_all(self):
142
+ with self.__multitask_lock:
143
+ self.report_manager.after_all()
144
+ self.behave_manager.clear()
145
+
146
+ def before_feature(self, feature):
147
+ from holado_system.system.global_system import GlobalSystem
148
+ from holado_helper.debug.memory.memory_profiler import MemoryProfiler
149
+ from holado_test.common.context.feature_context import FeatureContext
150
+ from holado_test.test_config import TestConfig
151
+
152
+ log_prefix = f"[Before feature '{feature.name}'] "
153
+
154
+ with self.__multitask_lock:
155
+ # Logs
156
+ logger.info("="*150)
157
+ logger.info(f"Feature [{feature.name}]")
158
+
159
+ logger.info(f"{log_prefix}Begin")
160
+ if self.has_feature_context(is_reference=True):
161
+ from holado_core.common.exceptions.technical_exception import TechnicalException
162
+ raise TechnicalException(f"{log_prefix}A feature context is already defined")
163
+
164
+ GlobalSystem.log_resource_usage(prefix=log_prefix, level=logging.INFO, logger_=logger)
165
+ if TestConfig.profile_memory_in_features and MemoryProfiler.is_tracker_available():
166
+ MemoryProfiler.create_or_reset_tracker_of_objects_summary_changes("features summary")
167
+ # MemoryProfiler.create_or_reset_tracker_of_objects_changes("features objects")
168
+
169
+ # Feature context
170
+ feature_context = FeatureContext(feature)
171
+ self.__set_feature_context(feature_context)
172
+
173
+ # Report
174
+ try:
175
+ self.report_manager.before_feature(feature_context, feature)
176
+ except:
177
+ logger.exception(f"{log_prefix}Error while updating report before feature")
178
+
179
+ logger.info(f"{log_prefix}End")
180
+
181
+ def after_feature(self, feature):
182
+ from holado_system.system.global_system import GlobalSystem
183
+ from holado_helper.debug.memory.memory_profiler import MemoryProfiler
184
+ from holado_test.test_config import TestConfig
185
+
186
+ log_prefix = f"[After feature '{feature.name}'] "
187
+
188
+ with self.__multitask_lock:
189
+ logger.info(f"{log_prefix}Begin")
190
+ if not self.has_feature_context(is_reference=True):
191
+ from holado_core.common.exceptions.technical_exception import TechnicalException
192
+ raise TechnicalException(f"{log_prefix}No feature context is defined")
193
+
194
+ if TestConfig.profile_memory_in_features and MemoryProfiler.is_tracker_available():
195
+ MemoryProfiler.log_tracker_diff(name="features summary", prefix=log_prefix, level=logging.INFO, logger_=logger) # @UndefinedVariable
196
+ # MemoryProfiler.log_tracker_diff(name="features objects", prefix="[After feature] ", level=logging.INFO, logger_=logger) # @UndefinedVariable
197
+ GlobalSystem.log_resource_usage(prefix=log_prefix, level=logging.INFO, logger_=logger)
198
+
199
+ # End feature context
200
+ self.get_feature_context().end()
201
+
202
+ # Report
203
+ try:
204
+ self.report_manager.after_feature(feature)
205
+ except:
206
+ logger.exception(f"{log_prefix}Error while updating report after feature")
207
+
208
+ if Tools.do_log(logger, logging.DEBUG):
209
+ logger.debug(f"{log_prefix}Deleting feature context")
210
+ self.__delete_feature_context()
211
+
212
+ logger.info(f"{log_prefix}End")
213
+ logger.info(f"Finished feature [{feature.name}]")
214
+
215
+ def has_feature_context(self, is_reference=None, do_log=False):
216
+ return self.multitask_manager.has_feature_context(is_reference=is_reference, do_log=do_log)
217
+
218
+ def get_feature_context(self):
219
+ return self.multitask_manager.get_feature_context()
220
+
221
+ def __set_feature_context(self, feature_context):
222
+ return self.multitask_manager.set_feature_context(feature_context)
223
+
224
+ def __delete_feature_context(self):
225
+ return self.multitask_manager.delete_feature_context()
226
+
227
+ def before_scenario(self, scenario):
228
+ from holado_system.system.global_system import GlobalSystem
229
+ from holado_helper.debug.memory.memory_profiler import MemoryProfiler
230
+ from holado_test.common.context.scenario_context import ScenarioContext
231
+ from holado_test.test_config import TestConfig
232
+
233
+ log_prefix = f"[Before scenario '{scenario.name}'] "
234
+
235
+ with self.__multitask_lock:
236
+ logger.info("-"*150)
237
+ logger.info(f"Scenario [{scenario.name}]")
238
+
239
+ logger.info(f"{log_prefix}Begin")
240
+ if not self.has_feature_context(is_reference=True):
241
+ from holado_core.common.exceptions.technical_exception import TechnicalException
242
+ raise TechnicalException(f"{log_prefix}No feature context is defined")
243
+
244
+ # Create and initialize ScenarioContext
245
+ scenario_context = ScenarioContext(scenario)
246
+ self.get_feature_context().add_scenario(scenario_context)
247
+ scenario_context.initialize()
248
+
249
+ # Set variable with scenario context instance
250
+ self.get_scenario_context().get_variable_manager().register_variable("SCENARIO_CONTEXT", self.get_scenario_context())
251
+
252
+ # Report
253
+ try:
254
+ self.report_manager.before_scenario(scenario_context, scenario)
255
+ except:
256
+ logger.exception(f"{log_prefix}Error while updating report before scenario")
257
+
258
+ # Behave context
259
+ try:
260
+ self.behave_manager.before_scenario()
261
+ except:
262
+ logger.exception(f"{log_prefix}Error while updating behave context before scenario")
263
+
264
+ GlobalSystem.log_resource_usage(log_prefix, level=logging.INFO, logger_=logger)
265
+ if TestConfig.profile_memory_in_scenarios and MemoryProfiler.is_tracker_available():
266
+ MemoryProfiler.create_or_reset_tracker_of_objects_summary_changes("scenarios summary")
267
+ # MemoryProfiler.create_or_reset_tracker_of_objects_changes("scenarios objects")
268
+
269
+ logger.info(f"{log_prefix}Doing previous scenario post processes if needed...")
270
+ self.get_scenario_context().do_previous_scenario_post_processes()
271
+
272
+ logger.info(f"{log_prefix}End")
273
+ logger.info(f"Start scenario [{scenario.name}]")
274
+
275
+
276
+ def after_scenario(self, scenario):
277
+ from holado_core.common.exceptions.technical_exception import TechnicalException
278
+ from holado_system.system.global_system import GlobalSystem
279
+ from holado_helper.debug.memory.memory_profiler import MemoryProfiler
280
+ from holado_test.test_config import TestConfig
281
+ from holado_report.report.report_manager import ReportManager
282
+
283
+ log_prefix = f"[After scenario '{scenario.name}'] "
284
+
285
+ with self.__multitask_lock:
286
+ # Log error on failing scenario
287
+ status_validation, step_failed, step_number = ReportManager.get_current_scenario_status_information(scenario)
288
+ if status_validation != "Passed":
289
+ msg_list = []
290
+ if step_failed is not None:
291
+ msg_list.append(f"Scenario {status_validation}: [scenario in {scenario.filename} at l.{scenario.line} - step {step_number} (l.{step_failed.line})]")
292
+ else:
293
+ msg_list.append(f"Scenario {status_validation}: [scenario in {scenario.filename} at l.{scenario.line} - step ? (missing step implementation ?)]")
294
+ step_error_message = ReportManager.get_step_error_message(step_failed)
295
+ if step_error_message:
296
+ msg_list.append(step_error_message)
297
+ msg = "\n".join(msg_list)
298
+ logger.error(msg)
299
+
300
+
301
+ # Process after scenario
302
+ logger.info(f"{log_prefix}Begin")
303
+ # logger.printf"++++++++++++ scenario: {Tools.represent_object(scenario)}")
304
+
305
+ logger.info(f"{log_prefix}Resource usage:")
306
+ if TestConfig.profile_memory_in_scenarios and MemoryProfiler.is_tracker_available():
307
+ MemoryProfiler.log_tracker_diff(name="scenarios summary", prefix=log_prefix, level=logging.INFO, logger_=logger) # @UndefinedVariable
308
+ # MemoryProfiler.log_tracker_diff(name="scenarios objects", prefix="[After scenario] ", level=logging.INFO, logger_=logger) # @UndefinedVariable
309
+ GlobalSystem.log_resource_usage(prefix=log_prefix, level=logging.INFO, logger_=logger)
310
+
311
+ if not self.has_feature_context(is_reference=True):
312
+ raise TechnicalException(f"{log_prefix}No feature context is defined")
313
+ if not self.has_scenario_context(is_reference=True):
314
+ raise TechnicalException(f"{log_prefix}No scenario context is defined")
315
+
316
+ self.get_scenario_context().end()
317
+
318
+ # Post processes
319
+ logger.info(f"{log_prefix}Post processing...")
320
+ self.get_scenario_context().scope_manager.reset_scope_level()
321
+ self.get_scenario_context().do_post_processes()
322
+
323
+ # Report
324
+ logger.info(f"{log_prefix}Generating reports...")
325
+ try:
326
+ self.report_manager.after_scenario(scenario)
327
+ except:
328
+ logger.exception(f"{log_prefix}Error while updating report after scenario")
329
+
330
+ # Delete scenario context
331
+ logger.info(f"{log_prefix}Deleting scenario context...")
332
+ # if Tools.do_log(logger, logging.DEBUG):
333
+ # logger.debug("Deleting context of scenario [{}]".format(scenario.name))
334
+ self.__delete_scenario_context()
335
+
336
+ # Remove all threads
337
+ logger.info(f"{log_prefix}Interrupting and unregistering all threads...")
338
+ # if Tools.do_log(logger, logging.DEBUG):
339
+ # logger.debug("Interrupting and unregistering all threads for scenario [{}]".format(scenario.name))
340
+ #TODO: For case of multiple scenarios launched in parallel, interrupt only threads related to current scenario (scenario launched by this thread)
341
+ self.threads_manager.interrupt_all_threads(scope="Scenario")
342
+ self.threads_manager.unregister_all_threads(scope="Scenario", keep_alive=False)
343
+
344
+ logger.info(f"{log_prefix}End")
345
+ logger.info(f"Finished scenario [{scenario.name}]")
346
+
347
+ def has_scenario_context(self, is_reference=None):
348
+ return self.has_feature_context(is_reference=is_reference) and self.get_feature_context().has_scenario
349
+
350
+ def get_scenario_context(self):
351
+ return self.get_feature_context().current_scenario
352
+
353
+ def __delete_scenario_context(self):
354
+ self.get_scenario_context().delete_object()
355
+
356
+ def before_step(self, step):
357
+ log_prefix = f"[Before step '{step}'] "
358
+
359
+ with self.__multitask_step_lock:
360
+ from holado_test.common.context.step_context import StepContext
361
+ from holado_core.common.exceptions.technical_exception import TechnicalException
362
+
363
+ if not self.has_feature_context(is_reference=None):
364
+ # Look again but do logs before raising exception
365
+ self.has_feature_context(is_reference=None, do_log=True)
366
+ raise TechnicalException(f"{log_prefix}No feature context is defined (step: {step})")
367
+ if not self.has_scenario_context(is_reference=None):
368
+ raise TechnicalException(f"{log_prefix}No scenario context is defined (step: {step})")
369
+ scenario_context = self.get_scenario_context()
370
+
371
+ # Manage step context
372
+ step_context = StepContext(step)
373
+ scenario_context.scope_manager.set_step_context(step_context)
374
+
375
+ # Update scenario context
376
+ step_level = scenario_context.scope_manager.scope_level("steps")
377
+ if step_level == 0:
378
+ if logger.isEnabledFor(logging.DEBUG):
379
+ logger.debug(f"{log_prefix}Add step {step_context} in scenario {scenario_context}")
380
+ scenario_context.add_step(step_context)
381
+
382
+ # Manage scope in define
383
+ if scenario_context.block_manager.is_in_define \
384
+ and (scenario_context.block_manager.is_in_sub_define # needed to add in define the "end define" steps of sub-define \
385
+ or step.name not in ["end for", "end while", "end function"]): # needed to not add in define the "end define" steps of current define
386
+ from holado_test.behave.behave import format_step
387
+ step_str = format_step(step)
388
+ scenario_context.block_manager.scope_in_define.add_steps(step_str)
389
+
390
+ # Set step status
391
+ step_context.status = "defined"
392
+
393
+ # Report
394
+ try:
395
+ self.report_manager.before_step(step_context, step, step_level)
396
+ except:
397
+ logger.exception(f"{log_prefix}Error while updating report before step")
398
+
399
+ def after_step(self, step):
400
+ log_prefix = f"[After step '{step}'] "
401
+
402
+ with self.__multitask_step_lock:
403
+ from holado_core.common.exceptions.technical_exception import TechnicalException
404
+
405
+ if not self.has_feature_context(is_reference=None):
406
+ raise TechnicalException(f"{log_prefix}No feature context is defined (step: {step})")
407
+ if not self.has_scenario_context(is_reference=None):
408
+ raise TechnicalException(f"{log_prefix}No scenario context is defined (step: {step})")
409
+ scenario_context = self.get_scenario_context()
410
+
411
+ # Manage step context
412
+ step_context = scenario_context.scope_manager.get_step_context()
413
+ step_context.end()
414
+ if step_context.status is None:
415
+ step_context.status = step.status.name
416
+ if logger.isEnabledFor(logging.DEBUG):
417
+ logger.debug(f"{log_prefix}Ended step {step_context} in scenario {scenario_context}")
418
+
419
+ # Report
420
+ try:
421
+ step_level = scenario_context.scope_manager.scope_level("steps")
422
+ self.report_manager.after_step(step_context, step, step_level)
423
+ except:
424
+ logger.exception(f"{log_prefix}Error while updating report after step")
425
+
426
+ def has_step_context(self):
427
+ return self.has_feature_context() and self.get_feature_context().has_scenario and self.get_scenario_context().has_step()
428
+
429
+ def get_step_context(self):
430
+ return self.get_scenario_context().get_current_step()
431
+
432
+
433
+
434
+ SessionContext.TSessionContext = SessionContext
435
+
436
+
@@ -0,0 +1,19 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ #################################################
4
+ # HolAdo (Holistic Automation do)
5
+ #
6
+ # (C) Copyright 2021-2025 by Eric Klumpp
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
11
+
12
+ # The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software.
13
+ #################################################
14
+
15
+
16
+ def initialize_loggers():
17
+ import holado.common.handlers.object
18
+ holado.common.handlers.object.initialize_logger()
19
+
@@ -0,0 +1,41 @@
1
+
2
+ #################################################
3
+ # HolAdo (Holistic Automation do)
4
+ #
5
+ # (C) Copyright 2021-2025 by Eric Klumpp
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
8
+ #
9
+ # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10
+
11
+ # The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software.
12
+ #################################################
13
+
14
+ from builtins import object
15
+
16
+ from enum import Enum
17
+
18
+
19
+ class AutoNumber(Enum):
20
+ def __new__(self):
21
+ value = len(self.__members__) + 1
22
+ obj = object.__new__(self)
23
+ obj._value_ = value
24
+ return obj
25
+
26
+
27
+ class ObjectStates(AutoNumber):
28
+ """
29
+ @summary: Object state
30
+ """
31
+ Created = ()
32
+ Initialized = ()
33
+ Opening = ()
34
+ Open = ()
35
+ Closing = ()
36
+ Closed = ()
37
+ Deleting = ()
38
+ Deleted = ()
39
+
40
+
41
+
@@ -0,0 +1,146 @@
1
+
2
+ #################################################
3
+ # HolAdo (Holistic Automation do)
4
+ #
5
+ # (C) Copyright 2021-2025 by Eric Klumpp
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
8
+ #
9
+ # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10
+
11
+ # The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software.
12
+ #################################################
13
+
14
+ from builtins import object
15
+ import logging
16
+ from holado.common.handlers.enums import ObjectStates
17
+ from holado.common.tools.gc_manager import GcManager
18
+
19
+ logger = None
20
+
21
+ def initialize_logger():
22
+ global logger
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class Object(object):
27
+ def __init__(self, name=None):
28
+ self.__name = name
29
+ self.__obj_state = ObjectStates.Created
30
+
31
+ @property
32
+ def name(self):
33
+ if self.__name:
34
+ return self.__name
35
+ else:
36
+ return str(self)
37
+
38
+ @property
39
+ def object_state(self):
40
+ return self.__obj_state
41
+
42
+ @object_state.setter
43
+ def object_state(self, state):
44
+ from holado_core.common.tools.tools import Tools
45
+ from holado_python.standard_library.typing import Typing
46
+
47
+ if Tools.do_log(logger, logging.TRACE): # @UndefinedVariable
48
+ logger.trace(f"State changed for object '{self.name}' (type: {Typing.get_object_class_fullname(self)}): {self.__obj_state} -> {state}")
49
+ self.__obj_state = state
50
+
51
+
52
+ class DeleteableObject(Object):
53
+ """
54
+ Add to a class deleting features:the possibility to be deleted
55
+ - Self deleting actions
56
+ - Register functions to call on delete
57
+
58
+ Note: It is highly recommended to set garbage collector periodicity with GcManager.collect_periodically method (see method documentation)
59
+ """
60
+
61
+ def __init__(self, name=None):
62
+ super().__init__(name)
63
+
64
+ self.__on_delete_funcs = []
65
+ self.__on_delete_gc_collect = False
66
+
67
+ def __del__(self):
68
+ try:
69
+ from holado_multitask.multithreading.functionthreaded import FunctionThreaded
70
+
71
+ if self.object_state in [ObjectStates.Deleting, ObjectStates.Deleted]:
72
+ return
73
+
74
+ # Note: Garbage collector default mecanism is incompatible with custom object finalizers (cf GcManager.Method __del__ is called by garbage collector. This call can be done in any thread at any moment.
75
+ if GcManager.is_collect_threaded():
76
+ self.__delete()
77
+ else:
78
+ func = FunctionThreaded(self.__delete, name=f"delete object '{self.name}'", register_thread=False)
79
+ func.start()
80
+ func.join(timeout=30, raise_if_still_alive=False) # timeout of 30s to limit deadlock impact ; raise to False since exceptions are omitted in gc collect context
81
+ except Exception as exc:
82
+ if "Python is likely shutting down" in str(exc):
83
+ # Simply return
84
+ return
85
+ else:
86
+ raise exc
87
+
88
+ def __delete(self):
89
+ try:
90
+ self.delete_object()
91
+ except Exception as exc:
92
+ if "Python is likely shutting down" in str(exc):
93
+ # Simply return
94
+ return
95
+ else:
96
+ raise exc
97
+
98
+ @property
99
+ def on_delete_call_gc_collect(self):
100
+ return self.__on_delete_gc_collect
101
+
102
+ @on_delete_call_gc_collect.setter
103
+ def on_delete_call_gc_collect(self, do_call):
104
+ self.__on_delete_gc_collect = do_call
105
+
106
+ def on_delete_call_func(self, func):
107
+ self.__on_delete_funcs.append(func)
108
+
109
+ def delete_object(self):
110
+ from holado_core.common.tools.tools import Tools
111
+ from holado_python.standard_library.typing import Typing
112
+
113
+ if self.object_state in [ObjectStates.Deleting, ObjectStates.Deleted]:
114
+ return False
115
+
116
+ if Tools.do_log(logger, logging.DEBUG):
117
+ logger.debug(f"Deleting object '{self.name}' (type: {Typing.get_object_class_fullname(self)})...")
118
+ self.object_state = ObjectStates.Deleting
119
+
120
+ # Run on_delete functions
121
+ for func in self.__on_delete_funcs:
122
+ try:
123
+ func()
124
+ except:
125
+ logger.exception(f"[{self.name}] Error while running on delete function '{func}'")
126
+
127
+ self._delete_object()
128
+
129
+ # Call garbage collector
130
+ if self.__on_delete_gc_collect:
131
+ GcManager.collect()
132
+
133
+ self.object_state = ObjectStates.Deleted
134
+ if Tools.do_log(logger, logging.DEBUG):
135
+ logger.debug(f"Deleted object '{self.name}' (type: {Typing.get_object_class_fullname(self)})")
136
+
137
+ return True
138
+
139
+ def _delete_object(self):
140
+ """
141
+ Implement this method for specific delete actions
142
+ """
143
+ pass
144
+
145
+
146
+
@@ -0,0 +1,39 @@
1
+ #################################################
2
+ # HolAdo (Holistic Automation do)
3
+ #
4
+ # (C) Copyright 2021-2025 by Eric Klumpp
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
+ #
8
+ # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
+
10
+ # The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software.
11
+ #################################################
12
+
13
+ import logging
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class Undefined(object):
19
+ def __init__(self, undefined_value=0):
20
+ self.__value = undefined_value
21
+
22
+ def is_undefined(obj):
23
+ return isinstance(obj, Undefined)
24
+
25
+
26
+ # Define specific undefined objects
27
+
28
+ undefined_argument = Undefined(0)
29
+ undefined_value = Undefined(1)
30
+
31
+
32
+
33
+ # Define specific default values
34
+ # Note: Real value is defined by methods managing these values as argument.
35
+
36
+ default_value = Undefined(2)
37
+ default_context = Undefined(3) # Example of real value: for ThreadsManager it means "current ScenarioContext" if a scenario context exists else "SessionContext".
38
+
39
+