File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 4040from blueapi .worker import TrackableTask , WorkerState
4141from blueapi .worker .event import TaskStatusEnum
4242
43+ from .authorization import OpaClient
4344from .model import (
4445 DeviceModel ,
4546 DeviceResponse ,
@@ -93,8 +94,13 @@ def teardown_runner():
9394def 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
Original file line number Diff line number Diff line change 11from unittest import mock
2- from unittest .mock import Mock , call
2+ from unittest .mock import Mock , call , patch
33
44import pytest
55from fastapi import FastAPI , Request
1010from 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 ()
You can’t perform that action at this time.
0 commit comments