|
| 1 | +import asyncio |
| 2 | +import threading |
| 3 | +from collections.abc import AsyncIterator |
| 4 | + |
| 5 | +import grpc |
| 6 | +import pytest |
| 7 | +from grpclib.server import Server |
| 8 | + |
| 9 | +from tests.output_betterproto.simple_service import ( |
| 10 | + Request, |
| 11 | + Response, |
| 12 | + SimpleServiceBase, |
| 13 | + SimpleServiceSyncStub, |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +class SimpleService(SimpleServiceBase): |
| 18 | + async def get_unary_unary(self, message: "Request") -> "Response": |
| 19 | + return Response(message=f"Hello {message.value}") |
| 20 | + |
| 21 | + async def get_unary_stream(self, message: "Request") -> "AsyncIterator[Response]": |
| 22 | + for i in range(5): |
| 23 | + yield Response(message=f"Hello {message.value} {i}") |
| 24 | + |
| 25 | + async def get_stream_unary(self, messages: "AsyncIterator[Request]") -> "Response": |
| 26 | + s = 0 |
| 27 | + async for m in messages: |
| 28 | + s += m.value |
| 29 | + return Response(message=f"Hello {s}") |
| 30 | + |
| 31 | + async def get_stream_stream(self, messages: "AsyncIterator[Request]") -> "AsyncIterator[Response]": |
| 32 | + async for message in messages: |
| 33 | + yield Response(message=f"Hello {message.value}") |
| 34 | + |
| 35 | + |
| 36 | +@pytest.mark.asyncio |
| 37 | +async def test_sync_client(): |
| 38 | + def start_server(): |
| 39 | + async def run_server(): |
| 40 | + server = Server([SimpleService()]) |
| 41 | + await server.start("127.0.0.1", 1234) |
| 42 | + await asyncio.sleep(3) # Close the server after 3 seconds |
| 43 | + server.close() |
| 44 | + |
| 45 | + loop = asyncio.new_event_loop() |
| 46 | + loop.run_until_complete(run_server()) |
| 47 | + loop.close() |
| 48 | + |
| 49 | + # We need to start the server in a new thread to avoid a deadlock |
| 50 | + server_thread = threading.Thread(target=start_server) |
| 51 | + server_thread.start() |
| 52 | + |
| 53 | + # Create a sync client |
| 54 | + with grpc.insecure_channel("localhost:1234") as channel: |
| 55 | + client = SimpleServiceSyncStub(channel) |
| 56 | + |
| 57 | + response = client.get_unary_unary(Request(value=42)) |
| 58 | + assert response.message == "Hello 42" |
| 59 | + |
| 60 | + response = client.get_unary_stream(Request(value=42)) |
| 61 | + assert [r.message for r in response] == [f"Hello 42 {i}" for i in range(5)] |
| 62 | + |
| 63 | + response = client.get_stream_unary([Request(value=i) for i in range(5)]) |
| 64 | + assert response.message == "Hello 10" |
| 65 | + |
| 66 | + response = client.get_stream_stream([Request(value=i) for i in range(5)]) |
| 67 | + assert [r.message for r in response] == [f"Hello {i}" for i in range(5)] |
| 68 | + |
| 69 | + # Create an async client |
| 70 | + # client = SimpleServiceStub(Channel(host="127.0.0.1", port=1234)) |
| 71 | + # response = await client.get_unary_unary(Request(value=42)) |
| 72 | + # assert response.message == "Hello 42" |
0 commit comments