|
| 1 | +import uuid |
| 2 | + |
| 3 | +import httpx |
| 4 | +import nexusrpc |
| 5 | +import nexusrpc.handler |
| 6 | + |
| 7 | +from temporalio.client import Client |
| 8 | +from temporalio.worker import Worker |
| 9 | +from tests.helpers.nexus import create_nexus_endpoint |
| 10 | + |
| 11 | +HTTP_PORT = 7243 |
| 12 | + |
| 13 | + |
| 14 | +def make_incrementer_service(op_names: list[str]) -> tuple[type, type]: |
| 15 | + # |
| 16 | + # service contract |
| 17 | + # |
| 18 | + |
| 19 | + # TODO(dan): does this work with just nexusrpc.contract.Operation[int, int] |
| 20 | + op_contracts = { |
| 21 | + name: nexusrpc.contract.Operation[int, int](name=name) for name in op_names |
| 22 | + } |
| 23 | + contract_cls = nexusrpc.contract.service(type("ServiceContract", (), op_contracts)) |
| 24 | + |
| 25 | + # |
| 26 | + # service impl |
| 27 | + # |
| 28 | + async def _increment_op( |
| 29 | + self, |
| 30 | + ctx: nexusrpc.handler.StartOperationContext, |
| 31 | + input: int, |
| 32 | + ) -> int: |
| 33 | + return input + 1 |
| 34 | + |
| 35 | + op_factories = { |
| 36 | + name: nexusrpc.handler.sync_operation(_increment_op) for name in op_names |
| 37 | + } |
| 38 | + |
| 39 | + impl_cls = nexusrpc.handler.service(contract=contract_cls)( |
| 40 | + type("ServiceImpl", (), op_factories) |
| 41 | + ) |
| 42 | + |
| 43 | + return contract_cls, impl_cls |
| 44 | + |
| 45 | + |
| 46 | +async def test_handler_creation_at_run_time(client: Client): |
| 47 | + task_queue = str(uuid.uuid4()) |
| 48 | + |
| 49 | + contract_cls, impl_cls = make_incrementer_service(["increment"]) |
| 50 | + |
| 51 | + service = contract_cls.__name__ |
| 52 | + endpoint = (await create_nexus_endpoint(task_queue, client)).endpoint.id |
| 53 | + async with Worker( |
| 54 | + client, |
| 55 | + task_queue=task_queue, |
| 56 | + nexus_services=[impl_cls()], |
| 57 | + ): |
| 58 | + async with httpx.AsyncClient() as http_client: |
| 59 | + response = await http_client.post( |
| 60 | + f"http://127.0.0.1:{HTTP_PORT}/nexus/endpoints/{endpoint}/services/{service}/increment", |
| 61 | + json=1, |
| 62 | + headers={}, |
| 63 | + ) |
| 64 | + print(f"\n\n{response.json()}\n\n") |
| 65 | + |
| 66 | + assert response.status_code == 200 |
| 67 | + assert response.json() == 2 |
0 commit comments