nomadro/apps/api/tests/test_pb_client.py

92 lines
3.6 KiB
Python

"""Credential recovery and concurrency tests; no live PocketBase calls."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
import threading
import unittest
import httpx
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services'))
from nomadro_pb.client import PocketBaseClient, PocketBaseError
class PocketBaseClientTests(unittest.TestCase):
def client(self, handler):
client = PocketBaseClient(base_url='https://pb.invalid', email='test', password='test')
client._client = httpx.Client(transport=httpx.MockTransport(handler))
self.addCleanup(client._client.close)
return client
def test_concurrent_calls_share_one_authentication(self):
auth_calls = []
barrier = threading.Barrier(8)
def handler(request):
auth_calls.append(request.url.path)
return httpx.Response(200, json={'token': 'shared'})
client = self.client(handler)
def token(_):
barrier.wait(timeout=5)
return client.admin_token()
with ThreadPoolExecutor(max_workers=8) as pool:
self.assertEqual(list(pool.map(token, range(8))), ['shared'] * 8)
self.assertEqual(len(auth_calls), 1)
def test_expired_credential_refreshes_once_and_preserves_write(self):
writes = []
auth_calls = []
def handler(request):
if request.url.path.endswith('auth-with-password'):
auth_calls.append(request)
return httpx.Response(200, json={'token': f'token-{len(auth_calls)}'})
writes.append((request.headers['Authorization'], request.content))
return httpx.Response(401 if len(writes) == 1 else 200, json={'id': 'saved'})
client = self.client(handler)
self.assertEqual(client.create('records', {'title': 'hello'}), {'id': 'saved'})
self.assertEqual([token for token, _ in writes], ['token-1', 'token-2'])
self.assertEqual(writes[0][1], writes[1][1])
def test_repeated_unauthorized_response_stops_after_one_retry(self):
writes = []
def handler(request):
if request.url.path.endswith('auth-with-password'):
return httpx.Response(200, json={'token': 'rejected'})
writes.append(request)
return httpx.Response(401, json={'message': 'rejected'})
with self.assertRaises(PocketBaseError):
self.client(handler).create('records', {'title': 'hello'})
self.assertEqual(len(writes), 2)
def test_server_errors_and_timeouts_do_not_replay_writes(self):
for failure in [403, 500, 'timeout']:
with self.subTest(failure=failure):
writes = []
def handler(request):
if request.url.path.endswith('auth-with-password'):
return httpx.Response(200, json={'token': 'valid'})
writes.append(request)
if failure == 'timeout':
raise httpx.ReadTimeout('timeout', request=request)
return httpx.Response(failure, json={'message': 'failed'})
with self.assertRaises((PocketBaseError, httpx.ReadTimeout)):
self.client(handler).create('records', {'title': 'hello'})
self.assertEqual(len(writes), 1)
def test_legacy_admin_endpoint_remains_supported(self):
def handler(request):
if '/_superusers/' in request.url.path:
return httpx.Response(404, json={})
return httpx.Response(200, json={'token': 'legacy'})
self.assertEqual(self.client(handler).admin_token(), 'legacy')