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.
testzeus_cli/config.py ADDED
@@ -0,0 +1,145 @@
1
+ """
2
+ Configuration management for TestZeus CLI.
3
+ """
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Dict, Any, Optional, Tuple
8
+
9
+ try:
10
+ import yaml
11
+ import keyring
12
+ except ImportError:
13
+ # Handle case where optional dependencies aren't installed
14
+ pass
15
+
16
+ # Config directory and file paths
17
+ CONFIG_DIR = Path.home() / ".testzeus"
18
+ CONFIG_FILE = CONFIG_DIR / "config.yaml"
19
+ KEYRING_SERVICE = "testzeus-cli"
20
+
21
+
22
+ def ensure_config_dir() -> None:
23
+ """Ensure config directory exists"""
24
+ CONFIG_DIR.mkdir(exist_ok=True)
25
+
26
+
27
+ def get_config_path() -> Path:
28
+ """Get the path to the config file"""
29
+ ensure_config_dir()
30
+ return CONFIG_FILE
31
+
32
+
33
+ def load_config() -> Dict[str, Any]:
34
+ """Load config from file"""
35
+ config_path = get_config_path()
36
+
37
+ if not config_path.exists():
38
+ # Create default config
39
+ default_config = {"default": {"api_url": "https://pb.prod.testzeus.app"}}
40
+ with open(config_path, "w") as f:
41
+ yaml.dump(default_config, f)
42
+ return default_config
43
+
44
+ with open(config_path, "r") as f:
45
+ return yaml.safe_load(f) or {}
46
+
47
+
48
+ def save_config(config: Dict[str, Any]) -> None:
49
+ """Save config to file"""
50
+ config_path = get_config_path()
51
+
52
+ with open(config_path, "w") as f:
53
+ yaml.dump(config, f)
54
+
55
+
56
+ def get_profile_config(profile: str = "default") -> Dict[str, Any]:
57
+ """Get config for a specific profile"""
58
+ config = load_config()
59
+
60
+ if profile not in config:
61
+ config[profile] = {"api_url": "https://pb.prod.testzeus.app"}
62
+ save_config(config)
63
+
64
+ return config[profile]
65
+
66
+
67
+ def update_config(profile: str, updates: Dict[str, Any]) -> None:
68
+ """Update config for a specific profile"""
69
+ config = load_config()
70
+
71
+ if profile not in config:
72
+ config[profile] = {}
73
+
74
+ for key, value in updates.items():
75
+ if key == "password":
76
+ # Store password in keyring
77
+ keyring.set_password(KEYRING_SERVICE, f"{profile}:password", value)
78
+ else:
79
+ config[profile][key] = value
80
+
81
+ save_config(config)
82
+
83
+
84
+ def get_client_config(
85
+ profile: str = "default", api_url: Optional[str] = None
86
+ ) -> Tuple[Dict[str, Any], Optional[str]]:
87
+ """
88
+ Get config for creating a TestZeusClient and the saved token if available
89
+
90
+ Args:
91
+ profile: Configuration profile to use
92
+ api_url: Optional API URL to override profile setting
93
+
94
+ Returns:
95
+ A tuple of (client_config, token) where token may be None
96
+ """
97
+ profile_config = get_profile_config(profile)
98
+
99
+ client_config: Dict[str, Any] = {}
100
+ token = None
101
+
102
+ # Use provided API URL or fall back to profile config
103
+ if api_url:
104
+ client_config["base_url"] = api_url
105
+ elif "api_url" in profile_config:
106
+ client_config["base_url"] = profile_config.get("api_url")
107
+
108
+ # Add email if present in config
109
+ if "email" in profile_config:
110
+ client_config["email"] = profile_config.get("email")
111
+
112
+ # Get token if available, but don't add to client_config
113
+ # as the SDK doesn't accept it as a constructor parameter
114
+ if "token" in profile_config:
115
+ token = profile_config.get("token")
116
+
117
+ # Try to get password from keyring
118
+ try:
119
+ password = keyring.get_password(KEYRING_SERVICE, f"{profile}:password")
120
+ if password:
121
+ client_config["password"] = password
122
+ except Exception:
123
+ # Ignore keyring errors - password will need to be provided another way
124
+ pass
125
+
126
+ return client_config, token
127
+
128
+
129
+ def clear_auth_data(profile: str = "default") -> None:
130
+ """Clear authentication data for a profile"""
131
+ config = load_config()
132
+
133
+ if profile in config:
134
+ # Remove token if present
135
+ if "token" in config[profile]:
136
+ del config[profile]["token"]
137
+
138
+ # Try to remove password from keyring
139
+ try:
140
+ keyring.delete_password(KEYRING_SERVICE, f"{profile}:password")
141
+ except Exception:
142
+ # Ignore keyring errors
143
+ pass
144
+
145
+ save_config(config)
@@ -0,0 +1,7 @@
1
+ """
2
+ Utility modules for TestZeus CLI.
3
+ """
4
+
5
+ from testzeus_cli.utils.formatters import format_output
6
+ from testzeus_cli.utils.validators import validate_id, parse_key_value_pairs
7
+ from testzeus_cli.utils.client import run_client_operation, with_authenticated_client
@@ -0,0 +1,100 @@
1
+ """
2
+ Authentication utility functions for the TestZeus CLI.
3
+ """
4
+
5
+ import base64
6
+ import json
7
+ from testzeus_sdk import TestZeusClient
8
+ from typing import Dict, Any, Optional, cast
9
+
10
+
11
+ def decode_jwt_payload(token: str) -> Optional[Dict[str, Any]]:
12
+ """
13
+ Decode a JWT token payload.
14
+
15
+ Args:
16
+ token: The JWT token
17
+
18
+ Returns:
19
+ Decoded payload as a dictionary, or None if decoding fails
20
+ """
21
+ try:
22
+ # For JWT tokens
23
+ token_parts = token.split(".")
24
+ if len(token_parts) == 3: # Standard JWT format
25
+ # Decode the payload (middle part)
26
+ payload = token_parts[1]
27
+ # Add padding if needed
28
+ padding = "=" * (4 - len(payload) % 4)
29
+ payload += padding
30
+ # Decode from base64
31
+ decoded = base64.b64decode(payload.replace("-", "+").replace("_", "/"))
32
+ return cast(Dict[str, Any], json.loads(decoded))
33
+ except Exception:
34
+ pass
35
+
36
+ return None
37
+
38
+
39
+ def initialize_client_with_token(client: TestZeusClient, token: str) -> None:
40
+ """
41
+ Initialize a TestZeusClient with a token, properly setting up the auth store model.
42
+
43
+ Args:
44
+ client: The TestZeusClient instance
45
+ token: JWT token
46
+ """
47
+ # Set the token
48
+ client.token = token
49
+ client._authenticated = True
50
+
51
+ # Extract token data
52
+ claims = decode_jwt_payload(token)
53
+ tenant_id = None
54
+
55
+ if claims:
56
+ # Check for tenant ID in various possible locations within the token
57
+ if "tenant" in claims:
58
+ tenant_id = claims["tenant"]
59
+ elif "record" in claims and "tenant" in claims["record"]:
60
+ tenant_id = claims["record"]["tenant"]
61
+ elif "collectionId" in claims:
62
+ # Use collection ID as a fallback
63
+ tenant_id = claims["collectionId"]
64
+
65
+ # If no tenant ID found in token, use the default
66
+ if not tenant_id:
67
+ tenant_id = "pbc_138639755" # Default tenant ID for TestZeus
68
+
69
+ # Save the token to the auth store - don't try to set the model property directly
70
+ # as it's read-only. Instead, just save the token and let PocketBase handle it.
71
+ client.pb.auth_store.save(token, None)
72
+
73
+ # Add tenant ID directly to the client for easy access
74
+ # This is the important part - ensure the tenant ID is accessible
75
+ setattr(client, "_tenant_id", tenant_id)
76
+
77
+
78
+ def extract_tenant_from_token(token: str) -> str:
79
+ """
80
+ Extract tenant ID from a JWT token.
81
+
82
+ Args:
83
+ token: The JWT token
84
+
85
+ Returns:
86
+ Tenant ID or default ID if not found
87
+ """
88
+ claims = decode_jwt_payload(token)
89
+
90
+ if claims:
91
+ # Check for tenant ID in various possible locations
92
+ if "tenant" in claims:
93
+ return str(claims["tenant"])
94
+ elif "record" in claims and "tenant" in claims["record"]:
95
+ return str(claims["record"]["tenant"])
96
+ elif "collectionId" in claims:
97
+ return str(claims["collectionId"])
98
+
99
+ # Default tenant ID for TestZeus
100
+ return "pbc_138639755"
@@ -0,0 +1,60 @@
1
+ """
2
+ Client utility functions for TestZeus CLI.
3
+ """
4
+
5
+ import asyncio
6
+ from typing import Dict, Any, Optional, Callable, TypeVar, Awaitable, cast, Dict
7
+
8
+ from testzeus_sdk import TestZeusClient
9
+ from testzeus_cli.config import get_client_config
10
+ from testzeus_cli.utils.auth import initialize_client_with_token
11
+
12
+ T = TypeVar("T")
13
+
14
+
15
+ async def with_authenticated_client(
16
+ profile: str,
17
+ api_url: Optional[str],
18
+ operation: Callable[[TestZeusClient], Awaitable[T]],
19
+ ) -> T:
20
+ """
21
+ Execute an operation with an authenticated client
22
+
23
+ Args:
24
+ profile: Configuration profile to use
25
+ api_url: Optional API URL to override profile setting
26
+ operation: Async function that takes a TestZeusClient and returns a value
27
+
28
+ Returns:
29
+ The result of the operation
30
+ """
31
+ config, token = get_client_config(profile, api_url)
32
+ client = TestZeusClient(**config)
33
+
34
+ async with client:
35
+ # Apply token from config if available
36
+ if token:
37
+ initialize_client_with_token(client, token)
38
+ else:
39
+ await client.ensure_authenticated()
40
+
41
+ return await operation(client)
42
+
43
+
44
+ def run_client_operation(
45
+ ctx: Dict[str, Any], operation: Callable[[TestZeusClient], Awaitable[T]]
46
+ ) -> T:
47
+ """
48
+ Run an operation with a client using the context configuration
49
+
50
+ Args:
51
+ ctx: Click context object with configuration
52
+ operation: Async function that takes a TestZeusClient and returns a value
53
+
54
+ Returns:
55
+ The result of the operation
56
+ """
57
+ profile = ctx.obj["PROFILE"]
58
+ api_url = ctx.obj.get("API_URL")
59
+
60
+ return asyncio.run(with_authenticated_client(profile, api_url, operation))
@@ -0,0 +1,289 @@
1
+ """
2
+ Output formatting utilities for TestZeus CLI.
3
+ """
4
+
5
+ import json
6
+ import yaml
7
+ from typing import Any, Dict, List, Optional, Set
8
+ from rich.console import Console
9
+ from rich.table import Table
10
+
11
+ console = Console()
12
+
13
+ # Fields to completely exclude from display
14
+ EXCLUDED_FIELDS = {
15
+ "collectionId",
16
+ "collection",
17
+ "collectionName",
18
+ "collection_id",
19
+ "collection_name",
20
+ }
21
+
22
+
23
+ def format_output(data: Any, format_type: str = "table") -> None:
24
+ """
25
+ Format and print output based on the specified format type
26
+
27
+ Args:
28
+ data: Data to format (dict, list, or primitive)
29
+ format_type: Output format type ("table", "json", or "yaml")
30
+ """
31
+ if format_type == "json":
32
+ console.print(json.dumps(data, indent=2, default=format_object_for_json))
33
+ elif format_type == "yaml":
34
+ console.print(yaml.dump(data, sort_keys=False, default_flow_style=False))
35
+ else: # table format
36
+ if isinstance(data, dict):
37
+ format_dict_as_table(data)
38
+ elif isinstance(data, list):
39
+ format_list_as_table(data)
40
+ else:
41
+ # Simple value, just print it
42
+ console.print(str(data))
43
+
44
+
45
+ def format_object_for_json(obj: Any) -> Any:
46
+ """
47
+ Format complex objects for JSON serialization
48
+
49
+ Args:
50
+ obj: Object to format
51
+
52
+ Returns:
53
+ JSON serializable representation of the object
54
+ """
55
+ # If the object has a data property (like SDK models)
56
+ if hasattr(obj, "data") and isinstance(obj.data, dict):
57
+ return obj.data
58
+
59
+ # If the object has __dict__
60
+ if hasattr(obj, "__dict__"):
61
+ return obj.__dict__
62
+
63
+ # Default to string representation
64
+ return str(obj)
65
+
66
+
67
+ def format_value_for_display(value: Any) -> str:
68
+ """
69
+ Format a value for display in table output
70
+
71
+ Args:
72
+ value: Value to format
73
+
74
+ Returns:
75
+ String representation suitable for display
76
+ """
77
+ # If value is a dictionary with id/name fields, show a friendly representation
78
+ if isinstance(value, dict) and "id" in value:
79
+ if "name" in value:
80
+ return f"{value['name']} ({value['id']})"
81
+ return f"ID: {value['id']}"
82
+
83
+ # If value is a list of dictionaries with ids, summarize
84
+ if (
85
+ isinstance(value, list)
86
+ and value
87
+ and all(isinstance(x, dict) and "id" in x for x in value)
88
+ ):
89
+ if len(value) == 1 and "name" in value[0]:
90
+ return f"{value[0]['name']} ({value[0]['id']})"
91
+ return f"{len(value)} items"
92
+
93
+ # If value is a list of strings
94
+ if isinstance(value, list) and value and all(isinstance(x, str) for x in value):
95
+ if len(value) <= 3:
96
+ return ", ".join(value)
97
+ return f"{len(value)} items: {', '.join(value[:2])}..."
98
+
99
+ # If value has a data attribute
100
+ if hasattr(value, "data") and isinstance(value.data, dict):
101
+ data = value.data
102
+ if "name" in data and "id" in data:
103
+ return f"{data['name']} ({data['id']})"
104
+ elif "id" in data:
105
+ return f"ID: {data['id']}"
106
+
107
+ # Format nested structures
108
+ if isinstance(value, dict) or isinstance(value, list):
109
+ try:
110
+ json_str = json.dumps(value, default=format_object_for_json)
111
+ if len(json_str) > 50 and not (isinstance(value, dict) and "id" in value):
112
+ return f"{json_str[:50]}..."
113
+ return json_str
114
+ except:
115
+ return str(value)
116
+
117
+ # Default string representation
118
+ return str(value)
119
+
120
+
121
+ def format_dict_as_table(data: Dict[str, Any], title: Optional[str] = None) -> None:
122
+ """
123
+ Format a dictionary as a table
124
+
125
+ Args:
126
+ data: Dictionary to format
127
+ title: Optional table title
128
+ """
129
+ # Special handling for paginated responses
130
+ if "items" in data and isinstance(data["items"], list):
131
+ # Print pagination info
132
+ if "page" in data and "per_page" in data and "total_items" in data:
133
+ console.print(
134
+ f"Page {data['page']} of {(data['total_items'] + data['per_page'] - 1) // data['per_page']} "
135
+ f"(showing {len(data['items'])} of {data['total_items']} items)"
136
+ )
137
+
138
+ # Format the items
139
+ format_list_as_table(data["items"], title)
140
+ return
141
+
142
+ # Standard dictionary rendering
143
+ table = Table(title=title)
144
+ table.add_column("Key", style="cyan")
145
+ table.add_column("Value")
146
+
147
+ for key, value in data.items():
148
+ # Skip excluded fields
149
+ if key.lower() in EXCLUDED_FIELDS or any(
150
+ excluded in key.lower() for excluded in EXCLUDED_FIELDS
151
+ ):
152
+ continue
153
+
154
+ # Format the value for display
155
+ value_str = format_value_for_display(value)
156
+ table.add_row(key, value_str)
157
+
158
+ console.print(table)
159
+
160
+
161
+ def format_list_as_table(data: List[Any], title: Optional[str] = None) -> None:
162
+ """
163
+ Format a list as a table
164
+
165
+ Args:
166
+ data: List to format
167
+ title: Optional table title
168
+ """
169
+ if not data:
170
+ console.print("[yellow]No data available[/yellow]")
171
+ return
172
+
173
+ # Get all keys from all dictionaries
174
+ all_keys: Set[str] = set()
175
+ for item in data:
176
+ if isinstance(item, dict):
177
+ all_keys.update(item.keys())
178
+ elif hasattr(item, "data") and isinstance(item.data, dict):
179
+ all_keys.update(item.data.keys())
180
+
181
+ # Remove excluded fields
182
+ for field in list(all_keys):
183
+ if field.lower() in EXCLUDED_FIELDS or any(
184
+ excluded in field.lower() for excluded in EXCLUDED_FIELDS
185
+ ):
186
+ all_keys.discard(field)
187
+
188
+ # If list of dictionaries
189
+ if all_keys:
190
+ # Create table with columns for each key
191
+ table = Table(title=title, show_lines=True)
192
+
193
+ # Keep table manageable - use most common/important fields
194
+ # Prioritize certain fields - order determines display order
195
+ priority_fields = [
196
+ "id",
197
+ "name",
198
+ "status",
199
+ "created",
200
+ "updated",
201
+ "start_time",
202
+ "end_time",
203
+ "test", # Add test reference
204
+ "duration", # Add test duration
205
+ "tenant", # Add tenant reference
206
+ ]
207
+
208
+ # Limit max columns to make output more readable
209
+ max_display_columns = 6 # Reduce from 10 to 6 for better readability
210
+
211
+ # First ensure we have id and name if they exist
212
+ filtered_keys = set()
213
+ for key in ["id", "name"]:
214
+ if key in all_keys:
215
+ filtered_keys.add(key)
216
+
217
+ # Then add other priority fields until we reach the limit
218
+ for key in priority_fields:
219
+ if (
220
+ key in all_keys
221
+ and key not in filtered_keys
222
+ and len(filtered_keys) < max_display_columns
223
+ ):
224
+ filtered_keys.add(key)
225
+
226
+ # If we still have room, add some non-priority fields
227
+ if len(filtered_keys) < max_display_columns:
228
+ remaining_keys = sorted(list(all_keys - filtered_keys))
229
+ remaining_keys = remaining_keys[: max_display_columns - len(filtered_keys)]
230
+ filtered_keys.update(remaining_keys)
231
+
232
+ # Sort columns with priority fields first
233
+ columns = sorted(
234
+ filtered_keys,
235
+ key=lambda x: (priority_fields.index(x) if x in priority_fields else 999,),
236
+ )
237
+
238
+ # Add columns to table with appropriate width for IDs
239
+ for key in columns:
240
+ if key == "id":
241
+ # For ID column: full width, no wrap, no justify
242
+ table.add_column("ID", min_width=30, max_width=30, no_wrap=True)
243
+ elif key == "name":
244
+ # For name column: more space, allow wrap
245
+ table.add_column("Name", min_width=40, max_width=40, overflow="fold")
246
+ elif key == "status":
247
+ # For status: smaller fixed width
248
+ table.add_column("Status", min_width=10, max_width=10, justify="center")
249
+ else:
250
+ # For other columns: standard format
251
+ table.add_column(key.capitalize(), width=20, overflow="ellipsis")
252
+
253
+ # Add rows
254
+ for item in data:
255
+ # Handle both dict items and objects with data attribute
256
+ item_data = item
257
+ if hasattr(item, "data") and isinstance(item.data, dict):
258
+ item_data = item.data
259
+
260
+ if isinstance(item_data, dict):
261
+ # Extract values for each column
262
+ row_values = []
263
+ for key in columns:
264
+ if key in item_data:
265
+ value = item_data.get(key, "")
266
+ # Format for display
267
+ formatted_value = format_value_for_display(value)
268
+ # For IDs, don't truncate
269
+ if key == "id" and value:
270
+ formatted_value = str(value)
271
+ else:
272
+ formatted_value = ""
273
+ row_values.append(formatted_value)
274
+
275
+ table.add_row(*row_values)
276
+ else:
277
+ # Item isn't a dict, just add as a single column
278
+ table.add_row(str(item))
279
+
280
+ console.print(table)
281
+ else:
282
+ # Simple list of primitive values
283
+ table = Table(title=title)
284
+ table.add_column("Value")
285
+
286
+ for item in data:
287
+ table.add_row(str(item))
288
+
289
+ console.print(table)
@@ -0,0 +1,70 @@
1
+ """
2
+ Input validation utilities for TestZeus CLI.
3
+ """
4
+
5
+ from typing import Any, Dict, List, Optional, Union, TypeVar, Callable
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ def validate_required_arg(value: Optional[T], name: str) -> T:
11
+ """
12
+ Validate that a required argument is provided
13
+
14
+ Args:
15
+ value: Argument value to validate
16
+ name: Name of the argument for error message
17
+
18
+ Returns:
19
+ The value if valid
20
+
21
+ Raises:
22
+ ValueError: If the value is None
23
+ """
24
+ if value is None:
25
+ raise ValueError(f"Required argument '{name}' is missing")
26
+ return value
27
+
28
+
29
+ def validate_id(id_value: str, entity_type: str = "entity") -> str:
30
+ """
31
+ Validate that an ID is in the correct format
32
+
33
+ Args:
34
+ id_value: ID value to validate
35
+ entity_type: Type of entity for error message
36
+
37
+ Returns:
38
+ The validated ID
39
+
40
+ Raises:
41
+ ValueError: If the ID is invalid
42
+ """
43
+ if not id_value or not isinstance(id_value, str):
44
+ raise ValueError(f"Invalid {entity_type} ID")
45
+ return id_value.strip()
46
+
47
+
48
+ def parse_key_value_pairs(pairs: List[str]) -> Dict[str, str]:
49
+ """
50
+ Parse a list of key=value pairs into a dictionary
51
+
52
+ Args:
53
+ pairs: List of strings in 'key=value' format
54
+
55
+ Returns:
56
+ Dictionary of parsed key-value pairs
57
+
58
+ Raises:
59
+ ValueError: If any pair doesn't follow the key=value format
60
+ """
61
+ result = {}
62
+ for pair in pairs:
63
+ try:
64
+ key, value = pair.split("=", 1)
65
+ result[key.strip()] = value.strip()
66
+ except ValueError:
67
+ raise ValueError(
68
+ f"Invalid format for key-value pair: '{pair}'. Expected 'key=value'"
69
+ )
70
+ return result
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 TestZeus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.