testzeus-sdk 0.0.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.
- testzeus_sdk/__init__.py +12 -0
- testzeus_sdk/client.py +308 -0
- testzeus_sdk/managers/__init__.py +24 -0
- testzeus_sdk/managers/agent_configs_manager.py +44 -0
- testzeus_sdk/managers/base.py +304 -0
- testzeus_sdk/managers/environment_manager.py +144 -0
- testzeus_sdk/managers/tag_manager.py +94 -0
- testzeus_sdk/managers/tags_manager.py +43 -0
- testzeus_sdk/managers/tenant_consumption_logs_manager.py +44 -0
- testzeus_sdk/managers/tenant_consumption_manager.py +43 -0
- testzeus_sdk/managers/tenants_manager.py +42 -0
- testzeus_sdk/managers/test_data_manager.py +75 -0
- testzeus_sdk/managers/test_designs_manager.py +46 -0
- testzeus_sdk/managers/test_device_manager.py +44 -0
- testzeus_sdk/managers/test_manager.py +247 -0
- testzeus_sdk/managers/test_run_dash_output_steps_manager.py +45 -0
- testzeus_sdk/managers/test_run_dash_outputs_attachments_manager.py +107 -0
- testzeus_sdk/managers/test_run_dash_outputs_manager.py +45 -0
- testzeus_sdk/managers/test_run_dashs_manager.py +70 -0
- testzeus_sdk/managers/test_run_manager.py +150 -0
- testzeus_sdk/managers/test_run_reports_manager.py +45 -0
- testzeus_sdk/managers/test_runs_manager.py +49 -0
- testzeus_sdk/managers/test_runs_stage_manager.py +49 -0
- testzeus_sdk/managers/tests_manager.py +73 -0
- testzeus_sdk/managers/users_manager.py +42 -0
- testzeus_sdk/models/__init__.py +24 -0
- testzeus_sdk/models/agent_configs.py +31 -0
- testzeus_sdk/models/base.py +55 -0
- testzeus_sdk/models/environment.py +61 -0
- testzeus_sdk/models/tag.py +30 -0
- testzeus_sdk/models/tags.py +26 -0
- testzeus_sdk/models/tenant_consumption.py +34 -0
- testzeus_sdk/models/tenant_consumption_logs.py +30 -0
- testzeus_sdk/models/tenants.py +30 -0
- testzeus_sdk/models/test.py +65 -0
- testzeus_sdk/models/test_data.py +71 -0
- testzeus_sdk/models/test_designs.py +31 -0
- testzeus_sdk/models/test_device.py +47 -0
- testzeus_sdk/models/test_run.py +104 -0
- testzeus_sdk/models/test_run_dash_output_steps.py +40 -0
- testzeus_sdk/models/test_run_dash_outputs.py +30 -0
- testzeus_sdk/models/test_run_dash_outputs_attachments.py +32 -0
- testzeus_sdk/models/test_run_dashs.py +34 -0
- testzeus_sdk/models/test_run_reports.py +31 -0
- testzeus_sdk/models/test_runs.py +38 -0
- testzeus_sdk/models/test_runs_stage.py +38 -0
- testzeus_sdk/models/tests.py +34 -0
- testzeus_sdk/models/users.py +37 -0
- testzeus_sdk/utils/__init__.py +3 -0
- testzeus_sdk/utils/helpers.py +110 -0
- testzeus_sdk/utils/schema_generator.py +363 -0
- testzeus_sdk-0.0.1.dist-info/LICENSE +21 -0
- testzeus_sdk-0.0.1.dist-info/METADATA +323 -0
- testzeus_sdk-0.0.1.dist-info/RECORD +55 -0
- testzeus_sdk-0.0.1.dist-info/WHEEL +4 -0
testzeus_sdk/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TestZeus SDK for Python.
|
|
3
|
+
|
|
4
|
+
This SDK provides a simple interface to interact with TestZeus testing platform.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
|
|
9
|
+
from testzeus_sdk.client import TestZeusClient
|
|
10
|
+
|
|
11
|
+
# Provide a simple alias for the client
|
|
12
|
+
Client = TestZeusClient
|
testzeus_sdk/client.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Main client class for TestZeus SDK.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import json
|
|
7
|
+
import aiohttp
|
|
8
|
+
import asyncio
|
|
9
|
+
from typing import Dict, Any, Optional, List, Union
|
|
10
|
+
from pocketbase import PocketBase
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TestZeusClient:
|
|
14
|
+
"""
|
|
15
|
+
Client for interacting with TestZeus API.
|
|
16
|
+
|
|
17
|
+
This client wraps the PocketBase client and provides access to all TestZeus
|
|
18
|
+
functionality through specialized managers for each entity type.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
base_url: Optional[str] = None,
|
|
24
|
+
email: Optional[str] = None,
|
|
25
|
+
password: Optional[str] = None,
|
|
26
|
+
):
|
|
27
|
+
"""
|
|
28
|
+
Initialize the TestZeus client
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
base_url: TestZeus API base URL
|
|
32
|
+
email: User email for authentication
|
|
33
|
+
password: User password for authentication
|
|
34
|
+
"""
|
|
35
|
+
default_url = "https://pb.prod.testzeus.app"
|
|
36
|
+
self.base_url = base_url or os.environ.get("TESTZEUS_BASE_URL", default_url)
|
|
37
|
+
if self.base_url:
|
|
38
|
+
self.base_url = self.base_url.rstrip("/")
|
|
39
|
+
self.email = email or os.environ.get("TESTZEUS_EMAIL")
|
|
40
|
+
self.password = password or os.environ.get("TESTZEUS_PASSWORD")
|
|
41
|
+
|
|
42
|
+
# Initialize the PocketBase client
|
|
43
|
+
self.pb = PocketBase(self.base_url)
|
|
44
|
+
|
|
45
|
+
# Auth token and session
|
|
46
|
+
self.token = None
|
|
47
|
+
self.session = None
|
|
48
|
+
self._authenticated = False
|
|
49
|
+
|
|
50
|
+
# Import here to avoid circular imports
|
|
51
|
+
from testzeus_sdk.managers.test_manager import TestManager
|
|
52
|
+
from testzeus_sdk.managers.test_run_manager import TestRunManager
|
|
53
|
+
from testzeus_sdk.managers.test_data_manager import TestDataManager
|
|
54
|
+
from testzeus_sdk.managers.environment_manager import EnvironmentManager
|
|
55
|
+
from testzeus_sdk.managers.tag_manager import TagManager
|
|
56
|
+
|
|
57
|
+
# Import new managers
|
|
58
|
+
from testzeus_sdk.managers.agent_configs_manager import AgentConfigsManager
|
|
59
|
+
from testzeus_sdk.managers.test_device_manager import TestDeviceManager
|
|
60
|
+
from testzeus_sdk.managers.test_designs_manager import TestDesignsManager
|
|
61
|
+
from testzeus_sdk.managers.test_run_dashs_manager import TestRunDashsManager
|
|
62
|
+
from testzeus_sdk.managers.test_run_dash_outputs_manager import (
|
|
63
|
+
TestRunDashOutputsManager,
|
|
64
|
+
)
|
|
65
|
+
from testzeus_sdk.managers.test_run_dash_output_steps_manager import (
|
|
66
|
+
TestRunDashOutputStepsManager,
|
|
67
|
+
)
|
|
68
|
+
from testzeus_sdk.managers.tenant_consumption_manager import (
|
|
69
|
+
TenantConsumptionManager,
|
|
70
|
+
)
|
|
71
|
+
from testzeus_sdk.managers.tenant_consumption_logs_manager import (
|
|
72
|
+
TenantConsumptionLogsManager,
|
|
73
|
+
)
|
|
74
|
+
from testzeus_sdk.managers.test_run_dash_outputs_attachments_manager import (
|
|
75
|
+
TestRunDashOutputsAttachmentsManager
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
# Initialize managers
|
|
79
|
+
self.tests = TestManager(self)
|
|
80
|
+
self.test_runs = TestRunManager(self)
|
|
81
|
+
self.test_data = TestDataManager(self)
|
|
82
|
+
self.environments = EnvironmentManager(self)
|
|
83
|
+
self.tags = TagManager(self)
|
|
84
|
+
|
|
85
|
+
# Initialize new managers
|
|
86
|
+
self.agent_configs = AgentConfigsManager(self)
|
|
87
|
+
self.test_devices = TestDeviceManager(self)
|
|
88
|
+
self.test_designs = TestDesignsManager(self)
|
|
89
|
+
self.test_run_dashs = TestRunDashsManager(self)
|
|
90
|
+
self.test_run_dash_outputs = TestRunDashOutputsManager(self)
|
|
91
|
+
self.test_run_dash_output_steps = TestRunDashOutputStepsManager(self)
|
|
92
|
+
self.tenant_consumption = TenantConsumptionManager(self)
|
|
93
|
+
self.tenant_consumption_logs = TenantConsumptionLogsManager(self)
|
|
94
|
+
self.test_run_dash_outputs_attachments = TestRunDashOutputsAttachmentsManager(self)
|
|
95
|
+
|
|
96
|
+
async def __aenter__(self) -> "TestZeusClient":
|
|
97
|
+
"""Context manager entry point"""
|
|
98
|
+
if self.session is None:
|
|
99
|
+
self.session = aiohttp.ClientSession()
|
|
100
|
+
return self
|
|
101
|
+
|
|
102
|
+
async def __aexit__(
|
|
103
|
+
self,
|
|
104
|
+
exc_type: Optional[type],
|
|
105
|
+
exc_val: Optional[Exception],
|
|
106
|
+
exc_tb: Optional[asyncio.Task],
|
|
107
|
+
) -> None:
|
|
108
|
+
"""Context manager exit point"""
|
|
109
|
+
if self.session and not self.session.closed:
|
|
110
|
+
await self.session.close()
|
|
111
|
+
self.session = None
|
|
112
|
+
|
|
113
|
+
async def ensure_authenticated(self) -> None:
|
|
114
|
+
"""
|
|
115
|
+
Ensure the client is authenticated before making API calls
|
|
116
|
+
"""
|
|
117
|
+
if self._authenticated:
|
|
118
|
+
# Make sure PocketBase client has the token
|
|
119
|
+
if self.token and not self.pb.auth_store.token:
|
|
120
|
+
self.pb.auth_store.save(self.token, None)
|
|
121
|
+
return
|
|
122
|
+
|
|
123
|
+
if self.session is None:
|
|
124
|
+
self.session = aiohttp.ClientSession()
|
|
125
|
+
|
|
126
|
+
if self.email and self.password:
|
|
127
|
+
# Username/password authentication
|
|
128
|
+
await self.authenticate(self.email, self.password)
|
|
129
|
+
else:
|
|
130
|
+
raise ValueError(
|
|
131
|
+
"Authentication credentials not provided. "
|
|
132
|
+
"Set email/password via constructor or environment variables."
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
async def authenticate(self, email: str, password: str) -> str:
|
|
136
|
+
"""
|
|
137
|
+
Authenticate with email and password
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
email: User email
|
|
141
|
+
password: User password
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
Authentication token
|
|
145
|
+
"""
|
|
146
|
+
if self.session is None:
|
|
147
|
+
self.session = aiohttp.ClientSession()
|
|
148
|
+
|
|
149
|
+
# First authenticate with PocketBase client
|
|
150
|
+
try:
|
|
151
|
+
auth_data = self.pb.collection("users").auth_with_password(email, password)
|
|
152
|
+
self.token = auth_data.token
|
|
153
|
+
self._authenticated = True
|
|
154
|
+
return self.token
|
|
155
|
+
except Exception as e:
|
|
156
|
+
# Fallback to our own authentication if PocketBase client fails
|
|
157
|
+
auth_url = f"{self.base_url}/api/collections/users/auth-with-password"
|
|
158
|
+
auth_data = {
|
|
159
|
+
"identity": email,
|
|
160
|
+
"password": password,
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async with self.session.post(auth_url, json=auth_data) as response:
|
|
164
|
+
if response.status != 200:
|
|
165
|
+
error_text = await response.text()
|
|
166
|
+
raise ValueError(f"Authentication failed: {error_text}")
|
|
167
|
+
|
|
168
|
+
data = await response.json()
|
|
169
|
+
self.token = data.get("token")
|
|
170
|
+
|
|
171
|
+
if not self.token:
|
|
172
|
+
raise ValueError("Authentication succeeded but no token was returned")
|
|
173
|
+
|
|
174
|
+
self._authenticated = True
|
|
175
|
+
return self.token
|
|
176
|
+
|
|
177
|
+
def _get_headers(self) -> Dict[str, str]:
|
|
178
|
+
"""
|
|
179
|
+
Get headers for API requests
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
Dictionary of HTTP headers
|
|
183
|
+
"""
|
|
184
|
+
headers = {
|
|
185
|
+
"Content-Type": "application/json",
|
|
186
|
+
"Accept": "application/json",
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if self.token:
|
|
190
|
+
# Token auth from login
|
|
191
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
192
|
+
|
|
193
|
+
return headers
|
|
194
|
+
|
|
195
|
+
async def request(
|
|
196
|
+
self,
|
|
197
|
+
method: str,
|
|
198
|
+
endpoint: str,
|
|
199
|
+
params: Optional[Dict[str, Any]] = None,
|
|
200
|
+
json_data: Optional[Dict[str, Any]] = None,
|
|
201
|
+
data: Optional[Any] = None,
|
|
202
|
+
) -> Any:
|
|
203
|
+
"""
|
|
204
|
+
Make an API request
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
method: HTTP method (GET, POST, PATCH, DELETE)
|
|
208
|
+
endpoint: API endpoint (starting with /)
|
|
209
|
+
params: Query parameters
|
|
210
|
+
json_data: JSON body for POST/PATCH requests
|
|
211
|
+
data: Form data for POST requests
|
|
212
|
+
|
|
213
|
+
Returns:
|
|
214
|
+
API response as dictionary
|
|
215
|
+
"""
|
|
216
|
+
await self.ensure_authenticated()
|
|
217
|
+
|
|
218
|
+
if self.session is None:
|
|
219
|
+
self.session = aiohttp.ClientSession()
|
|
220
|
+
|
|
221
|
+
url = f"{self.base_url}{endpoint}"
|
|
222
|
+
headers = self._get_headers()
|
|
223
|
+
|
|
224
|
+
async with self.session.request(
|
|
225
|
+
method=method,
|
|
226
|
+
url=url,
|
|
227
|
+
params=params,
|
|
228
|
+
json=json_data,
|
|
229
|
+
data=data,
|
|
230
|
+
headers=headers,
|
|
231
|
+
) as response:
|
|
232
|
+
response_text = await response.text()
|
|
233
|
+
|
|
234
|
+
if not response_text:
|
|
235
|
+
# Handle empty responses
|
|
236
|
+
if 200 <= response.status < 300:
|
|
237
|
+
return {}
|
|
238
|
+
else:
|
|
239
|
+
raise ValueError(
|
|
240
|
+
f"Request failed with status {response.status}: Empty response"
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
try:
|
|
244
|
+
import json as json_module
|
|
245
|
+
|
|
246
|
+
response_json = json_module.loads(response_text)
|
|
247
|
+
except ValueError:
|
|
248
|
+
if 200 <= response.status < 300:
|
|
249
|
+
# Success with non-JSON response
|
|
250
|
+
return {"data": response_text}
|
|
251
|
+
else:
|
|
252
|
+
# Error with non-JSON response
|
|
253
|
+
raise ValueError(
|
|
254
|
+
f"Request failed with status {response.status}: {response_text}"
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
# Check for error response
|
|
258
|
+
if not (200 <= response.status < 300):
|
|
259
|
+
error_message = (
|
|
260
|
+
response_json.get("message", response_json)
|
|
261
|
+
if isinstance(response_json, dict)
|
|
262
|
+
else response_text
|
|
263
|
+
)
|
|
264
|
+
raise ValueError(
|
|
265
|
+
f"Request failed with status {response.status}: {error_message}"
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
return response_json
|
|
269
|
+
|
|
270
|
+
def is_authenticated(self) -> bool:
|
|
271
|
+
"""
|
|
272
|
+
Check if the client is authenticated
|
|
273
|
+
|
|
274
|
+
Returns:
|
|
275
|
+
True if authenticated
|
|
276
|
+
"""
|
|
277
|
+
return self._authenticated and self.token is not None
|
|
278
|
+
|
|
279
|
+
def logout(self) -> None:
|
|
280
|
+
"""
|
|
281
|
+
Logout and clear authentication state
|
|
282
|
+
"""
|
|
283
|
+
self.token = None
|
|
284
|
+
self._authenticated = False
|
|
285
|
+
|
|
286
|
+
def get_tenant_id(self) -> str:
|
|
287
|
+
"""
|
|
288
|
+
Get the current tenant ID
|
|
289
|
+
|
|
290
|
+
Returns:
|
|
291
|
+
Tenant ID or empty string if not authenticated or not implemented
|
|
292
|
+
"""
|
|
293
|
+
return self.pb.auth_store.model.tenant
|
|
294
|
+
|
|
295
|
+
def get_user_id(self) -> str:
|
|
296
|
+
"""
|
|
297
|
+
Get the current User ID
|
|
298
|
+
|
|
299
|
+
Returns:
|
|
300
|
+
User ID or empty string if not authenticated or not implemented
|
|
301
|
+
"""
|
|
302
|
+
return self.pb.auth_store.model.id
|
|
303
|
+
|
|
304
|
+
def get_file_token(self) -> str:
|
|
305
|
+
"""
|
|
306
|
+
Get the current file token
|
|
307
|
+
"""
|
|
308
|
+
return self.pb.get_file_token()
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Managers for TestZeus SDK.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
# Import all manager classes
|
|
6
|
+
from .base import BaseManager
|
|
7
|
+
from .tenants_manager import TenantsManager
|
|
8
|
+
from .users_manager import UsersManager
|
|
9
|
+
from .agent_configs_manager import AgentConfigsManager
|
|
10
|
+
from .environment_manager import EnvironmentManager
|
|
11
|
+
from .tags_manager import TagsManager
|
|
12
|
+
from .tenant_consumption_manager import TenantConsumptionManager
|
|
13
|
+
from .tenant_consumption_logs_manager import TenantConsumptionLogsManager
|
|
14
|
+
from .test_data_manager import TestDataManager
|
|
15
|
+
from .test_designs_manager import TestDesignsManager
|
|
16
|
+
from .test_device_manager import TestDeviceManager
|
|
17
|
+
from .test_run_dash_output_steps_manager import TestRunDashOutputStepsManager
|
|
18
|
+
from .test_run_dash_outputs_manager import TestRunDashOutputsManager
|
|
19
|
+
from .test_run_dash_outputs_attachments_manager import TestRunDashOutputsAttachmentsManager
|
|
20
|
+
from .test_run_dashs_manager import TestRunDashsManager
|
|
21
|
+
from .test_run_reports_manager import TestRunReportsManager
|
|
22
|
+
from .test_runs_manager import TestRunsManager
|
|
23
|
+
from .test_runs_stage_manager import TestRunsStageManager
|
|
24
|
+
from .tests_manager import TestsManager
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Manager for agent_configs collection.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Dict, List, Any, Optional, Union
|
|
6
|
+
from testzeus_sdk.models.agent_configs import AgentConfigs
|
|
7
|
+
from testzeus_sdk.client import TestZeusClient
|
|
8
|
+
from .base import BaseManager
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AgentConfigsManager(BaseManager):
|
|
12
|
+
"""
|
|
13
|
+
Manager for AgentConfigs resources
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, client: TestZeusClient) -> None:
|
|
17
|
+
"""
|
|
18
|
+
Initialize the AgentConfigs manager
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
client: TestZeus client instance
|
|
22
|
+
"""
|
|
23
|
+
super().__init__(client, "agent_configs", AgentConfigs)
|
|
24
|
+
|
|
25
|
+
def _process_references(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
26
|
+
"""
|
|
27
|
+
Process name-based references to ID-based references
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
data: Entity data with potential name-based references
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
Processed data with ID-based references
|
|
34
|
+
"""
|
|
35
|
+
from testzeus_sdk.utils.helpers import convert_name_refs_to_ids
|
|
36
|
+
|
|
37
|
+
# Define which fields are relations and what collections they reference
|
|
38
|
+
ref_fields = {
|
|
39
|
+
"tenant": "pbc_138639755",
|
|
40
|
+
"modified_by": "_pb_users_auth_",
|
|
41
|
+
"tags": "pbc_1219621782",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return convert_name_refs_to_ids(self.client, data, ref_fields)
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Base manager class for TestZeus entity operations.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Dict, Any, Optional, List, TypeVar, Generic, Type, Union
|
|
6
|
+
from testzeus_sdk.client import TestZeusClient
|
|
7
|
+
from testzeus_sdk.models.base import BaseModel
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
T = TypeVar("T", bound=BaseModel)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def record_to_dict(record: Any) -> Dict[str, Any]:
|
|
14
|
+
"""
|
|
15
|
+
Convert a PocketBase Record to a dictionary.
|
|
16
|
+
Attempts multiple approaches to ensure compatibility with different PocketBase libraries.
|
|
17
|
+
"""
|
|
18
|
+
if hasattr(record, "to_dict") and callable(record.to_dict):
|
|
19
|
+
return record.to_dict()
|
|
20
|
+
elif hasattr(record, "export") and callable(record.export):
|
|
21
|
+
return record.export()
|
|
22
|
+
elif hasattr(record, "__dict__"):
|
|
23
|
+
return record.__dict__
|
|
24
|
+
else:
|
|
25
|
+
# As a last resort, try converting all attributes to a dict
|
|
26
|
+
return {
|
|
27
|
+
key: getattr(record, key)
|
|
28
|
+
for key in dir(record)
|
|
29
|
+
if not key.startswith("_") and not callable(getattr(record, key))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class BaseManager(Generic[T]):
|
|
34
|
+
"""
|
|
35
|
+
Base manager class for all TestZeus entities.
|
|
36
|
+
|
|
37
|
+
This class provides common CRUD operations for all entity types.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self, client: TestZeusClient, collection_name: str, model_class: Type[T]
|
|
42
|
+
) -> None:
|
|
43
|
+
"""
|
|
44
|
+
Initialize a manager for a specific entity type.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
client: TestZeus client instance
|
|
48
|
+
collection_name: Name of the PocketBase collection
|
|
49
|
+
model_class: Model class for this entity type
|
|
50
|
+
"""
|
|
51
|
+
self.client = client
|
|
52
|
+
self.collection_name = collection_name
|
|
53
|
+
self.model_class = model_class
|
|
54
|
+
|
|
55
|
+
async def get_list(
|
|
56
|
+
self,
|
|
57
|
+
page: int = 1,
|
|
58
|
+
per_page: int = 30,
|
|
59
|
+
filters: Optional[Dict[str, Any]] = None,
|
|
60
|
+
sort: Optional[Union[str, List[str]]] = None,
|
|
61
|
+
expand: Optional[Union[str, List[str]]] = None,
|
|
62
|
+
) -> Dict[str, Any]:
|
|
63
|
+
"""
|
|
64
|
+
Get a list of entities with optional filtering.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
page: Page number (1-based)
|
|
68
|
+
per_page: Number of items per page
|
|
69
|
+
filters: Dictionary of filter conditions
|
|
70
|
+
sort: Field(s) to sort by (prefix with '-' for descending order)
|
|
71
|
+
expand: Related collection(s) to expand
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
Dictionary containing items and pagination info
|
|
75
|
+
"""
|
|
76
|
+
await self.client.ensure_authenticated()
|
|
77
|
+
filter_str = self._build_filter_string(filters) if filters else None
|
|
78
|
+
|
|
79
|
+
# Prepare the sort parameter
|
|
80
|
+
sort_str = None
|
|
81
|
+
if sort:
|
|
82
|
+
if isinstance(sort, list):
|
|
83
|
+
sort_str = ",".join(sort)
|
|
84
|
+
else:
|
|
85
|
+
sort_str = sort
|
|
86
|
+
|
|
87
|
+
# Prepare the expand parameter
|
|
88
|
+
expand_str = None
|
|
89
|
+
if expand:
|
|
90
|
+
if isinstance(expand, list):
|
|
91
|
+
expand_str = ",".join(expand)
|
|
92
|
+
else:
|
|
93
|
+
expand_str = expand
|
|
94
|
+
|
|
95
|
+
result = self.client.pb.collection(self.collection_name).get_list(
|
|
96
|
+
page, per_page, query_params= {'filter':filter_str, 'sort': sort_str, 'expand': expand_str}
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
# Convert items to model instances
|
|
100
|
+
items = [self.model_class(record_to_dict(item)) for item in result.items]
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
"items": items,
|
|
104
|
+
"page": result.page,
|
|
105
|
+
"per_page": result.per_page,
|
|
106
|
+
"total_items": result.total_items,
|
|
107
|
+
"total_pages": result.total_pages,
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async def get_one(self, id_or_name: str, expand: str | List[str] = None) -> T:
|
|
111
|
+
"""
|
|
112
|
+
Get a single entity by ID or name.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
id_or_name: Entity ID or name
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
Entity model instance
|
|
119
|
+
"""
|
|
120
|
+
await self.client.ensure_authenticated()
|
|
121
|
+
|
|
122
|
+
expand_str = None
|
|
123
|
+
if expand:
|
|
124
|
+
if isinstance(expand, list):
|
|
125
|
+
expand_str = ",".join(expand)
|
|
126
|
+
else:
|
|
127
|
+
expand_str = expand
|
|
128
|
+
|
|
129
|
+
# Check if the provided string is an ID or name
|
|
130
|
+
if self._is_valid_id(id_or_name):
|
|
131
|
+
result = self.client.pb.collection(self.collection_name).get_one(id_or_name, query_params={'expand': expand_str})
|
|
132
|
+
else:
|
|
133
|
+
# Assume it's a name and try to find it
|
|
134
|
+
tenant_id = self.client.get_tenant_id()
|
|
135
|
+
if not tenant_id:
|
|
136
|
+
raise ValueError(
|
|
137
|
+
"User must be authenticated with a tenant to find by name"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
filter_str = f'name = "{id_or_name}" && tenant = "{tenant_id}"'
|
|
141
|
+
result = self.client.pb.collection(
|
|
142
|
+
self.collection_name
|
|
143
|
+
).get_first_list_item(filter_str)
|
|
144
|
+
|
|
145
|
+
return self.model_class(record_to_dict(result))
|
|
146
|
+
|
|
147
|
+
async def create(self, data: Dict[str, Any]) -> T:
|
|
148
|
+
"""
|
|
149
|
+
Create a new entity.
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
data: Entity data
|
|
153
|
+
|
|
154
|
+
Returns:
|
|
155
|
+
Created entity model instance
|
|
156
|
+
"""
|
|
157
|
+
await self.client.ensure_authenticated()
|
|
158
|
+
# Add tenant if not provided
|
|
159
|
+
if "tenant" not in data:
|
|
160
|
+
tenant_id = self.client.get_tenant_id()
|
|
161
|
+
if tenant_id:
|
|
162
|
+
data["tenant"] = tenant_id
|
|
163
|
+
|
|
164
|
+
# Add modified_by if not provided
|
|
165
|
+
if "modified_by" not in data and self.client.is_authenticated():
|
|
166
|
+
data["modified_by"] = self.client.get_user_id()
|
|
167
|
+
|
|
168
|
+
# Process name-based references
|
|
169
|
+
processed_data = self._process_references(data)
|
|
170
|
+
|
|
171
|
+
result = self.client.pb.collection(self.collection_name).create(processed_data)
|
|
172
|
+
return self.model_class(record_to_dict(result))
|
|
173
|
+
|
|
174
|
+
async def update(self, id_or_name: str, data: Dict[str, Any]) -> T:
|
|
175
|
+
"""
|
|
176
|
+
Update an existing entity.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
id_or_name: Entity ID or name
|
|
180
|
+
data: Updated entity data
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
Updated entity model instance
|
|
184
|
+
"""
|
|
185
|
+
await self.client.ensure_authenticated()
|
|
186
|
+
# Add tenant if not provided
|
|
187
|
+
if "tenant" not in data:
|
|
188
|
+
tenant_id = self.client.get_tenant_id()
|
|
189
|
+
if tenant_id:
|
|
190
|
+
data["tenant"] = tenant_id
|
|
191
|
+
|
|
192
|
+
# Add modified_by if not provided
|
|
193
|
+
if "modified_by" not in data and self.client.is_authenticated():
|
|
194
|
+
data["modified_by"] = self.client.get_user_id()
|
|
195
|
+
|
|
196
|
+
# Process name-based references
|
|
197
|
+
processed_data = self._process_references(data)
|
|
198
|
+
|
|
199
|
+
# Get the ID if a name was provided
|
|
200
|
+
entity_id = await self._get_id_from_name_or_id(id_or_name)
|
|
201
|
+
|
|
202
|
+
result = self.client.pb.collection(self.collection_name).update(
|
|
203
|
+
entity_id, processed_data
|
|
204
|
+
)
|
|
205
|
+
return self.model_class(record_to_dict(result))
|
|
206
|
+
|
|
207
|
+
async def delete(self, id_or_name: str) -> bool:
|
|
208
|
+
"""
|
|
209
|
+
Delete an entity.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
id_or_name: Entity ID or name
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
True if deletion was successful
|
|
216
|
+
"""
|
|
217
|
+
await self.client.ensure_authenticated()
|
|
218
|
+
# Get the ID if a name was provided
|
|
219
|
+
entity_id = await self._get_id_from_name_or_id(id_or_name)
|
|
220
|
+
|
|
221
|
+
return self.client.pb.collection(self.collection_name).delete(entity_id)
|
|
222
|
+
|
|
223
|
+
def _process_references(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
224
|
+
"""
|
|
225
|
+
Process name-based references to ID-based references.
|
|
226
|
+
|
|
227
|
+
This is a placeholder that should be overridden by subclasses
|
|
228
|
+
to handle entity-specific reference fields.
|
|
229
|
+
|
|
230
|
+
Args:
|
|
231
|
+
data: Entity data with potential name-based references
|
|
232
|
+
|
|
233
|
+
Returns:
|
|
234
|
+
Processed data with ID-based references
|
|
235
|
+
"""
|
|
236
|
+
# Base implementation does nothing
|
|
237
|
+
return data.copy()
|
|
238
|
+
|
|
239
|
+
async def _get_id_from_name_or_id(self, id_or_name: str) -> str:
|
|
240
|
+
"""
|
|
241
|
+
Get entity ID from name or ID.
|
|
242
|
+
|
|
243
|
+
Args:
|
|
244
|
+
id_or_name: Entity ID or name
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
Entity ID
|
|
248
|
+
"""
|
|
249
|
+
if self._is_valid_id(id_or_name):
|
|
250
|
+
return id_or_name
|
|
251
|
+
|
|
252
|
+
# Try to find the entity by name
|
|
253
|
+
try:
|
|
254
|
+
entity = await self.get_one(id_or_name)
|
|
255
|
+
return entity.id
|
|
256
|
+
except Exception as e:
|
|
257
|
+
raise ValueError(
|
|
258
|
+
f"Could not find {self.collection_name} with name: {id_or_name}"
|
|
259
|
+
) from e
|
|
260
|
+
|
|
261
|
+
@staticmethod
|
|
262
|
+
def _is_valid_id(id_str: str) -> bool:
|
|
263
|
+
"""
|
|
264
|
+
Check if a string is a valid ID.
|
|
265
|
+
|
|
266
|
+
For PocketBase, IDs are typically 15 characters alphanumeric.
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
id_str: String to check
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
True if string is a valid ID
|
|
273
|
+
"""
|
|
274
|
+
return len(id_str) == 15 and id_str.isalnum()
|
|
275
|
+
|
|
276
|
+
@staticmethod
|
|
277
|
+
def _build_filter_string(filters: Dict[str, Any]) -> str:
|
|
278
|
+
"""
|
|
279
|
+
Build a filter string from a dictionary of filters.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
filters: Dictionary of filter conditions
|
|
283
|
+
|
|
284
|
+
Returns:
|
|
285
|
+
Filter string for PocketBase API
|
|
286
|
+
"""
|
|
287
|
+
conditions = []
|
|
288
|
+
|
|
289
|
+
for key, value in filters.items():
|
|
290
|
+
if isinstance(value, list):
|
|
291
|
+
# Handle list values (e.g., tags)
|
|
292
|
+
or_conditions = [f'{key} = "{item}"' for item in value]
|
|
293
|
+
conditions.append(f"({' || '.join(or_conditions)})")
|
|
294
|
+
elif isinstance(value, bool):
|
|
295
|
+
# Handle boolean values
|
|
296
|
+
conditions.append(f"{key} = {str(value).lower()}")
|
|
297
|
+
elif isinstance(value, (int, float)):
|
|
298
|
+
# Handle numeric values
|
|
299
|
+
conditions.append(f"{key} = {value}")
|
|
300
|
+
else:
|
|
301
|
+
# Handle string values
|
|
302
|
+
conditions.append(f'{key} = "{value}"')
|
|
303
|
+
|
|
304
|
+
return " && ".join(conditions)
|