Skip to content

Commit a0def5f

Browse files
committed
Create OpaClient as part of server lifecycle
1 parent a7ae4a4 commit a0def5f

2 files changed

Lines changed: 24 additions & 2 deletions

File tree

src/blueapi/service/main.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
from blueapi.worker import TrackableTask, WorkerState
4141
from blueapi.worker.event import TaskStatusEnum
4242

43+
from .authorization import OpaClient
4344
from .model import (
4445
DeviceModel,
4546
DeviceResponse,
@@ -93,8 +94,13 @@ def teardown_runner():
9394
def lifespan(config: ApplicationConfig):
9495
@asynccontextmanager
9596
async def inner(app: FastAPI):
97+
if not (meta := config.env.metadata):
98+
raise ValueError("Instrument name is required in metadata")
99+
96100
setup_runner(config)
97-
yield
101+
async with OpaClient.for_config(meta.instrument, config.opa) as opa:
102+
app.state.authz = opa
103+
yield
98104
teardown_runner()
99105

100106
return inner

tests/unit_tests/service/test_main.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from unittest import mock
2-
from unittest.mock import Mock, call
2+
from unittest.mock import Mock, call, patch
33

44
import pytest
55
from fastapi import FastAPI, Request
@@ -10,6 +10,7 @@
1010
from blueapi.service.main import (
1111
add_version_headers,
1212
get_passthrough_headers,
13+
lifespan,
1314
log_request_details,
1415
)
1516

@@ -79,3 +80,18 @@ def test_get_passthrough_headers(
7980
request = Mock(spec=Request)
8081
request.headers = headers
8182
assert get_passthrough_headers(request) == expected_headers
83+
84+
85+
@patch("blueapi.service.main.teardown_runner")
86+
@patch("blueapi.service.main.setup_runner")
87+
async def test_lifespan(setup: Mock, teardown: Mock):
88+
conf = ApplicationConfig()
89+
lifespan_fn = lifespan(conf)
90+
91+
app = Mock()
92+
93+
async with lifespan_fn(app):
94+
setup.assert_called_once_with(conf)
95+
teardown.assert_not_called()
96+
97+
teardown.assert_called_once()

0 commit comments

Comments
 (0)