testzeus-cli 0.0.2__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.
@@ -0,0 +1,309 @@
1
+ """
2
+ Commands for managing test runs in TestZeus CLI.
3
+ """
4
+
5
+ import asyncio
6
+ import os
7
+ import time
8
+ from pathlib import Path
9
+ import click
10
+ from typing import Dict, Any, Optional, List
11
+ from rich.console import Console
12
+ from rich.progress import Progress
13
+
14
+ from testzeus_sdk import TestZeusClient
15
+ from testzeus_cli.config import get_client_config
16
+ from testzeus_cli.utils.formatters import format_output
17
+ from testzeus_cli.utils.validators import validate_id, parse_key_value_pairs
18
+ from testzeus_cli.utils.auth import initialize_client_with_token
19
+
20
+ console = Console()
21
+
22
+
23
+ @click.group(name="test-runs")
24
+ def test_runs_group():
25
+ """Manage TestZeus test runs"""
26
+ pass
27
+
28
+
29
+ @test_runs_group.command(name="create")
30
+ @click.option("--name", required=True, help="Test run name")
31
+ @click.option("--test", required=True, help="Test ID or name")
32
+ @click.pass_context
33
+ def create_test_run(ctx, name, test):
34
+ """Create and start a test run"""
35
+
36
+ async def _run():
37
+ config, token = get_client_config(
38
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
39
+ )
40
+ client = TestZeusClient(**config)
41
+
42
+ async with client:
43
+ # Apply token from config if available
44
+ if token:
45
+ initialize_client_with_token(client, token)
46
+ else:
47
+ await client.ensure_authenticated()
48
+
49
+ test_run = await client.test_runs.create_and_start(name=name, test=test)
50
+ return test_run.data
51
+
52
+ result = asyncio.run(_run())
53
+ console.print(
54
+ f"[green]Test run created and started with ID: {result['id']}[/green]"
55
+ )
56
+ format_output(result, ctx.obj["FORMAT"])
57
+
58
+
59
+ @test_runs_group.command(name="list")
60
+ @click.option(
61
+ "--filters", "-f", multiple=True, help="Filter results (format: key=value)"
62
+ )
63
+ @click.option("--sort", help="Sort by field")
64
+ @click.option("--expand", help="Expand related entities")
65
+ @click.pass_context
66
+ def list_test_runs(ctx, filters, sort, expand):
67
+ """List test runs with optional filters and sorting"""
68
+
69
+ async def _run():
70
+ config, token = get_client_config(
71
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
72
+ )
73
+ client = TestZeusClient(**config)
74
+
75
+ # Parse filters
76
+ filter_dict = parse_key_value_pairs(filters) if filters else {}
77
+
78
+ async with client:
79
+ # Apply token from config if available
80
+ if token:
81
+ initialize_client_with_token(client, token)
82
+ else:
83
+ await client.ensure_authenticated()
84
+
85
+ test_runs = await client.test_runs.get_list(
86
+ expand=expand, sort=sort, filters=filter_dict
87
+ )
88
+ return test_runs
89
+
90
+ result = asyncio.run(_run())
91
+ format_output(result, ctx.obj["FORMAT"])
92
+
93
+
94
+ @test_runs_group.command(name="get")
95
+ @click.argument("test_run_id")
96
+ @click.option("--expand", help="Expand related entities")
97
+ @click.pass_context
98
+ def get_test_run(ctx, test_run_id, expand):
99
+ """Get a single test run by ID"""
100
+
101
+ async def _run():
102
+ config, token = get_client_config(
103
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
104
+ )
105
+ client = TestZeusClient(**config)
106
+
107
+ test_run_id_validated = validate_id(test_run_id, "test run")
108
+
109
+ async with client:
110
+ # Apply token from config if available
111
+ if token:
112
+ initialize_client_with_token(client, token)
113
+ else:
114
+ await client.ensure_authenticated()
115
+
116
+ test_run = await client.test_runs.get_one(
117
+ test_run_id_validated, expand=expand
118
+ )
119
+ return test_run.data
120
+
121
+ result = asyncio.run(_run())
122
+ format_output(result, ctx.obj["FORMAT"])
123
+
124
+
125
+ @test_runs_group.command(name="get-expanded")
126
+ @click.argument("test_run_id")
127
+ @click.pass_context
128
+ def get_expanded_test_run(ctx, test_run_id):
129
+ """Get expanded details for a test run including all outputs and steps"""
130
+
131
+ async def _run():
132
+ config, token = get_client_config(
133
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
134
+ )
135
+ client = TestZeusClient(**config)
136
+
137
+ test_run_id_validated = validate_id(test_run_id, "test run")
138
+
139
+ async with client:
140
+ # Apply token from config if available
141
+ if token:
142
+ initialize_client_with_token(client, token)
143
+ else:
144
+ await client.ensure_authenticated()
145
+
146
+ expanded_test_run = await client.test_runs.get_expanded(
147
+ test_run_id_validated
148
+ )
149
+ return expanded_test_run
150
+
151
+ result = asyncio.run(_run())
152
+ format_output(result, ctx.obj["FORMAT"])
153
+
154
+
155
+ @test_runs_group.command(name="cancel")
156
+ @click.argument("test_run_id")
157
+ @click.pass_context
158
+ def cancel_test_run(ctx, test_run_id):
159
+ """Cancel a running test"""
160
+
161
+ async def _run():
162
+ config, token = get_client_config(
163
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
164
+ )
165
+ client = TestZeusClient(**config)
166
+
167
+ test_run_id_validated = validate_id(test_run_id, "test run")
168
+
169
+ async with client:
170
+ # Apply token from config if available
171
+ if token:
172
+ initialize_client_with_token(client, token)
173
+ else:
174
+ await client.ensure_authenticated()
175
+
176
+ cancelled_test = await client.test_runs.cancel(test_run_id_validated)
177
+ return cancelled_test.data
178
+
179
+ try:
180
+ result = asyncio.run(_run())
181
+ console.print(
182
+ f"[green]Test run cancelled successfully: {result['name']}[/green]"
183
+ )
184
+ format_output(result, ctx.obj["FORMAT"])
185
+ except ValueError as e:
186
+ console.print(f"[red]Failed to cancel test run:[/red] {str(e)}")
187
+ exit(1)
188
+
189
+
190
+ @test_runs_group.command(name="watch")
191
+ @click.argument("test_run_id")
192
+ @click.option("--interval", default=5, help="Check interval in seconds")
193
+ @click.pass_context
194
+ def watch_test_run(ctx, test_run_id, interval):
195
+ """Watch a test run until completion"""
196
+
197
+ async def _monitor_test_run():
198
+ config, token = get_client_config(
199
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
200
+ )
201
+ client = TestZeusClient(**config)
202
+
203
+ test_run_id_validated = validate_id(test_run_id, "test run")
204
+
205
+ with Progress() as progress:
206
+ task = progress.add_task("[cyan]Running test...", total=None)
207
+
208
+ async with client:
209
+ # Apply token from config if available
210
+ if token:
211
+ initialize_client_with_token(client, token)
212
+ else:
213
+ await client.ensure_authenticated()
214
+
215
+ while True:
216
+ test_run = await client.test_runs.get_one(test_run_id_validated)
217
+
218
+ # Update progress description with status
219
+ progress.update(
220
+ task, description=f"[cyan]Test status: {test_run.status}[/cyan]"
221
+ )
222
+
223
+ if test_run.is_completed():
224
+ progress.update(task, completed=100, total=100)
225
+ console.print("[green]Test run completed successfully![/green]")
226
+ return test_run.data
227
+ elif test_run.is_failed():
228
+ progress.update(task, completed=100, total=100)
229
+ console.print("[red]Test run failed![/red]")
230
+ return test_run.data
231
+ elif test_run.is_crashed():
232
+ progress.update(task, completed=100, total=100)
233
+ console.print("[red]Test run crashed![/red]")
234
+ return test_run.data
235
+ elif test_run.is_cancelled():
236
+ progress.update(task, completed=100, total=100)
237
+ console.print("[yellow]Test run was cancelled![/yellow]")
238
+ return test_run.data
239
+
240
+ # Sleep for the specified interval
241
+ await asyncio.sleep(interval)
242
+
243
+ try:
244
+ result = asyncio.run(_monitor_test_run())
245
+ duration = result.get("duration") or "Unknown"
246
+ console.print(f"Test run duration: {duration} seconds")
247
+ format_output(result, ctx.obj["FORMAT"])
248
+ except Exception as e:
249
+ console.print(f"[red]Error watching test run:[/red] {str(e)}")
250
+ exit(1)
251
+
252
+
253
+ @test_runs_group.command(name="download-attachments")
254
+ @click.argument("test_run_id")
255
+ @click.option(
256
+ "--output-dir", default="./attachments", help="Directory to save attachments"
257
+ )
258
+ @click.pass_context
259
+ def download_attachments(ctx, test_run_id, output_dir):
260
+ """Download all attachments for a test run"""
261
+
262
+ async def _run():
263
+ config, token = get_client_config(
264
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
265
+ )
266
+ client = TestZeusClient(**config)
267
+
268
+ test_run_id_validated = validate_id(test_run_id, "test run")
269
+
270
+ # Create output directory if it doesn't exist
271
+ output_path = Path(output_dir)
272
+ output_path.mkdir(parents=True, exist_ok=True)
273
+
274
+ async with client:
275
+ # Apply token from config if available
276
+ if token:
277
+ initialize_client_with_token(client, token)
278
+ else:
279
+ await client.ensure_authenticated()
280
+
281
+ # Download all attachments for the test run
282
+ result = await client.test_runs.download_all_attachments(
283
+ test_run_id_validated, str(output_path)
284
+ )
285
+ return result
286
+
287
+ try:
288
+ result = asyncio.run(_run())
289
+
290
+ if not result:
291
+ console.print(
292
+ "[yellow]No attachments found or downloaded for this test run[/yellow]"
293
+ )
294
+ return
295
+
296
+ console.print(
297
+ f"[green]Downloaded {len(result)} attachments to {output_dir}[/green]"
298
+ )
299
+ for attachment in result:
300
+ console.print(f"- {attachment}")
301
+ except Exception as e:
302
+ if ctx.obj.get("VERBOSE"):
303
+ console.print(f"[red]Failed to download attachments:[/red]")
304
+ import traceback
305
+
306
+ console.print(traceback.format_exc())
307
+ else:
308
+ console.print(f"[red]Failed to download attachments:[/red] {str(e)}")
309
+ exit(1)
@@ -0,0 +1,389 @@
1
+ """
2
+ Commands for managing tests in TestZeus CLI.
3
+ """
4
+
5
+ import asyncio
6
+ import os
7
+ import json
8
+ import click
9
+ import datetime
10
+ from typing import Dict, Any, Optional, List
11
+ from pathlib import Path
12
+ from rich.console import Console
13
+
14
+ from testzeus_sdk import TestZeusClient
15
+ from testzeus_cli.config import get_client_config
16
+ from testzeus_cli.utils.formatters import format_output
17
+ from testzeus_cli.utils.validators import validate_id, parse_key_value_pairs
18
+ from testzeus_cli.utils.client import run_client_operation
19
+ from testzeus_cli.utils.auth import initialize_client_with_token
20
+
21
+ console = Console()
22
+
23
+
24
+ def clean_data_for_api(data: Dict[str, Any]) -> Dict[str, Any]:
25
+ """
26
+ Clean the data dictionary for API use by converting non-serializable types.
27
+ Also ensures that required fields like name and tenant are preserved.
28
+
29
+ Args:
30
+ data: Dictionary of data to clean
31
+
32
+ Returns:
33
+ Cleaned dictionary suitable for API use
34
+ """
35
+ clean_data = {}
36
+
37
+ # Critical fields that must be preserved if they exist in the original data
38
+ critical_fields = ["name", "tenant", "id", "status"]
39
+
40
+ for key, value in data.items():
41
+ # Skip internal PocketBase fields that aren't needed for updates
42
+ if key in ["collection_id", "collection_name", "expand", "created", "updated"]:
43
+ continue
44
+
45
+ # Convert datetime objects to ISO format strings
46
+ if isinstance(value, datetime.datetime):
47
+ clean_data[key] = value.isoformat()
48
+ else:
49
+ clean_data[key] = value
50
+
51
+ # Double-check critical fields are preserved
52
+ for field in critical_fields:
53
+ if field in data and (field not in clean_data or not clean_data[field]):
54
+ clean_data[field] = data[field]
55
+
56
+ return clean_data
57
+
58
+
59
+ @click.group(name="tests")
60
+ def tests_group():
61
+ """Manage TestZeus tests"""
62
+ pass
63
+
64
+
65
+ @tests_group.command(name="list")
66
+ @click.option(
67
+ "--filters", "-f", multiple=True, help="Filter results (format: key=value)"
68
+ )
69
+ @click.option("--sort", help="Sort by field")
70
+ @click.option("--expand", help="Expand related entities")
71
+ @click.pass_context
72
+ def list_tests(ctx, filters, sort, expand):
73
+ """List tests with optional filters and sorting"""
74
+
75
+ # Parse filters
76
+ filter_dict = parse_key_value_pairs(filters) if filters else {}
77
+
78
+ # Define the operation to run with the authenticated client
79
+ async def _list_tests(client: TestZeusClient):
80
+ return await client.tests.get_list(
81
+ expand=expand, sort=sort, filters=filter_dict
82
+ )
83
+
84
+ # Run the operation and format the result
85
+ result = run_client_operation(ctx, _list_tests)
86
+ format_output(result, ctx.obj["FORMAT"])
87
+
88
+
89
+ @tests_group.command(name="get")
90
+ @click.argument("test_id")
91
+ @click.option("--expand", help="Expand related entities")
92
+ @click.pass_context
93
+ def get_test(ctx, test_id, expand):
94
+ """Get a single test by ID"""
95
+
96
+ async def _run():
97
+ config, token = get_client_config(
98
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
99
+ )
100
+ client = TestZeusClient(**config)
101
+
102
+ test_id_validated = validate_id(test_id, "test")
103
+
104
+ async with client:
105
+ # Apply token from config if available
106
+ if token:
107
+ initialize_client_with_token(client, token)
108
+ else:
109
+ await client.ensure_authenticated()
110
+
111
+ test = await client.tests.get_one(test_id_validated, expand=expand)
112
+ return test.data
113
+
114
+ result = asyncio.run(_run())
115
+ format_output(result, ctx.obj["FORMAT"])
116
+
117
+
118
+ def _read_feature_file(file_path: str) -> str:
119
+ """
120
+ Read feature content from a file as plain text
121
+
122
+ Args:
123
+ file_path: Path to the feature file
124
+
125
+ Returns:
126
+ The raw text content of the file
127
+ """
128
+ feature_path = Path(file_path)
129
+ if not feature_path.exists():
130
+ raise click.BadParameter(f"Feature file not found: {file_path}")
131
+
132
+ try:
133
+ with open(feature_path, "r", encoding="utf-8") as f:
134
+ content = f.read().strip()
135
+ except Exception as e:
136
+ raise click.BadParameter(f"Failed to read feature file: {str(e)}")
137
+
138
+ # Always return the raw text content, regardless of file extension
139
+ return content
140
+
141
+
142
+ @tests_group.command(name="create")
143
+ @click.option("--name", required=True, help="Test name")
144
+ @click.option("--feature", help="Test feature content as text")
145
+ @click.option("--feature-file", help="Path to file containing feature content (text)")
146
+ @click.option("--status", default="draft", help="Test status (draft, ready, deleted)")
147
+ @click.option("--data", multiple=True, help="Test data IDs")
148
+ @click.option("--tags", multiple=True, help="Tag IDs")
149
+ @click.option("--environment", help="Environment ID")
150
+ @click.pass_context
151
+ def create_test(ctx, name, feature, feature_file, status, data, tags, environment):
152
+ """Create a new test with feature content from text or file"""
153
+
154
+ if not feature and not feature_file:
155
+ raise click.UsageError("Either --feature or --feature-file is required")
156
+
157
+ if feature and feature_file:
158
+ raise click.UsageError("Cannot use both --feature and --feature-file")
159
+
160
+ # Process the feature content (from file or directly)
161
+ feature_content = _read_feature_file(feature_file) if feature_file else feature
162
+
163
+ async def _run():
164
+ config, token = get_client_config(
165
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
166
+ )
167
+ client = TestZeusClient(**config)
168
+
169
+ # Prepare parameters
170
+ test_data = {"name": name, "status": status}
171
+
172
+ # Always set feature content as text
173
+ test_data["test_feature"] = feature_content
174
+
175
+ if data:
176
+ test_data["test_data"] = list(data)
177
+
178
+ if tags:
179
+ test_data["tags"] = list(tags)
180
+
181
+ if environment:
182
+ test_data["environment"] = environment
183
+
184
+ async with client:
185
+ # Apply token from config if available
186
+ if token:
187
+ initialize_client_with_token(client, token)
188
+ else:
189
+ await client.ensure_authenticated()
190
+
191
+ # Add tenant ID from the client's authentication
192
+ test_data["tenant"] = client.get_tenant_id()
193
+
194
+ new_test = await client.tests.create(test_data)
195
+ return new_test.data
196
+
197
+ result = asyncio.run(_run())
198
+ console.print(f"[green]Test created successfully with ID: {result['id']}[/green]")
199
+ format_output(result, ctx.obj["FORMAT"])
200
+
201
+
202
+ @tests_group.command(name="update")
203
+ @click.argument("test_id")
204
+ @click.option("--name", help="New test name")
205
+ @click.option("--feature", help="New test feature content as text")
206
+ @click.option(
207
+ "--feature-file", help="Path to file containing new feature content (text)"
208
+ )
209
+ @click.option("--status", help="New test status (draft, ready, deleted)")
210
+ @click.option("--data", multiple=True, help="Test data IDs")
211
+ @click.option("--tags", multiple=True, help="Tag IDs")
212
+ @click.option("--environment", help="Environment ID")
213
+ @click.pass_context
214
+ def update_test(
215
+ ctx, test_id, name, feature, feature_file, status, data, tags, environment
216
+ ):
217
+ """Update an existing test with feature content from text or file"""
218
+
219
+ if feature and feature_file:
220
+ raise click.UsageError("Cannot use both --feature and --feature-file")
221
+
222
+ # Process the feature content if a file was provided
223
+ feature_content = None
224
+ if feature_file:
225
+ feature_content = _read_feature_file(feature_file)
226
+ elif feature:
227
+ feature_content = feature
228
+
229
+ async def _run():
230
+ config, token = get_client_config(
231
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
232
+ )
233
+ client = TestZeusClient(**config)
234
+
235
+ test_id_validated = validate_id(test_id, "test")
236
+
237
+ async with client:
238
+ # Apply token from config if available
239
+ if token:
240
+ # Use the safe initialization method to ensure tenant data is set
241
+ initialize_client_with_token(client, token)
242
+ else:
243
+ await client.ensure_authenticated()
244
+
245
+ # First, fetch the existing test to get ALL fields
246
+ existing_test = await client.tests.get_one(test_id_validated)
247
+
248
+ if ctx.obj.get("VERBOSE"):
249
+ console.print(f"[blue]Existing test: {existing_test.data}[/blue]")
250
+
251
+ # Start with all existing data to ensure we don't lose anything
252
+ updates = dict(existing_test.data)
253
+
254
+ # Check if we have at least one field to update
255
+ has_updates = False
256
+
257
+ # Add only the fields the user wants to update
258
+ if name:
259
+ updates["name"] = name
260
+ has_updates = True
261
+
262
+ if feature_content is not None:
263
+ # Always set feature content as text
264
+ updates["test_feature"] = feature_content
265
+ has_updates = True
266
+
267
+ if status:
268
+ updates["status"] = status
269
+ has_updates = True
270
+
271
+ if data:
272
+ updates["test_data"] = list(data)
273
+ has_updates = True
274
+
275
+ if tags:
276
+ updates["tags"] = list(tags)
277
+ has_updates = True
278
+
279
+ if environment:
280
+ updates["environment"] = environment
281
+ has_updates = True
282
+
283
+ if not has_updates:
284
+ console.print("[yellow]No updates provided[/yellow]")
285
+ return None
286
+
287
+ if ctx.obj.get("VERBOSE"):
288
+ console.print(f"[blue]Updating test with: {updates}[/blue]")
289
+
290
+ # Clean the data before sending to the API
291
+ clean_updates = clean_data_for_api(updates)
292
+
293
+ if ctx.obj.get("VERBOSE"):
294
+ console.print(f"[blue]Cleaned updates for API: {clean_updates}[/blue]")
295
+
296
+ updated_test = await client.tests.update(test_id_validated, clean_updates)
297
+ return updated_test.data
298
+
299
+ try:
300
+ result = asyncio.run(_run())
301
+ if result:
302
+ console.print(f"[green]Test updated successfully: {result['name']}[/green]")
303
+ format_output(result, ctx.obj["FORMAT"])
304
+ except Exception as e:
305
+ if ctx.obj.get("VERBOSE"):
306
+ console.print(f"[red]Error updating test:[/red]")
307
+ import traceback
308
+
309
+ console.print(traceback.format_exc())
310
+ else:
311
+ console.print(f"[red]Error updating test:[/red] {str(e)}")
312
+ exit(1)
313
+
314
+
315
+ @tests_group.command(name="solve")
316
+ @click.argument("test_id")
317
+ @click.option("--output-file", help="Save solution to this file path")
318
+ @click.pass_context
319
+ def solve_test(ctx, test_id, output_file):
320
+ """Generate a solution for a test using the TestZeus platform"""
321
+
322
+ async def _run():
323
+ config, token = get_client_config(
324
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
325
+ )
326
+ client = TestZeusClient(**config)
327
+
328
+ test_id_validated = validate_id(test_id, "test")
329
+
330
+ async with client:
331
+ # Apply token from config if available
332
+ if token:
333
+ initialize_client_with_token(client, token)
334
+ else:
335
+ await client.ensure_authenticated()
336
+
337
+ # Get the test to fetch its features
338
+ test = await client.tests.get_one(test_id_validated)
339
+
340
+ # Generate solution
341
+ solution = await client.tests.solve(test_id_validated)
342
+
343
+ # Save to file if requested
344
+ if output_file:
345
+ with open(output_file, "w") as f:
346
+ if isinstance(solution, dict):
347
+ json.dump(solution, f, indent=2)
348
+ else:
349
+ f.write(str(solution))
350
+ console.print(f"[green]Solution saved to: {output_file}[/green]")
351
+
352
+ return solution
353
+
354
+ result = asyncio.run(_run())
355
+ console.print("[green]Solution generated successfully[/green]")
356
+ format_output(result, ctx.obj["FORMAT"])
357
+
358
+
359
+ @tests_group.command(name="delete")
360
+ @click.argument("test_id")
361
+ @click.confirmation_option(prompt="Are you sure you want to delete this test?")
362
+ @click.pass_context
363
+ def delete_test(ctx, test_id):
364
+ """Delete a test"""
365
+
366
+ async def _run():
367
+ config, token = get_client_config(
368
+ ctx.obj["PROFILE"], api_url=ctx.obj.get("API_URL")
369
+ )
370
+ client = TestZeusClient(**config)
371
+
372
+ test_id_validated = validate_id(test_id, "test")
373
+
374
+ async with client:
375
+ # Apply token from config if available
376
+ if token:
377
+ initialize_client_with_token(client, token)
378
+ else:
379
+ await client.ensure_authenticated()
380
+
381
+ success = await client.tests.delete(test_id_validated)
382
+ return {"success": success, "id": test_id_validated}
383
+
384
+ try:
385
+ result = asyncio.run(_run())
386
+ console.print(f"[green]Test deleted successfully: {result['id']}[/green]")
387
+ except Exception as e:
388
+ console.print(f"[red]Error deleting test:[/red] {str(e)}")
389
+ exit(1)