Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-primitive.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Dan Q Consolidate duplicate QUICKSTARTs on the top-level file 503f830 7 months ago History
test_blog.py · 10.7 KB · 409 lines
1"""
2Test the blog system endpoint.
3
4Tests:
5- Create post
6- List posts
7- Get specific post
8- Update post
9- Delete post
10- Pagination
11- Filtering by author
12- Search
13"""
14
15import requests
16import json
17
18BASE_URL = 'http://localhost:8001'
19
20# Mock token for testing (in production, get from auth system)
21MOCK_TOKEN = 'demo_token_12345678901234567890'
22
23
24def test_create_post():
25 """Test creating a blog post."""
26 print('\n=== Test 1: Create Post ===')
27
28 response = requests.post(
29 f'{BASE_URL}/objects/advanced_blog',
30 json={
31 'token': MOCK_TOKEN,
32 'title': 'My First Post',
33 'content': 'This is my first blog post using the Object Primitive System!',
34 'tags': ['introduction', 'first-post'],
35 }
36 )
37
38 print(f'Status: {response.status_code}')
39 data = response.json()
40 print(f'Response: {json.dumps(data, indent=2)}')
41
42 assert response.status_code == 200
43 assert data['status'] == 'ok'
44 assert 'post_id' in data
45 assert data['title'] == 'My First Post'
46
47 print('✅ Post creation works')
48 return data['post_id']
49
50
51def test_create_multiple_posts():
52 """Test creating multiple posts."""
53 print('\n=== Test 2: Create Multiple Posts ===')
54
55 posts = [
56 {
57 'title': 'Getting Started with Object Primitives',
58 'content': 'Learn how to build applications using the Object Primitive paradigm...',
59 'tags': ['tutorial', 'beginner'],
60 },
61 {
62 'title': 'Advanced Auth Patterns',
63 'content': 'Deep dive into authentication and authorization patterns...',
64 'tags': ['tutorial', 'security'],
65 },
66 {
67 'title': 'Building a Blog',
68 'content': 'Step by step guide to building a blog system...',
69 'tags': ['tutorial', 'project'],
70 },
71 ]
72
73 post_ids = []
74 for post in posts:
75 response = requests.post(
76 f'{BASE_URL}/objects/advanced_blog',
77 json={'token': MOCK_TOKEN, **post}
78 )
79 data = response.json()
80 assert data['status'] == 'ok'
81 post_ids.append(data['post_id'])
82
83 print(f'Created {len(post_ids)} posts')
84 print('✅ Multiple post creation works')
85 return post_ids
86
87
88def test_list_posts():
89 """Test listing all posts."""
90 print('\n=== Test 3: List Posts ===')
91
92 response = requests.get(f'{BASE_URL}/objects/advanced_blog')
93
94 print(f'Status: {response.status_code}')
95 data = response.json()
96 print(f'Response: {json.dumps(data, indent=2)}')
97
98 assert response.status_code == 200
99 assert data['status'] == 'ok'
100 assert 'posts' in data
101 assert len(data['posts']) >= 4 # We created 4 posts
102 assert 'pagination' in data
103
104 print(f'Found {len(data["posts"])} posts (total: {data["pagination"]["total"]})')
105 print('✅ Post listing works')
106
107
108def test_get_specific_post(post_id):
109 """Test getting a specific post."""
110 print('\n=== Test 4: Get Specific Post ===')
111
112 response = requests.get(
113 f'{BASE_URL}/objects/advanced_blog',
114 params={'id': post_id}
115 )
116
117 print(f'Status: {response.status_code}')
118 data = response.json()
119 print(f'Response: {json.dumps(data, indent=2)}')
120
121 assert response.status_code == 200
122 assert data['status'] == 'ok'
123 assert 'post' in data
124 assert data['post']['id'] == post_id
125 assert 'title' in data['post']
126 assert 'content' in data['post']
127 assert 'author' in data['post']
128
129 print('✅ Specific post retrieval works')
130
131
132def test_update_post(post_id):
133 """Test updating a post."""
134 print('\n=== Test 5: Update Post ===')
135
136 response = requests.put(
137 f'{BASE_URL}/objects/advanced_blog',
138 json={
139 'token': MOCK_TOKEN,
140 'id': post_id,
141 'title': 'My First Post (Updated)',
142 'content': 'This is my updated blog post!',
143 }
144 )
145
146 print(f'Status: {response.status_code}')
147 data = response.json()
148 print(f'Response: {json.dumps(data, indent=2)}')
149
150 assert response.status_code == 200
151 assert data['status'] == 'ok'
152
153 # Verify update
154 response = requests.get(
155 f'{BASE_URL}/objects/advanced_blog',
156 params={'id': post_id}
157 )
158 data = response.json()
159 assert data['post']['title'] == 'My First Post (Updated)'
160 assert data['post']['content'] == 'This is my updated blog post!'
161
162 print('✅ Post update works')
163
164
165def test_pagination():
166 """Test pagination."""
167 print('\n=== Test 6: Pagination ===')
168
169 # Get first 2 posts
170 response = requests.get(
171 f'{BASE_URL}/objects/advanced_blog',
172 params={'limit': '2', 'offset': '0'}
173 )
174
175 print(f'Status: {response.status_code}')
176 data = response.json()
177 print(f'Response: {json.dumps(data, indent=2)}')
178
179 assert response.status_code == 200
180 assert data['status'] == 'ok'
181 assert len(data['posts']) <= 2
182 assert data['pagination']['limit'] == 2
183 assert data['pagination']['offset'] == 0
184 assert 'has_more' in data['pagination']
185
186 # Get next 2 posts
187 response = requests.get(
188 f'{BASE_URL}/objects/advanced_blog',
189 params={'limit': '2', 'offset': '2'}
190 )
191 data = response.json()
192 assert len(data['posts']) <= 2
193
194 print('✅ Pagination works')
195
196
197def test_filter_by_author():
198 """Test filtering by author."""
199 print('\n=== Test 7: Filter by Author ===')
200
201 response = requests.get(
202 f'{BASE_URL}/objects/advanced_blog',
203 params={'author': 'demo_user'}
204 )
205
206 print(f'Status: {response.status_code}')
207 data = response.json()
208 print(f'Response: {json.dumps(data, indent=2)}')
209
210 assert response.status_code == 200
211 assert data['status'] == 'ok'
212
213 # All posts should be by demo_user
214 for post in data['posts']:
215 assert post['author'] == 'demo_user'
216
217 print(f'Found {len(data["posts"])} posts by demo_user')
218 print('✅ Author filtering works')
219
220
221def test_search():
222 """Test search functionality."""
223 print('\n=== Test 8: Search ===')
224
225 response = requests.get(
226 f'{BASE_URL}/objects/advanced_blog',
227 params={'search': 'tutorial'}
228 )
229
230 print(f'Status: {response.status_code}')
231 data = response.json()
232 print(f'Response: {json.dumps(data, indent=2)}')
233
234 assert response.status_code == 200
235 assert data['status'] == 'ok'
236
237 # Should find posts with "tutorial" in title or content
238 print(f'Found {len(data["posts"])} posts matching "tutorial"')
239
240 # Verify results contain search term
241 for post in data['posts']:
242 assert 'tutorial' in post['title'].lower() or 'tutorial' in post['excerpt'].lower()
243
244 print('✅ Search works')
245
246
247def test_sort_order():
248 """Test different sort orders."""
249 print('\n=== Test 9: Sort Order ===')
250
251 # Test newest first (default)
252 response = requests.get(
253 f'{BASE_URL}/objects/advanced_blog',
254 params={'sort': 'newest'}
255 )
256 data = response.json()
257 posts_newest = data['posts']
258
259 # Test oldest first
260 response = requests.get(
261 f'{BASE_URL}/objects/advanced_blog',
262 params={'sort': 'oldest'}
263 )
264 data = response.json()
265 posts_oldest = data['posts']
266
267 # First post in newest should be last post in oldest (if all posts are shown)
268 if len(posts_newest) > 0 and len(posts_oldest) > 0:
269 print(f'Newest first: {posts_newest[0]["title"]}')
270 print(f'Oldest first: {posts_oldest[0]["title"]}')
271
272 # Test alphabetical by title
273 response = requests.get(
274 f'{BASE_URL}/objects/advanced_blog',
275 params={'sort': 'title'}
276 )
277 data = response.json()
278 posts_alpha = data['posts']
279
280 if len(posts_alpha) > 1:
281 # Verify alphabetical order
282 titles = [p['title'] for p in posts_alpha]
283 assert titles == sorted(titles, key=lambda t: t.lower())
284
285 print('✅ Sorting works')
286
287
288def test_delete_post(post_id):
289 """Test deleting a post."""
290 print('\n=== Test 10: Delete Post ===')
291
292 response = requests.delete(
293 f'{BASE_URL}/objects/advanced_blog',
294 params={'token': MOCK_TOKEN, 'id': post_id}
295 )
296
297 print(f'Status: {response.status_code}')
298 data = response.json()
299 print(f'Response: {json.dumps(data, indent=2)}')
300
301 assert response.status_code == 200
302 assert data['status'] == 'ok'
303
304 # Verify post is deleted
305 response = requests.get(
306 f'{BASE_URL}/objects/advanced_blog',
307 params={'id': post_id}
308 )
309 data = response.json()
310 assert data['status'] == 'error'
311 assert 'not found' in data['message'].lower()
312
313 print('✅ Post deletion works')
314
315
316def test_validation():
317 """Test input validation."""
318 print('\n=== Test 11: Input Validation ===')
319
320 # Test missing title
321 response = requests.post(
322 f'{BASE_URL}/objects/advanced_blog',
323 json={
324 'token': MOCK_TOKEN,
325 'content': 'Content without title',
326 }
327 )
328 data = response.json()
329 assert data['status'] == 'error'
330 assert 'title' in data['message'].lower()
331
332 # Test missing content
333 response = requests.post(
334 f'{BASE_URL}/objects/advanced_blog',
335 json={
336 'token': MOCK_TOKEN,
337 'title': 'Title without content',
338 }
339 )
340 data = response.json()
341 assert data['status'] == 'error'
342 assert 'content' in data['message'].lower()
343
344 # Test missing token
345 response = requests.post(
346 f'{BASE_URL}/objects/advanced_blog',
347 json={
348 'title': 'Test',
349 'content': 'Test content',
350 }
351 )
352 data = response.json()
353 assert data['status'] == 'error'
354 assert 'token' in data['message'].lower()
355
356 print('✅ Input validation works')
357
358
359if __name__ == '__main__':
360 print('Testing Blog System (Object Primitive Style)')
361 print('=' * 50)
362
363 try:
364 # Create first post
365 post_id = test_create_post()
366
367 # Create multiple posts
368 more_post_ids = test_create_multiple_posts()
369
370 # Test listing
371 test_list_posts()
372
373 # Test getting specific post
374 test_get_specific_post(post_id)
375
376 # Test updating post
377 test_update_post(post_id)
378
379 # Test pagination
380 test_pagination()
381
382 # Test filtering
383 test_filter_by_author()
384
385 # Test search
386 test_search()
387
388 # Test sorting
389 test_sort_order()
390
391 # Test deletion
392 test_delete_post(post_id)
393
394 # Test validation
395 test_validation()
396
397 print('\n' + '=' * 50)
398 print('✅ All 11 blog tests passed!')
399 print('=' * 50)
400
401 except AssertionError as e:
402 print(f'\n❌ Test failed: {e}')
403 raise
404 except requests.exceptions.ConnectionError:
405 print('\n❌ Error: Server not running')
406 print('Start server with: python run_server.py')
407 except Exception as e:
408 print(f'\n❌ Unexpected error: {e}')
409 raise