0
# Test Lifecycle Management
1
2
Classes and context managers for managing test execution phases, including test cases, fixtures, steps, and containers. These components provide the foundation for tracking test lifecycle events and generating comprehensive test reports.
3
4
## Capabilities
5
6
### Steps and Context Management
7
8
Context managers and decorators for organizing test execution into hierarchical steps with proper lifecycle tracking.
9
10
```python { .api }
11
def step(title):
12
"""
13
Decorator and context manager for test steps.
14
15
Can be used as:
16
1. Context manager: with allure.step("Step description"):
17
2. Decorator: @allure.step("Step description")
18
3. Function decorator: @allure.step (uses function name)
19
20
Parameters:
21
- title (str or callable): Step title or function to decorate
22
23
Returns:
24
StepContext instance or decorated function
25
"""
26
27
class StepContext:
28
"""Context manager for test steps with parameter formatting."""
29
30
def __init__(self, title, params):
31
"""
32
Initialize step context.
33
34
Parameters:
35
- title (str): Step title with optional parameter placeholders
36
- params (dict): Parameters for title formatting
37
"""
38
39
def __enter__(self):
40
"""Enter step context and start step tracking."""
41
42
def __exit__(self, exc_type, exc_val, exc_tb):
43
"""
44
Exit step context and stop step tracking.
45
46
Parameters:
47
- exc_type: Exception type if step failed
48
- exc_val: Exception value if step failed
49
- exc_tb: Exception traceback if step failed
50
"""
51
52
def __call__(self, func):
53
"""
54
Use as function decorator.
55
56
Parameters:
57
- func: Function to wrap with step
58
59
Returns:
60
Wrapped function with step tracking
61
"""
62
```
63
64
**Usage Examples:**
65
66
```python
67
# Context manager usage
68
def test_user_registration():
69
with allure.step("Open registration page"):
70
navigate_to_registration()
71
72
with allure.step("Fill user details"):
73
fill_username("testuser")
74
fill_email("test@example.com")
75
76
with allure.step("Submit registration"):
77
click_submit()
78
79
# Decorator usage with parameters
80
@allure.step("Login with username: {username}")
81
def login_user(username, password):
82
enter_credentials(username, password)
83
click_login()
84
85
# Function decorator usage
86
@allure.step
87
def verify_dashboard_loaded():
88
assert dashboard.is_visible()
89
90
def test_login_flow():
91
login_user("testuser", "password123")
92
verify_dashboard_loaded()
93
```
94
95
### Attachment Management
96
97
Class for attaching files and data to test results, steps, and fixtures.
98
99
```python { .api }
100
class Attach:
101
"""Class for managing test attachments."""
102
103
def __call__(self, body, name=None, attachment_type=None, extension=None):
104
"""
105
Attach data to the current test or step.
106
107
Parameters:
108
- body (str or bytes): Data to attach
109
- name (str, optional): Display name for attachment
110
- attachment_type (AttachmentType or str, optional): MIME type
111
- extension (str, optional): File extension
112
"""
113
114
def file(self, source, name=None, attachment_type=None, extension=None):
115
"""
116
Attach a file to the current test or step.
117
118
Parameters:
119
- source (str): Path to file to attach
120
- name (str, optional): Display name for attachment
121
- attachment_type (AttachmentType or str, optional): MIME type
122
- extension (str, optional): File extension override
123
"""
124
125
# Module-level instance
126
attach: Attach
127
```
128
129
**Usage Examples:**
130
131
```python
132
def test_with_attachments():
133
# Attach text data
134
allure.attach("Test execution log", name="Execution Log",
135
attachment_type=allure.attachment_type.TEXT)
136
137
# Attach JSON data
138
test_data = {"user": "testuser", "action": "login"}
139
allure.attach(json.dumps(test_data, indent=2), name="Test Data",
140
attachment_type=allure.attachment_type.JSON)
141
142
# Attach screenshot file
143
allure.attach.file("/tmp/screenshot.png", name="Failure Screenshot",
144
attachment_type=allure.attachment_type.PNG)
145
146
# Attach arbitrary file
147
allure.attach.file("/tmp/debug.log", name="Debug Log",
148
attachment_type="text/plain")
149
```
150
151
### Fixture Lifecycle Management
152
153
Class for managing test fixture execution and lifecycle tracking.
154
155
```python { .api }
156
class fixture:
157
"""Context manager and callable for fixture lifecycle management."""
158
159
def __init__(self, fixture_function, parent_uuid=None, name=None):
160
"""
161
Initialize fixture wrapper.
162
163
Parameters:
164
- fixture_function (callable): The fixture function to wrap
165
- parent_uuid (str, optional): UUID of parent container
166
- name (str, optional): Custom fixture name
167
"""
168
169
def __call__(self, *args, **kwargs):
170
"""
171
Execute fixture with lifecycle tracking.
172
173
Parameters:
174
- *args: Positional arguments for fixture
175
- **kwargs: Keyword arguments for fixture
176
177
Returns:
178
Result of fixture function execution
179
"""
180
181
def __enter__(self):
182
"""Enter fixture context and start tracking."""
183
184
def __exit__(self, exc_type, exc_val, exc_tb):
185
"""
186
Exit fixture context and stop tracking.
187
188
Parameters:
189
- exc_type: Exception type if fixture failed
190
- exc_val: Exception value if fixture failed
191
- exc_tb: Exception traceback if fixture failed
192
"""
193
```
194
195
**Usage Example:**
196
197
```python
198
def database_fixture():
199
"""Set up test database."""
200
db = create_test_database()
201
populate_test_data(db)
202
return db
203
204
def test_with_fixture():
205
# Wrap fixture for Allure tracking
206
wrapped_fixture = allure_commons.fixture(database_fixture, name="Test Database")
207
208
# Execute fixture with tracking
209
db = wrapped_fixture()
210
211
# Use fixture result
212
user = db.get_user("testuser")
213
assert user is not None
214
```
215
216
### Test Lifecycle Management
217
218
Class for managing individual test execution and lifecycle tracking.
219
220
```python { .api }
221
class test:
222
"""Context manager and callable for test lifecycle management."""
223
224
def __init__(self, _test, context):
225
"""
226
Initialize test wrapper.
227
228
Parameters:
229
- _test (callable): The test function to wrap
230
- context (dict): Test execution context
231
"""
232
233
def __call__(self, *args, **kwargs):
234
"""
235
Execute test with lifecycle tracking.
236
237
Parameters:
238
- *args: Positional arguments for test
239
- **kwargs: Keyword arguments for test
240
241
Returns:
242
Result of test function execution
243
"""
244
245
def __enter__(self):
246
"""Enter test context and start tracking."""
247
248
def __exit__(self, exc_type, exc_val, exc_tb):
249
"""
250
Exit test context and stop tracking.
251
252
Parameters:
253
- exc_type: Exception type if test failed
254
- exc_val: Exception value if test failed
255
- exc_tb: Exception traceback if test failed
256
"""
257
```
258
259
### Advanced Lifecycle Management
260
261
Complete lifecycle management class for complex test execution scenarios.
262
263
```python { .api }
264
class AllureLifecycle:
265
"""Main lifecycle management class for test execution tracking."""
266
267
def __init__(self):
268
"""Initialize lifecycle manager with internal item storage."""
269
270
def schedule_test_case(self, uuid=None):
271
"""
272
Context manager to schedule a test case.
273
274
Parameters:
275
- uuid (str, optional): Custom UUID for test case
276
277
Yields:
278
TestResult: Test result object for configuration
279
"""
280
281
def update_test_case(self, uuid=None):
282
"""
283
Context manager to update test case properties.
284
285
Parameters:
286
- uuid (str, optional): UUID of test case to update
287
288
Yields:
289
TestResult: Test result object for modification
290
"""
291
292
def write_test_case(self, uuid=None):
293
"""
294
Write test case to registered reporters.
295
296
Parameters:
297
- uuid (str, optional): UUID of test case to write
298
"""
299
300
def start_step(self, parent_uuid=None, uuid=None):
301
"""
302
Context manager to start a test step.
303
304
Parameters:
305
- parent_uuid (str, optional): UUID of parent item
306
- uuid (str, optional): Custom UUID for step
307
308
Yields:
309
TestStepResult: Step result object for configuration
310
"""
311
312
def update_step(self, uuid=None):
313
"""
314
Context manager to update step properties.
315
316
Parameters:
317
- uuid (str, optional): UUID of step to update
318
319
Yields:
320
TestStepResult: Step result object for modification
321
"""
322
323
def stop_step(self, uuid=None):
324
"""
325
Stop step execution and set end timestamp.
326
327
Parameters:
328
- uuid (str, optional): UUID of step to stop
329
"""
330
331
def start_container(self, uuid=None):
332
"""
333
Context manager to start a test result container.
334
335
Parameters:
336
- uuid (str, optional): Custom UUID for container
337
338
Yields:
339
TestResultContainer: Container object for configuration
340
"""
341
342
def containers(self):
343
"""
344
Generator yielding all active containers.
345
346
Yields:
347
TestResultContainer: Active container objects
348
"""
349
350
def update_container(self, uuid=None):
351
"""
352
Context manager to update container properties.
353
354
Parameters:
355
- uuid (str, optional): UUID of container to update
356
357
Yields:
358
TestResultContainer: Container object for modification
359
"""
360
361
def write_container(self, uuid=None):
362
"""
363
Write container to registered reporters.
364
365
Parameters:
366
- uuid (str, optional): UUID of container to write
367
"""
368
369
def start_before_fixture(self, parent_uuid=None, uuid=None):
370
"""
371
Context manager to start a before fixture.
372
373
Parameters:
374
- parent_uuid (str, optional): UUID of parent container
375
- uuid (str, optional): Custom UUID for fixture
376
377
Yields:
378
TestBeforeResult: Before fixture result object
379
"""
380
381
def update_before_fixture(self, uuid=None):
382
"""
383
Context manager to update before fixture properties.
384
385
Parameters:
386
- uuid (str, optional): UUID of fixture to update
387
388
Yields:
389
TestBeforeResult: Before fixture result object
390
"""
391
392
def stop_before_fixture(self, uuid=None):
393
"""
394
Stop before fixture execution.
395
396
Parameters:
397
- uuid (str, optional): UUID of fixture to stop
398
"""
399
400
def start_after_fixture(self, parent_uuid=None, uuid=None):
401
"""
402
Context manager to start an after fixture.
403
404
Parameters:
405
- parent_uuid (str, optional): UUID of parent container
406
- uuid (str, optional): Custom UUID for fixture
407
408
Yields:
409
TestAfterResult: After fixture result object
410
"""
411
412
def update_after_fixture(self, uuid=None):
413
"""
414
Context manager to update after fixture properties.
415
416
Parameters:
417
- uuid (str, optional): UUID of fixture to update
418
419
Yields:
420
TestAfterResult: After fixture result object
421
"""
422
423
def stop_after_fixture(self, uuid=None):
424
"""
425
Stop after fixture execution.
426
427
Parameters:
428
- uuid (str, optional): UUID of fixture to stop
429
"""
430
431
def attach_file(self, uuid, source, name=None, attachment_type=None,
432
extension=None, parent_uuid=None):
433
"""
434
Attach a file to a test item.
435
436
Parameters:
437
- uuid (str): Attachment UUID
438
- source (str): Path to source file
439
- name (str, optional): Display name
440
- attachment_type (AttachmentType, optional): MIME type
441
- extension (str, optional): File extension
442
- parent_uuid (str, optional): Parent item UUID
443
"""
444
445
def attach_data(self, uuid, body, name=None, attachment_type=None,
446
extension=None, parent_uuid=None):
447
"""
448
Attach data to a test item.
449
450
Parameters:
451
- uuid (str): Attachment UUID
452
- body (str or bytes): Data to attach
453
- name (str, optional): Display name
454
- attachment_type (AttachmentType, optional): MIME type
455
- extension (str, optional): File extension
456
- parent_uuid (str, optional): Parent item UUID
457
"""
458
```
459
460
**Usage Example:**
461
462
```python
463
from allure_commons.lifecycle import AllureLifecycle
464
465
def custom_test_runner():
466
lifecycle = AllureLifecycle()
467
468
# Schedule and configure test case
469
with lifecycle.schedule_test_case() as test_result:
470
test_result.name = "Custom Test"
471
test_result.description = "Test executed by custom runner"
472
473
# Add test steps
474
with lifecycle.start_step() as step:
475
step.name = "Initialize test data"
476
# Execute step logic
477
478
with lifecycle.start_step() as step:
479
step.name = "Execute test scenario"
480
# Execute step logic
481
482
# Attach step data
483
lifecycle.attach_data(
484
uuid="step-data",
485
body="Step execution details",
486
name="Step Data"
487
)
488
489
# Write results
490
lifecycle.write_test_case()
491
```