UnisKB/scripts/check_local_runtime_api.py

33 lines
1.8 KiB
Python
Raw Normal View History

"""Exercise the signed API under the actual minimal model-service app configuration."""
import os
from pathlib import Path
import sys
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'apps'))
os.environ['SERVER_NAME'] = 'local_model'
os.environ['MAXKB_RUNTIME_AUTOSTART'] = '0'
from django.conf import settings
settings.configure(SECRET_KEY='test-only', AUTH_HANDLES=[], USE_I18N=False,
INSTALLED_APPS=['django.contrib.contenttypes', 'local_model'],
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}})
import django
django.setup()
from rest_framework.test import APIRequestFactory
from common.model_runtime_client import signed_request
from local_model.views.runtime import LocalModelRuntime
factory = APIRequestFactory()
with patch('common.model_runtime_client._secret', return_value=b'test-only'), patch('local_model.views.runtime.manager') as manager:
manager.status.return_value = {'status': 'UNLOADED'}
body, signature = signed_request({'operation': 'status', 'model_id': '00000000-0000-4000-8000-000000000001'})
response = LocalModelRuntime.as_view()(factory.post('/model_runtime', data=body,
content_type='application/json', HTTP_X_MODEL_RUNTIME_SIGNATURE=signature))
assert response.status_code == 200, response.content
manager.status.assert_called_once()
manager.reset_mock()
response = LocalModelRuntime.as_view()(factory.post('/model_runtime', data=body, content_type='application/json'))
assert response.status_code == 403, response.status_code
manager.status.assert_not_called()
print('Minimal model-service API: signed request accepted; unsigned request rejected')